code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def get_stp_mst_detail_output_msti_port_configured_path_cost(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") configured_path_cost = ET.SubElement(port, "configured-path-cost") configured_path_cost.text = kwargs.pop('configured_path_cost') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[get_stp_mst_detail_output_msti_port_configured_path_cost, 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[configured_path_cost] assign[=] call[name[ET].SubElement, parameter[name[port], constant[configured-path-cost]]] name[configured_path_cost].text assign[=] call[name[kwargs].pop, parameter[constant[configured_path_cost]]] 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_configured_path_cost] ( 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[configured_path_cost] = identifier[ET] . identifier[SubElement] ( identifier[port] , literal[string] ) identifier[configured_path_cost] . 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_configured_path_cost(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') configured_path_cost = ET.SubElement(port, 'configured-path-cost') configured_path_cost.text = kwargs.pop('configured_path_cost') callback = kwargs.pop('callback', self._callback) return callback(config)
def save_snapshot(self, context, snapshot_name, save_memory='No'): """ Saves virtual machine to a snapshot :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :param snapshot_name: snapshot name to save to :type snapshot_name: str :param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No :type save_memory: str :return: """ resource_details = self._parse_remote_model(context) created_snapshot_path = self.command_wrapper.execute_command_with_connection(context, self.snapshot_saver.save_snapshot, resource_details.vm_uuid, snapshot_name, save_memory) return set_command_result(created_snapshot_path)
def function[save_snapshot, parameter[self, context, snapshot_name, save_memory]]: constant[ Saves virtual machine to a snapshot :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :param snapshot_name: snapshot name to save to :type snapshot_name: str :param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No :type save_memory: str :return: ] variable[resource_details] assign[=] call[name[self]._parse_remote_model, parameter[name[context]]] variable[created_snapshot_path] assign[=] call[name[self].command_wrapper.execute_command_with_connection, parameter[name[context], name[self].snapshot_saver.save_snapshot, name[resource_details].vm_uuid, name[snapshot_name], name[save_memory]]] return[call[name[set_command_result], parameter[name[created_snapshot_path]]]]
keyword[def] identifier[save_snapshot] ( identifier[self] , identifier[context] , identifier[snapshot_name] , identifier[save_memory] = literal[string] ): literal[string] identifier[resource_details] = identifier[self] . identifier[_parse_remote_model] ( identifier[context] ) identifier[created_snapshot_path] = identifier[self] . identifier[command_wrapper] . identifier[execute_command_with_connection] ( identifier[context] , identifier[self] . identifier[snapshot_saver] . identifier[save_snapshot] , identifier[resource_details] . identifier[vm_uuid] , identifier[snapshot_name] , identifier[save_memory] ) keyword[return] identifier[set_command_result] ( identifier[created_snapshot_path] )
def save_snapshot(self, context, snapshot_name, save_memory='No'): """ Saves virtual machine to a snapshot :param context: resource context of the vCenterShell :type context: models.QualiDriverModels.ResourceCommandContext :param snapshot_name: snapshot name to save to :type snapshot_name: str :param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No :type save_memory: str :return: """ resource_details = self._parse_remote_model(context) created_snapshot_path = self.command_wrapper.execute_command_with_connection(context, self.snapshot_saver.save_snapshot, resource_details.vm_uuid, snapshot_name, save_memory) return set_command_result(created_snapshot_path)
def directory(self, dir_key): '''Initializes directory at dir_key.''' dir_items = self.get(dir_key) if not isinstance(dir_items, list): self.put(dir_key, [])
def function[directory, parameter[self, dir_key]]: constant[Initializes directory at dir_key.] variable[dir_items] assign[=] call[name[self].get, parameter[name[dir_key]]] if <ast.UnaryOp object at 0x7da18f09e9b0> begin[:] call[name[self].put, parameter[name[dir_key], list[[]]]]
keyword[def] identifier[directory] ( identifier[self] , identifier[dir_key] ): literal[string] identifier[dir_items] = identifier[self] . identifier[get] ( identifier[dir_key] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[dir_items] , identifier[list] ): identifier[self] . identifier[put] ( identifier[dir_key] ,[])
def directory(self, dir_key): """Initializes directory at dir_key.""" dir_items = self.get(dir_key) if not isinstance(dir_items, list): self.put(dir_key, []) # depends on [control=['if'], data=[]]
def term_regex(term): """ Returns a case-insensitive regex for searching terms """ return re.compile(r'^{0}$'.format(re.escape(term)), re.IGNORECASE)
def function[term_regex, parameter[term]]: constant[ Returns a case-insensitive regex for searching terms ] return[call[name[re].compile, parameter[call[constant[^{0}$].format, parameter[call[name[re].escape, parameter[name[term]]]]], name[re].IGNORECASE]]]
keyword[def] identifier[term_regex] ( identifier[term] ): literal[string] keyword[return] identifier[re] . identifier[compile] ( literal[string] . identifier[format] ( identifier[re] . identifier[escape] ( identifier[term] )), identifier[re] . identifier[IGNORECASE] )
def term_regex(term): """ Returns a case-insensitive regex for searching terms """ return re.compile('^{0}$'.format(re.escape(term)), re.IGNORECASE)
def policy_exists(vhost, name, runas=None): ''' Return whether the policy exists based on rabbitmqctl list_policies. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.policy_exists / HA ''' if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() policies = list_policies(runas=runas) return bool(vhost in policies and name in policies[vhost])
def function[policy_exists, parameter[vhost, name, runas]]: constant[ Return whether the policy exists based on rabbitmqctl list_policies. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.policy_exists / HA ] if <ast.BoolOp object at 0x7da18c4ce2c0> begin[:] variable[runas] assign[=] call[name[salt].utils.user.get_user, parameter[]] variable[policies] assign[=] call[name[list_policies], parameter[]] return[call[name[bool], parameter[<ast.BoolOp object at 0x7da18f810a60>]]]
keyword[def] identifier[policy_exists] ( identifier[vhost] , identifier[name] , identifier[runas] = keyword[None] ): literal[string] keyword[if] identifier[runas] keyword[is] keyword[None] keyword[and] keyword[not] identifier[salt] . identifier[utils] . identifier[platform] . identifier[is_windows] (): identifier[runas] = identifier[salt] . identifier[utils] . identifier[user] . identifier[get_user] () identifier[policies] = identifier[list_policies] ( identifier[runas] = identifier[runas] ) keyword[return] identifier[bool] ( identifier[vhost] keyword[in] identifier[policies] keyword[and] identifier[name] keyword[in] identifier[policies] [ identifier[vhost] ])
def policy_exists(vhost, name, runas=None): """ Return whether the policy exists based on rabbitmqctl list_policies. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.policy_exists / HA """ if runas is None and (not salt.utils.platform.is_windows()): runas = salt.utils.user.get_user() # depends on [control=['if'], data=[]] policies = list_policies(runas=runas) return bool(vhost in policies and name in policies[vhost])
def encode_csv(data_dict, column_names): """Builds a csv string. Args: data_dict: dict of {column_name: 1 value} column_names: list of column names Returns: A csv string version of data_dict """ import csv import six values = [str(data_dict[x]) for x in column_names] str_buff = six.StringIO() writer = csv.writer(str_buff, lineterminator='') writer.writerow(values) return str_buff.getvalue()
def function[encode_csv, parameter[data_dict, column_names]]: constant[Builds a csv string. Args: data_dict: dict of {column_name: 1 value} column_names: list of column names Returns: A csv string version of data_dict ] import module[csv] import module[six] variable[values] assign[=] <ast.ListComp object at 0x7da2043466e0> variable[str_buff] assign[=] call[name[six].StringIO, parameter[]] variable[writer] assign[=] call[name[csv].writer, parameter[name[str_buff]]] call[name[writer].writerow, parameter[name[values]]] return[call[name[str_buff].getvalue, parameter[]]]
keyword[def] identifier[encode_csv] ( identifier[data_dict] , identifier[column_names] ): literal[string] keyword[import] identifier[csv] keyword[import] identifier[six] identifier[values] =[ identifier[str] ( identifier[data_dict] [ identifier[x] ]) keyword[for] identifier[x] keyword[in] identifier[column_names] ] identifier[str_buff] = identifier[six] . identifier[StringIO] () identifier[writer] = identifier[csv] . identifier[writer] ( identifier[str_buff] , identifier[lineterminator] = literal[string] ) identifier[writer] . identifier[writerow] ( identifier[values] ) keyword[return] identifier[str_buff] . identifier[getvalue] ()
def encode_csv(data_dict, column_names): """Builds a csv string. Args: data_dict: dict of {column_name: 1 value} column_names: list of column names Returns: A csv string version of data_dict """ import csv import six values = [str(data_dict[x]) for x in column_names] str_buff = six.StringIO() writer = csv.writer(str_buff, lineterminator='') writer.writerow(values) return str_buff.getvalue()
def find_vulnerabilities( cfg_list, blackbox_mapping_file, sources_and_sinks_file, interactive=False, nosec_lines=defaultdict(set) ): """Find vulnerabilities in a list of CFGs from a trigger_word_file. Args: cfg_list(list[CFG]): the list of CFGs to scan. blackbox_mapping_file(str) sources_and_sinks_file(str) interactive(bool): determines if we ask the user about blackbox functions not in the mapping file. Returns: A list of vulnerabilities. """ vulnerabilities = list() definitions = parse(sources_and_sinks_file) with open(blackbox_mapping_file) as infile: blackbox_mapping = json.load(infile) for cfg in cfg_list: find_vulnerabilities_in_cfg( cfg, definitions, Lattice(cfg.nodes), blackbox_mapping, vulnerabilities, interactive, nosec_lines ) if interactive: with open(blackbox_mapping_file, 'w') as outfile: json.dump(blackbox_mapping, outfile, indent=4) return vulnerabilities
def function[find_vulnerabilities, parameter[cfg_list, blackbox_mapping_file, sources_and_sinks_file, interactive, nosec_lines]]: constant[Find vulnerabilities in a list of CFGs from a trigger_word_file. Args: cfg_list(list[CFG]): the list of CFGs to scan. blackbox_mapping_file(str) sources_and_sinks_file(str) interactive(bool): determines if we ask the user about blackbox functions not in the mapping file. Returns: A list of vulnerabilities. ] variable[vulnerabilities] assign[=] call[name[list], parameter[]] variable[definitions] assign[=] call[name[parse], parameter[name[sources_and_sinks_file]]] with call[name[open], parameter[name[blackbox_mapping_file]]] begin[:] variable[blackbox_mapping] assign[=] call[name[json].load, parameter[name[infile]]] for taget[name[cfg]] in starred[name[cfg_list]] begin[:] call[name[find_vulnerabilities_in_cfg], parameter[name[cfg], name[definitions], call[name[Lattice], parameter[name[cfg].nodes]], name[blackbox_mapping], name[vulnerabilities], name[interactive], name[nosec_lines]]] if name[interactive] begin[:] with call[name[open], parameter[name[blackbox_mapping_file], constant[w]]] begin[:] call[name[json].dump, parameter[name[blackbox_mapping], name[outfile]]] return[name[vulnerabilities]]
keyword[def] identifier[find_vulnerabilities] ( identifier[cfg_list] , identifier[blackbox_mapping_file] , identifier[sources_and_sinks_file] , identifier[interactive] = keyword[False] , identifier[nosec_lines] = identifier[defaultdict] ( identifier[set] ) ): literal[string] identifier[vulnerabilities] = identifier[list] () identifier[definitions] = identifier[parse] ( identifier[sources_and_sinks_file] ) keyword[with] identifier[open] ( identifier[blackbox_mapping_file] ) keyword[as] identifier[infile] : identifier[blackbox_mapping] = identifier[json] . identifier[load] ( identifier[infile] ) keyword[for] identifier[cfg] keyword[in] identifier[cfg_list] : identifier[find_vulnerabilities_in_cfg] ( identifier[cfg] , identifier[definitions] , identifier[Lattice] ( identifier[cfg] . identifier[nodes] ), identifier[blackbox_mapping] , identifier[vulnerabilities] , identifier[interactive] , identifier[nosec_lines] ) keyword[if] identifier[interactive] : keyword[with] identifier[open] ( identifier[blackbox_mapping_file] , literal[string] ) keyword[as] identifier[outfile] : identifier[json] . identifier[dump] ( identifier[blackbox_mapping] , identifier[outfile] , identifier[indent] = literal[int] ) keyword[return] identifier[vulnerabilities]
def find_vulnerabilities(cfg_list, blackbox_mapping_file, sources_and_sinks_file, interactive=False, nosec_lines=defaultdict(set)): """Find vulnerabilities in a list of CFGs from a trigger_word_file. Args: cfg_list(list[CFG]): the list of CFGs to scan. blackbox_mapping_file(str) sources_and_sinks_file(str) interactive(bool): determines if we ask the user about blackbox functions not in the mapping file. Returns: A list of vulnerabilities. """ vulnerabilities = list() definitions = parse(sources_and_sinks_file) with open(blackbox_mapping_file) as infile: blackbox_mapping = json.load(infile) # depends on [control=['with'], data=['infile']] for cfg in cfg_list: find_vulnerabilities_in_cfg(cfg, definitions, Lattice(cfg.nodes), blackbox_mapping, vulnerabilities, interactive, nosec_lines) # depends on [control=['for'], data=['cfg']] if interactive: with open(blackbox_mapping_file, 'w') as outfile: json.dump(blackbox_mapping, outfile, indent=4) # depends on [control=['with'], data=['outfile']] # depends on [control=['if'], data=[]] return vulnerabilities
def _process_cascaded_event_contents(records, additional_events=None): """ Flatten a series of records into its most basic elements (subcontribution level). Yields results. :param records: queue records to process :param additional_events: events whose content will be included in addition to those found in records """ changed_events = additional_events or set() changed_contributions = set() changed_subcontributions = set() session_records = {rec.session_id for rec in records if rec.type == EntryType.session} contribution_records = {rec.contrib_id for rec in records if rec.type == EntryType.contribution} subcontribution_records = {rec.subcontrib_id for rec in records if rec.type == EntryType.subcontribution} event_records = {rec.event_id for rec in records if rec.type == EntryType.event} if event_records: changed_events.update(Event.find(Event.id.in_(event_records))) for event in changed_events: yield event # Sessions are added (explicitly changed only, since they don't need to be sent anywhere) if session_records: changed_contributions.update(Contribution .find(Contribution.session_id.in_(session_records), ~Contribution.is_deleted)) # Contributions are added (implictly + explicitly changed) changed_event_ids = {ev.id for ev in changed_events} condition = Contribution.event_id.in_(changed_event_ids) & ~Contribution.is_deleted if contribution_records: condition = db.or_(condition, Contribution.id.in_(contribution_records)) contrib_query = Contribution.find(condition).options(joinedload('subcontributions')) for contribution in contrib_query: yield contribution changed_subcontributions.update(contribution.subcontributions) # Same for subcontributions if subcontribution_records: changed_subcontributions.update(SubContribution.find(SubContribution.id.in_(subcontribution_records))) for subcontrib in changed_subcontributions: yield subcontrib
def function[_process_cascaded_event_contents, parameter[records, additional_events]]: constant[ Flatten a series of records into its most basic elements (subcontribution level). Yields results. :param records: queue records to process :param additional_events: events whose content will be included in addition to those found in records ] variable[changed_events] assign[=] <ast.BoolOp object at 0x7da18f58e620> variable[changed_contributions] assign[=] call[name[set], parameter[]] variable[changed_subcontributions] assign[=] call[name[set], parameter[]] variable[session_records] assign[=] <ast.SetComp object at 0x7da18f58f160> variable[contribution_records] assign[=] <ast.SetComp object at 0x7da18ede4af0> variable[subcontribution_records] assign[=] <ast.SetComp object at 0x7da18ede78b0> variable[event_records] assign[=] <ast.SetComp object at 0x7da18ede7130> if name[event_records] begin[:] call[name[changed_events].update, parameter[call[name[Event].find, parameter[call[name[Event].id.in_, parameter[name[event_records]]]]]]] for taget[name[event]] in starred[name[changed_events]] begin[:] <ast.Yield object at 0x7da18ede7850> if name[session_records] begin[:] call[name[changed_contributions].update, parameter[call[name[Contribution].find, parameter[call[name[Contribution].session_id.in_, parameter[name[session_records]]], <ast.UnaryOp object at 0x7da18ede42e0>]]]] variable[changed_event_ids] assign[=] <ast.SetComp object at 0x7da18ede6fe0> variable[condition] assign[=] binary_operation[call[name[Contribution].event_id.in_, parameter[name[changed_event_ids]]] <ast.BitAnd object at 0x7da2590d6b60> <ast.UnaryOp object at 0x7da18ede48e0>] if name[contribution_records] begin[:] variable[condition] assign[=] call[name[db].or_, parameter[name[condition], call[name[Contribution].id.in_, parameter[name[contribution_records]]]]] variable[contrib_query] assign[=] call[call[name[Contribution].find, parameter[name[condition]]].options, parameter[call[name[joinedload], parameter[constant[subcontributions]]]]] for taget[name[contribution]] in starred[name[contrib_query]] begin[:] <ast.Yield object at 0x7da1b2344670> call[name[changed_subcontributions].update, parameter[name[contribution].subcontributions]] if name[subcontribution_records] begin[:] call[name[changed_subcontributions].update, parameter[call[name[SubContribution].find, parameter[call[name[SubContribution].id.in_, parameter[name[subcontribution_records]]]]]]] for taget[name[subcontrib]] in starred[name[changed_subcontributions]] begin[:] <ast.Yield object at 0x7da1b23445e0>
keyword[def] identifier[_process_cascaded_event_contents] ( identifier[records] , identifier[additional_events] = keyword[None] ): literal[string] identifier[changed_events] = identifier[additional_events] keyword[or] identifier[set] () identifier[changed_contributions] = identifier[set] () identifier[changed_subcontributions] = identifier[set] () identifier[session_records] ={ identifier[rec] . identifier[session_id] keyword[for] identifier[rec] keyword[in] identifier[records] keyword[if] identifier[rec] . identifier[type] == identifier[EntryType] . identifier[session] } identifier[contribution_records] ={ identifier[rec] . identifier[contrib_id] keyword[for] identifier[rec] keyword[in] identifier[records] keyword[if] identifier[rec] . identifier[type] == identifier[EntryType] . identifier[contribution] } identifier[subcontribution_records] ={ identifier[rec] . identifier[subcontrib_id] keyword[for] identifier[rec] keyword[in] identifier[records] keyword[if] identifier[rec] . identifier[type] == identifier[EntryType] . identifier[subcontribution] } identifier[event_records] ={ identifier[rec] . identifier[event_id] keyword[for] identifier[rec] keyword[in] identifier[records] keyword[if] identifier[rec] . identifier[type] == identifier[EntryType] . identifier[event] } keyword[if] identifier[event_records] : identifier[changed_events] . identifier[update] ( identifier[Event] . identifier[find] ( identifier[Event] . identifier[id] . identifier[in_] ( identifier[event_records] ))) keyword[for] identifier[event] keyword[in] identifier[changed_events] : keyword[yield] identifier[event] keyword[if] identifier[session_records] : identifier[changed_contributions] . identifier[update] ( identifier[Contribution] . identifier[find] ( identifier[Contribution] . identifier[session_id] . identifier[in_] ( identifier[session_records] ),~ identifier[Contribution] . identifier[is_deleted] )) identifier[changed_event_ids] ={ identifier[ev] . identifier[id] keyword[for] identifier[ev] keyword[in] identifier[changed_events] } identifier[condition] = identifier[Contribution] . identifier[event_id] . identifier[in_] ( identifier[changed_event_ids] )&~ identifier[Contribution] . identifier[is_deleted] keyword[if] identifier[contribution_records] : identifier[condition] = identifier[db] . identifier[or_] ( identifier[condition] , identifier[Contribution] . identifier[id] . identifier[in_] ( identifier[contribution_records] )) identifier[contrib_query] = identifier[Contribution] . identifier[find] ( identifier[condition] ). identifier[options] ( identifier[joinedload] ( literal[string] )) keyword[for] identifier[contribution] keyword[in] identifier[contrib_query] : keyword[yield] identifier[contribution] identifier[changed_subcontributions] . identifier[update] ( identifier[contribution] . identifier[subcontributions] ) keyword[if] identifier[subcontribution_records] : identifier[changed_subcontributions] . identifier[update] ( identifier[SubContribution] . identifier[find] ( identifier[SubContribution] . identifier[id] . identifier[in_] ( identifier[subcontribution_records] ))) keyword[for] identifier[subcontrib] keyword[in] identifier[changed_subcontributions] : keyword[yield] identifier[subcontrib]
def _process_cascaded_event_contents(records, additional_events=None): """ Flatten a series of records into its most basic elements (subcontribution level). Yields results. :param records: queue records to process :param additional_events: events whose content will be included in addition to those found in records """ changed_events = additional_events or set() changed_contributions = set() changed_subcontributions = set() session_records = {rec.session_id for rec in records if rec.type == EntryType.session} contribution_records = {rec.contrib_id for rec in records if rec.type == EntryType.contribution} subcontribution_records = {rec.subcontrib_id for rec in records if rec.type == EntryType.subcontribution} event_records = {rec.event_id for rec in records if rec.type == EntryType.event} if event_records: changed_events.update(Event.find(Event.id.in_(event_records))) # depends on [control=['if'], data=[]] for event in changed_events: yield event # depends on [control=['for'], data=['event']] # Sessions are added (explicitly changed only, since they don't need to be sent anywhere) if session_records: changed_contributions.update(Contribution.find(Contribution.session_id.in_(session_records), ~Contribution.is_deleted)) # depends on [control=['if'], data=[]] # Contributions are added (implictly + explicitly changed) changed_event_ids = {ev.id for ev in changed_events} condition = Contribution.event_id.in_(changed_event_ids) & ~Contribution.is_deleted if contribution_records: condition = db.or_(condition, Contribution.id.in_(contribution_records)) # depends on [control=['if'], data=[]] contrib_query = Contribution.find(condition).options(joinedload('subcontributions')) for contribution in contrib_query: yield contribution changed_subcontributions.update(contribution.subcontributions) # depends on [control=['for'], data=['contribution']] # Same for subcontributions if subcontribution_records: changed_subcontributions.update(SubContribution.find(SubContribution.id.in_(subcontribution_records))) # depends on [control=['if'], data=[]] for subcontrib in changed_subcontributions: yield subcontrib # depends on [control=['for'], data=['subcontrib']]
def sync_config_devices(obj, newconfig, newdevices, test=False): ''' Syncs the given config and devices with the object (a profile or a container) returns a changes dict with all changes made. obj : The object to sync with / or just test with. newconfig: The new config to check with the obj. newdevices: The new devices to check with the obj. test: Wherever to not change anything and give "Would change" message. ''' changes = {} # # config changes # if newconfig is None: newconfig = {} newconfig = dict(list(zip( map(six.text_type, newconfig.keys()), map(six.text_type, newconfig.values()) ))) cck = set(newconfig.keys()) obj.config = dict(list(zip( map(six.text_type, obj.config.keys()), map(six.text_type, obj.config.values()) ))) ock = set(obj.config.keys()) config_changes = {} # Removed keys for k in ock.difference(cck): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue if not test: config_changes[k] = ( 'Removed config key "{0}", its value was "{1}"' ).format(k, obj.config[k]) del obj.config[k] else: config_changes[k] = ( 'Would remove config key "{0} with value "{1}"' ).format(k, obj.config[k]) # same keys for k in cck.intersection(ock): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue if newconfig[k] != obj.config[k]: if not test: config_changes[k] = ( 'Changed config key "{0}" to "{1}", ' 'its value was "{2}"' ).format(k, newconfig[k], obj.config[k]) obj.config[k] = newconfig[k] else: config_changes[k] = ( 'Would change config key "{0}" to "{1}", ' 'its current value is "{2}"' ).format(k, newconfig[k], obj.config[k]) # New keys for k in cck.difference(ock): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue if not test: config_changes[k] = ( 'Added config key "{0}" = "{1}"' ).format(k, newconfig[k]) obj.config[k] = newconfig[k] else: config_changes[k] = ( 'Would add config key "{0}" = "{1}"' ).format(k, newconfig[k]) if config_changes: changes['config'] = config_changes # # devices changes # if newdevices is None: newdevices = {} dk = set(obj.devices.keys()) ndk = set(newdevices.keys()) devices_changes = {} # Removed devices for k in dk.difference(ndk): # Ignore LXD internals. if k == u'root': continue if not test: devices_changes[k] = ( 'Removed device "{0}"' ).format(k) del obj.devices[k] else: devices_changes[k] = ( 'Would remove device "{0}"' ).format(k) # Changed devices for k, v in six.iteritems(obj.devices): # Ignore LXD internals also for new devices. if k == u'root': continue if k not in newdevices: # In test mode we don't delete devices above. continue if newdevices[k] != v: if not test: devices_changes[k] = ( 'Changed device "{0}"' ).format(k) obj.devices[k] = newdevices[k] else: devices_changes[k] = ( 'Would change device "{0}"' ).format(k) # New devices for k in ndk.difference(dk): # Ignore LXD internals. if k == u'root': continue if not test: devices_changes[k] = ( 'Added device "{0}"' ).format(k) obj.devices[k] = newdevices[k] else: devices_changes[k] = ( 'Would add device "{0}"' ).format(k) if devices_changes: changes['devices'] = devices_changes return changes
def function[sync_config_devices, parameter[obj, newconfig, newdevices, test]]: constant[ Syncs the given config and devices with the object (a profile or a container) returns a changes dict with all changes made. obj : The object to sync with / or just test with. newconfig: The new config to check with the obj. newdevices: The new devices to check with the obj. test: Wherever to not change anything and give "Would change" message. ] variable[changes] assign[=] dictionary[[], []] if compare[name[newconfig] is constant[None]] begin[:] variable[newconfig] assign[=] dictionary[[], []] variable[newconfig] assign[=] call[name[dict], parameter[call[name[list], parameter[call[name[zip], parameter[call[name[map], parameter[name[six].text_type, call[name[newconfig].keys, parameter[]]]], call[name[map], parameter[name[six].text_type, call[name[newconfig].values, parameter[]]]]]]]]]] variable[cck] assign[=] call[name[set], parameter[call[name[newconfig].keys, parameter[]]]] name[obj].config assign[=] call[name[dict], parameter[call[name[list], parameter[call[name[zip], parameter[call[name[map], parameter[name[six].text_type, call[name[obj].config.keys, parameter[]]]], call[name[map], parameter[name[six].text_type, call[name[obj].config.values, parameter[]]]]]]]]]] variable[ock] assign[=] call[name[set], parameter[call[name[obj].config.keys, parameter[]]]] variable[config_changes] assign[=] dictionary[[], []] for taget[name[k]] in starred[call[name[ock].difference, parameter[name[cck]]]] begin[:] if <ast.BoolOp object at 0x7da2054a7e50> begin[:] continue if <ast.UnaryOp object at 0x7da2054a5c90> begin[:] call[name[config_changes]][name[k]] assign[=] call[constant[Removed config key "{0}", its value was "{1}"].format, parameter[name[k], call[name[obj].config][name[k]]]] <ast.Delete object at 0x7da2054a52a0> for taget[name[k]] in starred[call[name[cck].intersection, parameter[name[ock]]]] begin[:] if <ast.BoolOp object at 0x7da1b2186890> begin[:] continue if compare[call[name[newconfig]][name[k]] not_equal[!=] call[name[obj].config][name[k]]] begin[:] if <ast.UnaryOp object at 0x7da1b26ac700> begin[:] call[name[config_changes]][name[k]] assign[=] call[constant[Changed config key "{0}" to "{1}", its value was "{2}"].format, parameter[name[k], call[name[newconfig]][name[k]], call[name[obj].config][name[k]]]] call[name[obj].config][name[k]] assign[=] call[name[newconfig]][name[k]] for taget[name[k]] in starred[call[name[cck].difference, parameter[name[ock]]]] begin[:] if <ast.BoolOp object at 0x7da1b26aeb90> begin[:] continue if <ast.UnaryOp object at 0x7da1b26acdc0> begin[:] call[name[config_changes]][name[k]] assign[=] call[constant[Added config key "{0}" = "{1}"].format, parameter[name[k], call[name[newconfig]][name[k]]]] call[name[obj].config][name[k]] assign[=] call[name[newconfig]][name[k]] if name[config_changes] begin[:] call[name[changes]][constant[config]] assign[=] name[config_changes] if compare[name[newdevices] is constant[None]] begin[:] variable[newdevices] assign[=] dictionary[[], []] variable[dk] assign[=] call[name[set], parameter[call[name[obj].devices.keys, parameter[]]]] variable[ndk] assign[=] call[name[set], parameter[call[name[newdevices].keys, parameter[]]]] variable[devices_changes] assign[=] dictionary[[], []] for taget[name[k]] in starred[call[name[dk].difference, parameter[name[ndk]]]] begin[:] if compare[name[k] equal[==] constant[root]] begin[:] continue if <ast.UnaryOp object at 0x7da18ede4640> begin[:] call[name[devices_changes]][name[k]] assign[=] call[constant[Removed device "{0}"].format, parameter[name[k]]] <ast.Delete object at 0x7da18ede7e50> for taget[tuple[[<ast.Name object at 0x7da18ede6290>, <ast.Name object at 0x7da18ede5900>]]] in starred[call[name[six].iteritems, parameter[name[obj].devices]]] begin[:] if compare[name[k] equal[==] constant[root]] begin[:] continue if compare[name[k] <ast.NotIn object at 0x7da2590d7190> name[newdevices]] begin[:] continue if compare[call[name[newdevices]][name[k]] not_equal[!=] name[v]] begin[:] if <ast.UnaryOp object at 0x7da18ede5fc0> begin[:] call[name[devices_changes]][name[k]] assign[=] call[constant[Changed device "{0}"].format, parameter[name[k]]] call[name[obj].devices][name[k]] assign[=] call[name[newdevices]][name[k]] for taget[name[k]] in starred[call[name[ndk].difference, parameter[name[dk]]]] begin[:] if compare[name[k] equal[==] constant[root]] begin[:] continue if <ast.UnaryOp object at 0x7da18ede46d0> begin[:] call[name[devices_changes]][name[k]] assign[=] call[constant[Added device "{0}"].format, parameter[name[k]]] call[name[obj].devices][name[k]] assign[=] call[name[newdevices]][name[k]] if name[devices_changes] begin[:] call[name[changes]][constant[devices]] assign[=] name[devices_changes] return[name[changes]]
keyword[def] identifier[sync_config_devices] ( identifier[obj] , identifier[newconfig] , identifier[newdevices] , identifier[test] = keyword[False] ): literal[string] identifier[changes] ={} keyword[if] identifier[newconfig] keyword[is] keyword[None] : identifier[newconfig] ={} identifier[newconfig] = identifier[dict] ( identifier[list] ( identifier[zip] ( identifier[map] ( identifier[six] . identifier[text_type] , identifier[newconfig] . identifier[keys] ()), identifier[map] ( identifier[six] . identifier[text_type] , identifier[newconfig] . identifier[values] ()) ))) identifier[cck] = identifier[set] ( identifier[newconfig] . identifier[keys] ()) identifier[obj] . identifier[config] = identifier[dict] ( identifier[list] ( identifier[zip] ( identifier[map] ( identifier[six] . identifier[text_type] , identifier[obj] . identifier[config] . identifier[keys] ()), identifier[map] ( identifier[six] . identifier[text_type] , identifier[obj] . identifier[config] . identifier[values] ()) ))) identifier[ock] = identifier[set] ( identifier[obj] . identifier[config] . identifier[keys] ()) identifier[config_changes] ={} keyword[for] identifier[k] keyword[in] identifier[ock] . identifier[difference] ( identifier[cck] ): keyword[if] identifier[k] . identifier[startswith] ( literal[string] ) keyword[or] identifier[k] . identifier[startswith] ( literal[string] ): keyword[continue] keyword[if] keyword[not] identifier[test] : identifier[config_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] , identifier[obj] . identifier[config] [ identifier[k] ]) keyword[del] identifier[obj] . identifier[config] [ identifier[k] ] keyword[else] : identifier[config_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] , identifier[obj] . identifier[config] [ identifier[k] ]) keyword[for] identifier[k] keyword[in] identifier[cck] . identifier[intersection] ( identifier[ock] ): keyword[if] identifier[k] . identifier[startswith] ( literal[string] ) keyword[or] identifier[k] . identifier[startswith] ( literal[string] ): keyword[continue] keyword[if] identifier[newconfig] [ identifier[k] ]!= identifier[obj] . identifier[config] [ identifier[k] ]: keyword[if] keyword[not] identifier[test] : identifier[config_changes] [ identifier[k] ]=( literal[string] literal[string] ). identifier[format] ( identifier[k] , identifier[newconfig] [ identifier[k] ], identifier[obj] . identifier[config] [ identifier[k] ]) identifier[obj] . identifier[config] [ identifier[k] ]= identifier[newconfig] [ identifier[k] ] keyword[else] : identifier[config_changes] [ identifier[k] ]=( literal[string] literal[string] ). identifier[format] ( identifier[k] , identifier[newconfig] [ identifier[k] ], identifier[obj] . identifier[config] [ identifier[k] ]) keyword[for] identifier[k] keyword[in] identifier[cck] . identifier[difference] ( identifier[ock] ): keyword[if] identifier[k] . identifier[startswith] ( literal[string] ) keyword[or] identifier[k] . identifier[startswith] ( literal[string] ): keyword[continue] keyword[if] keyword[not] identifier[test] : identifier[config_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] , identifier[newconfig] [ identifier[k] ]) identifier[obj] . identifier[config] [ identifier[k] ]= identifier[newconfig] [ identifier[k] ] keyword[else] : identifier[config_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] , identifier[newconfig] [ identifier[k] ]) keyword[if] identifier[config_changes] : identifier[changes] [ literal[string] ]= identifier[config_changes] keyword[if] identifier[newdevices] keyword[is] keyword[None] : identifier[newdevices] ={} identifier[dk] = identifier[set] ( identifier[obj] . identifier[devices] . identifier[keys] ()) identifier[ndk] = identifier[set] ( identifier[newdevices] . identifier[keys] ()) identifier[devices_changes] ={} keyword[for] identifier[k] keyword[in] identifier[dk] . identifier[difference] ( identifier[ndk] ): keyword[if] identifier[k] == literal[string] : keyword[continue] keyword[if] keyword[not] identifier[test] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) keyword[del] identifier[obj] . identifier[devices] [ identifier[k] ] keyword[else] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[six] . identifier[iteritems] ( identifier[obj] . identifier[devices] ): keyword[if] identifier[k] == literal[string] : keyword[continue] keyword[if] identifier[k] keyword[not] keyword[in] identifier[newdevices] : keyword[continue] keyword[if] identifier[newdevices] [ identifier[k] ]!= identifier[v] : keyword[if] keyword[not] identifier[test] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) identifier[obj] . identifier[devices] [ identifier[k] ]= identifier[newdevices] [ identifier[k] ] keyword[else] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) keyword[for] identifier[k] keyword[in] identifier[ndk] . identifier[difference] ( identifier[dk] ): keyword[if] identifier[k] == literal[string] : keyword[continue] keyword[if] keyword[not] identifier[test] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) identifier[obj] . identifier[devices] [ identifier[k] ]= identifier[newdevices] [ identifier[k] ] keyword[else] : identifier[devices_changes] [ identifier[k] ]=( literal[string] ). identifier[format] ( identifier[k] ) keyword[if] identifier[devices_changes] : identifier[changes] [ literal[string] ]= identifier[devices_changes] keyword[return] identifier[changes]
def sync_config_devices(obj, newconfig, newdevices, test=False): """ Syncs the given config and devices with the object (a profile or a container) returns a changes dict with all changes made. obj : The object to sync with / or just test with. newconfig: The new config to check with the obj. newdevices: The new devices to check with the obj. test: Wherever to not change anything and give "Would change" message. """ changes = {} # # config changes # if newconfig is None: newconfig = {} # depends on [control=['if'], data=['newconfig']] newconfig = dict(list(zip(map(six.text_type, newconfig.keys()), map(six.text_type, newconfig.values())))) cck = set(newconfig.keys()) obj.config = dict(list(zip(map(six.text_type, obj.config.keys()), map(six.text_type, obj.config.values())))) ock = set(obj.config.keys()) config_changes = {} # Removed keys for k in ock.difference(cck): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue # depends on [control=['if'], data=[]] if not test: config_changes[k] = 'Removed config key "{0}", its value was "{1}"'.format(k, obj.config[k]) del obj.config[k] # depends on [control=['if'], data=[]] else: config_changes[k] = 'Would remove config key "{0} with value "{1}"'.format(k, obj.config[k]) # depends on [control=['for'], data=['k']] # same keys for k in cck.intersection(ock): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue # depends on [control=['if'], data=[]] if newconfig[k] != obj.config[k]: if not test: config_changes[k] = 'Changed config key "{0}" to "{1}", its value was "{2}"'.format(k, newconfig[k], obj.config[k]) obj.config[k] = newconfig[k] # depends on [control=['if'], data=[]] else: config_changes[k] = 'Would change config key "{0}" to "{1}", its current value is "{2}"'.format(k, newconfig[k], obj.config[k]) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['k']] # New keys for k in cck.difference(ock): # Ignore LXD internals. if k.startswith('volatile.') or k.startswith('image.'): continue # depends on [control=['if'], data=[]] if not test: config_changes[k] = 'Added config key "{0}" = "{1}"'.format(k, newconfig[k]) obj.config[k] = newconfig[k] # depends on [control=['if'], data=[]] else: config_changes[k] = 'Would add config key "{0}" = "{1}"'.format(k, newconfig[k]) # depends on [control=['for'], data=['k']] if config_changes: changes['config'] = config_changes # depends on [control=['if'], data=[]] # # devices changes # if newdevices is None: newdevices = {} # depends on [control=['if'], data=['newdevices']] dk = set(obj.devices.keys()) ndk = set(newdevices.keys()) devices_changes = {} # Removed devices for k in dk.difference(ndk): # Ignore LXD internals. if k == u'root': continue # depends on [control=['if'], data=[]] if not test: devices_changes[k] = 'Removed device "{0}"'.format(k) del obj.devices[k] # depends on [control=['if'], data=[]] else: devices_changes[k] = 'Would remove device "{0}"'.format(k) # depends on [control=['for'], data=['k']] # Changed devices for (k, v) in six.iteritems(obj.devices): # Ignore LXD internals also for new devices. if k == u'root': continue # depends on [control=['if'], data=[]] if k not in newdevices: # In test mode we don't delete devices above. continue # depends on [control=['if'], data=[]] if newdevices[k] != v: if not test: devices_changes[k] = 'Changed device "{0}"'.format(k) obj.devices[k] = newdevices[k] # depends on [control=['if'], data=[]] else: devices_changes[k] = 'Would change device "{0}"'.format(k) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # New devices for k in ndk.difference(dk): # Ignore LXD internals. if k == u'root': continue # depends on [control=['if'], data=[]] if not test: devices_changes[k] = 'Added device "{0}"'.format(k) obj.devices[k] = newdevices[k] # depends on [control=['if'], data=[]] else: devices_changes[k] = 'Would add device "{0}"'.format(k) # depends on [control=['for'], data=['k']] if devices_changes: changes['devices'] = devices_changes # depends on [control=['if'], data=[]] return changes
def get_gff_db(gff_fname, ext=".db"): """ Get db for GFF file. If the database has a .db file, load that. Otherwise, create a named temporary file, serialize the db to that, and return the loaded database. """ if not os.path.isfile(gff_fname): # Not sure how we should deal with errors normally in # gffutils -- Ryan? raise ValueError("GFF %s does not exist." % (gff_fname)) candidate_db_fname = "%s.%s" % (gff_fname, ext) if os.path.isfile(candidate_db_fname): # Standard .db file found, so return it return candidate_db_fname # Otherwise, we need to create a temporary but non-deleted # file to store the db in. It'll be up to the user # of the function the delete the file when done. ## NOTE: Ryan must have a good scheme for dealing with this ## since pybedtools does something similar under the hood, i.e. ## creating temporary files as needed without over proliferation db_fname = tempfile.NamedTemporaryFile(delete=False) # Create the database for the gff file (suppress output # when using function internally) print("Creating db for %s" % (gff_fname)) t1 = time.time() db = gffutils.create_db(gff_fname, db_fname.name, merge_strategy="merge", verbose=False) t2 = time.time() print(" - Took %.2f seconds" % (t2 - t1)) return db
def function[get_gff_db, parameter[gff_fname, ext]]: constant[ Get db for GFF file. If the database has a .db file, load that. Otherwise, create a named temporary file, serialize the db to that, and return the loaded database. ] if <ast.UnaryOp object at 0x7da20c992b30> begin[:] <ast.Raise object at 0x7da20c991ff0> variable[candidate_db_fname] assign[=] binary_operation[constant[%s.%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da20c992560>, <ast.Name object at 0x7da20c993850>]]] if call[name[os].path.isfile, parameter[name[candidate_db_fname]]] begin[:] return[name[candidate_db_fname]] variable[db_fname] assign[=] call[name[tempfile].NamedTemporaryFile, parameter[]] call[name[print], parameter[binary_operation[constant[Creating db for %s] <ast.Mod object at 0x7da2590d6920> name[gff_fname]]]] variable[t1] assign[=] call[name[time].time, parameter[]] variable[db] assign[=] call[name[gffutils].create_db, parameter[name[gff_fname], name[db_fname].name]] variable[t2] assign[=] call[name[time].time, parameter[]] call[name[print], parameter[binary_operation[constant[ - Took %.2f seconds] <ast.Mod object at 0x7da2590d6920> binary_operation[name[t2] - name[t1]]]]] return[name[db]]
keyword[def] identifier[get_gff_db] ( identifier[gff_fname] , identifier[ext] = literal[string] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[gff_fname] ): keyword[raise] identifier[ValueError] ( literal[string] %( identifier[gff_fname] )) identifier[candidate_db_fname] = literal[string] %( identifier[gff_fname] , identifier[ext] ) keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[candidate_db_fname] ): keyword[return] identifier[candidate_db_fname] identifier[db_fname] = identifier[tempfile] . identifier[NamedTemporaryFile] ( identifier[delete] = keyword[False] ) identifier[print] ( literal[string] %( identifier[gff_fname] )) identifier[t1] = identifier[time] . identifier[time] () identifier[db] = identifier[gffutils] . identifier[create_db] ( identifier[gff_fname] , identifier[db_fname] . identifier[name] , identifier[merge_strategy] = literal[string] , identifier[verbose] = keyword[False] ) identifier[t2] = identifier[time] . identifier[time] () identifier[print] ( literal[string] %( identifier[t2] - identifier[t1] )) keyword[return] identifier[db]
def get_gff_db(gff_fname, ext='.db'): """ Get db for GFF file. If the database has a .db file, load that. Otherwise, create a named temporary file, serialize the db to that, and return the loaded database. """ if not os.path.isfile(gff_fname): # Not sure how we should deal with errors normally in # gffutils -- Ryan? raise ValueError('GFF %s does not exist.' % gff_fname) # depends on [control=['if'], data=[]] candidate_db_fname = '%s.%s' % (gff_fname, ext) if os.path.isfile(candidate_db_fname): # Standard .db file found, so return it return candidate_db_fname # depends on [control=['if'], data=[]] # Otherwise, we need to create a temporary but non-deleted # file to store the db in. It'll be up to the user # of the function the delete the file when done. ## NOTE: Ryan must have a good scheme for dealing with this ## since pybedtools does something similar under the hood, i.e. ## creating temporary files as needed without over proliferation db_fname = tempfile.NamedTemporaryFile(delete=False) # Create the database for the gff file (suppress output # when using function internally) print('Creating db for %s' % gff_fname) t1 = time.time() db = gffutils.create_db(gff_fname, db_fname.name, merge_strategy='merge', verbose=False) t2 = time.time() print(' - Took %.2f seconds' % (t2 - t1)) return db
def hbar_stack(self, stackers, **kw): ''' Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "left", "right", **kw): result.append(self.hbar(**kw)) return result
def function[hbar_stack, parameter[self, stackers]]: constant[ Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ] variable[result] assign[=] list[[]] for taget[name[kw]] in starred[call[name[_double_stack], parameter[name[stackers], constant[left], constant[right]]]] begin[:] call[name[result].append, parameter[call[name[self].hbar, parameter[]]]] return[name[result]]
keyword[def] identifier[hbar_stack] ( identifier[self] , identifier[stackers] ,** identifier[kw] ): literal[string] identifier[result] =[] keyword[for] identifier[kw] keyword[in] identifier[_double_stack] ( identifier[stackers] , literal[string] , literal[string] ,** identifier[kw] ): identifier[result] . identifier[append] ( identifier[self] . identifier[hbar] (** identifier[kw] )) keyword[return] identifier[result]
def hbar_stack(self, stackers, **kw): """ Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') """ result = [] for kw in _double_stack(stackers, 'left', 'right', **kw): result.append(self.hbar(**kw)) # depends on [control=['for'], data=['kw']] return result
def validate(number): """This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers. """ clean_number = clear_punctuation(number) if len(clean_number) == 11: return cpf.validate(clean_number) elif len(clean_number) == 14: return cnpj.validate(clean_number) return False
def function[validate, parameter[number]]: constant[This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers. ] variable[clean_number] assign[=] call[name[clear_punctuation], parameter[name[number]]] if compare[call[name[len], parameter[name[clean_number]]] equal[==] constant[11]] begin[:] return[call[name[cpf].validate, parameter[name[clean_number]]]] return[constant[False]]
keyword[def] identifier[validate] ( identifier[number] ): literal[string] identifier[clean_number] = identifier[clear_punctuation] ( identifier[number] ) keyword[if] identifier[len] ( identifier[clean_number] )== literal[int] : keyword[return] identifier[cpf] . identifier[validate] ( identifier[clean_number] ) keyword[elif] identifier[len] ( identifier[clean_number] )== literal[int] : keyword[return] identifier[cnpj] . identifier[validate] ( identifier[clean_number] ) keyword[return] keyword[False]
def validate(number): """This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers. Feel free to use this or the other modules directly. :param number: a CPF or CNPJ number. Clear number to have only numbers. :type number: string :return: Bool -- True if number is a valid CPF or CNPJ number. False if it is not or do not complain with the right size of these numbers. """ clean_number = clear_punctuation(number) if len(clean_number) == 11: return cpf.validate(clean_number) # depends on [control=['if'], data=[]] elif len(clean_number) == 14: return cnpj.validate(clean_number) # depends on [control=['if'], data=[]] return False
def licenses_desc(self): """Remove prefix.""" return {self._acronym_lic(l): l.split(self.prefix_lic)[1] for l in self.resp_text.split('\n') if l.startswith(self.prefix_lic)}
def function[licenses_desc, parameter[self]]: constant[Remove prefix.] return[<ast.DictComp object at 0x7da2047eb850>]
keyword[def] identifier[licenses_desc] ( identifier[self] ): literal[string] keyword[return] { identifier[self] . identifier[_acronym_lic] ( identifier[l] ): identifier[l] . identifier[split] ( identifier[self] . identifier[prefix_lic] )[ literal[int] ] keyword[for] identifier[l] keyword[in] identifier[self] . identifier[resp_text] . identifier[split] ( literal[string] ) keyword[if] identifier[l] . identifier[startswith] ( identifier[self] . identifier[prefix_lic] )}
def licenses_desc(self): """Remove prefix.""" return {self._acronym_lic(l): l.split(self.prefix_lic)[1] for l in self.resp_text.split('\n') if l.startswith(self.prefix_lic)}
def experiments_fmri_create(self, experiment_url, data_file): """Upload given data file as fMRI for experiment with given Url. Parameters ---------- experiment_url : string Url for experiment resource data_file: Abs. Path to file on disk Functional data file Returns ------- scoserv.FunctionalDataHandle Handle to created fMRI resource """ # Get the experiment experiment = self.experiments_get(experiment_url) # Upload data FunctionalDataHandle.create( experiment.links[sco.REF_EXPERIMENTS_FMRI_CREATE], data_file ) # Get new fmri data handle and return it return self.experiments_get(experiment_url).fmri_data
def function[experiments_fmri_create, parameter[self, experiment_url, data_file]]: constant[Upload given data file as fMRI for experiment with given Url. Parameters ---------- experiment_url : string Url for experiment resource data_file: Abs. Path to file on disk Functional data file Returns ------- scoserv.FunctionalDataHandle Handle to created fMRI resource ] variable[experiment] assign[=] call[name[self].experiments_get, parameter[name[experiment_url]]] call[name[FunctionalDataHandle].create, parameter[call[name[experiment].links][name[sco].REF_EXPERIMENTS_FMRI_CREATE], name[data_file]]] return[call[name[self].experiments_get, parameter[name[experiment_url]]].fmri_data]
keyword[def] identifier[experiments_fmri_create] ( identifier[self] , identifier[experiment_url] , identifier[data_file] ): literal[string] identifier[experiment] = identifier[self] . identifier[experiments_get] ( identifier[experiment_url] ) identifier[FunctionalDataHandle] . identifier[create] ( identifier[experiment] . identifier[links] [ identifier[sco] . identifier[REF_EXPERIMENTS_FMRI_CREATE] ], identifier[data_file] ) keyword[return] identifier[self] . identifier[experiments_get] ( identifier[experiment_url] ). identifier[fmri_data]
def experiments_fmri_create(self, experiment_url, data_file): """Upload given data file as fMRI for experiment with given Url. Parameters ---------- experiment_url : string Url for experiment resource data_file: Abs. Path to file on disk Functional data file Returns ------- scoserv.FunctionalDataHandle Handle to created fMRI resource """ # Get the experiment experiment = self.experiments_get(experiment_url) # Upload data FunctionalDataHandle.create(experiment.links[sco.REF_EXPERIMENTS_FMRI_CREATE], data_file) # Get new fmri data handle and return it return self.experiments_get(experiment_url).fmri_data
def query(self, criteria, **opts): """ Returns a dict of the query, including the results :param critera: string of search criteria :param **opts: :formats: json/xml (default: json) :timezone: timezone to use (default: UTC) :time_from: 15m ago from now (datetime) :time_to: right now (datetime) """ time_now = datetime.datetime.now().replace(second=0, microsecond=0) right_now = time_now.isoformat() minutes_ago = (time_now - datetime.timedelta(minutes=15)).isoformat() formats = opts.get('formats', 'json') timezone = opts.get('timezone', 'UTC') time_from = opts.get('time_from', minutes_ago) time_to = opts.get('time_to', right_now) # setting up options t_options = { 'q': criteria, 'format': formats, 'tz': timezone, 'from': time_from, 'to': time_to, } options = '&'.join(['{}={}'.format(k, v) for k, v in t_options.items()]) req = requests.get('%s?%s' % (self.url, options), auth=self.auth) try: data = req.json() except json.decoder.JSONDecodeError: data = [] return { 'data': data, 'response': req.status_code, 'reason': req.reason, }
def function[query, parameter[self, criteria]]: constant[ Returns a dict of the query, including the results :param critera: string of search criteria :param **opts: :formats: json/xml (default: json) :timezone: timezone to use (default: UTC) :time_from: 15m ago from now (datetime) :time_to: right now (datetime) ] variable[time_now] assign[=] call[call[name[datetime].datetime.now, parameter[]].replace, parameter[]] variable[right_now] assign[=] call[name[time_now].isoformat, parameter[]] variable[minutes_ago] assign[=] call[binary_operation[name[time_now] - call[name[datetime].timedelta, parameter[]]].isoformat, parameter[]] variable[formats] assign[=] call[name[opts].get, parameter[constant[formats], constant[json]]] variable[timezone] assign[=] call[name[opts].get, parameter[constant[timezone], constant[UTC]]] variable[time_from] assign[=] call[name[opts].get, parameter[constant[time_from], name[minutes_ago]]] variable[time_to] assign[=] call[name[opts].get, parameter[constant[time_to], name[right_now]]] variable[t_options] assign[=] dictionary[[<ast.Constant object at 0x7da204564880>, <ast.Constant object at 0x7da204565ed0>, <ast.Constant object at 0x7da204567250>, <ast.Constant object at 0x7da204567d30>, <ast.Constant object at 0x7da204566920>], [<ast.Name object at 0x7da18f00c2b0>, <ast.Name object at 0x7da18f00f3d0>, <ast.Name object at 0x7da18f00c700>, <ast.Name object at 0x7da18f00cc10>, <ast.Name object at 0x7da18f00fa00>]] variable[options] assign[=] call[constant[&].join, parameter[<ast.ListComp object at 0x7da18f00e830>]] variable[req] assign[=] call[name[requests].get, parameter[binary_operation[constant[%s?%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18f00ccd0>, <ast.Name object at 0x7da18f00c220>]]]]] <ast.Try object at 0x7da18f00ea40> return[dictionary[[<ast.Constant object at 0x7da18f09c730>, <ast.Constant object at 0x7da18f09da80>, <ast.Constant object at 0x7da18f09db40>], [<ast.Name object at 0x7da18f09e230>, <ast.Attribute object at 0x7da18f09d870>, <ast.Attribute object at 0x7da18f00dc60>]]]
keyword[def] identifier[query] ( identifier[self] , identifier[criteria] ,** identifier[opts] ): literal[string] identifier[time_now] = identifier[datetime] . identifier[datetime] . identifier[now] (). identifier[replace] ( identifier[second] = literal[int] , identifier[microsecond] = literal[int] ) identifier[right_now] = identifier[time_now] . identifier[isoformat] () identifier[minutes_ago] =( identifier[time_now] - identifier[datetime] . identifier[timedelta] ( identifier[minutes] = literal[int] )). identifier[isoformat] () identifier[formats] = identifier[opts] . identifier[get] ( literal[string] , literal[string] ) identifier[timezone] = identifier[opts] . identifier[get] ( literal[string] , literal[string] ) identifier[time_from] = identifier[opts] . identifier[get] ( literal[string] , identifier[minutes_ago] ) identifier[time_to] = identifier[opts] . identifier[get] ( literal[string] , identifier[right_now] ) identifier[t_options] ={ literal[string] : identifier[criteria] , literal[string] : identifier[formats] , literal[string] : identifier[timezone] , literal[string] : identifier[time_from] , literal[string] : identifier[time_to] , } identifier[options] = literal[string] . identifier[join] ([ literal[string] . identifier[format] ( identifier[k] , identifier[v] ) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[t_options] . identifier[items] ()]) identifier[req] = identifier[requests] . identifier[get] ( literal[string] % ( identifier[self] . identifier[url] , identifier[options] ), identifier[auth] = identifier[self] . identifier[auth] ) keyword[try] : identifier[data] = identifier[req] . identifier[json] () keyword[except] identifier[json] . identifier[decoder] . identifier[JSONDecodeError] : identifier[data] =[] keyword[return] { literal[string] : identifier[data] , literal[string] : identifier[req] . identifier[status_code] , literal[string] : identifier[req] . identifier[reason] , }
def query(self, criteria, **opts): """ Returns a dict of the query, including the results :param critera: string of search criteria :param **opts: :formats: json/xml (default: json) :timezone: timezone to use (default: UTC) :time_from: 15m ago from now (datetime) :time_to: right now (datetime) """ time_now = datetime.datetime.now().replace(second=0, microsecond=0) right_now = time_now.isoformat() minutes_ago = (time_now - datetime.timedelta(minutes=15)).isoformat() formats = opts.get('formats', 'json') timezone = opts.get('timezone', 'UTC') time_from = opts.get('time_from', minutes_ago) time_to = opts.get('time_to', right_now) # setting up options t_options = {'q': criteria, 'format': formats, 'tz': timezone, 'from': time_from, 'to': time_to} options = '&'.join(['{}={}'.format(k, v) for (k, v) in t_options.items()]) req = requests.get('%s?%s' % (self.url, options), auth=self.auth) try: data = req.json() # depends on [control=['try'], data=[]] except json.decoder.JSONDecodeError: data = [] # depends on [control=['except'], data=[]] return {'data': data, 'response': req.status_code, 'reason': req.reason}
def get_assets_by_record_type(self, asset_record_type=None): """Gets an ``AssetList`` containing the given asset record ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. arg: asset_record_type (osid.type.Type): an asset record type return: (osid.repository.AssetList) - the returned ``Asset list`` raise: NullArgument - ``asset_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ return AssetList(self._provider_session.get_assets_by_record_type(asset_record_type), self._config_map)
def function[get_assets_by_record_type, parameter[self, asset_record_type]]: constant[Gets an ``AssetList`` containing the given asset record ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. arg: asset_record_type (osid.type.Type): an asset record type return: (osid.repository.AssetList) - the returned ``Asset list`` raise: NullArgument - ``asset_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* ] return[call[name[AssetList], parameter[call[name[self]._provider_session.get_assets_by_record_type, parameter[name[asset_record_type]]], name[self]._config_map]]]
keyword[def] identifier[get_assets_by_record_type] ( identifier[self] , identifier[asset_record_type] = keyword[None] ): literal[string] keyword[return] identifier[AssetList] ( identifier[self] . identifier[_provider_session] . identifier[get_assets_by_record_type] ( identifier[asset_record_type] ), identifier[self] . identifier[_config_map] )
def get_assets_by_record_type(self, asset_record_type=None): """Gets an ``AssetList`` containing the given asset record ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise, the returned list may contain only those assets that are accessible through this session. arg: asset_record_type (osid.type.Type): an asset record type return: (osid.repository.AssetList) - the returned ``Asset list`` raise: NullArgument - ``asset_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ return AssetList(self._provider_session.get_assets_by_record_type(asset_record_type), self._config_map)
def hxzip_decode(data_size, data): """Decode HxZip data stream :param int data_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array output: an array of ``numpy.uint8`` """ import zlib data_stream = zlib.decompress(data) output = numpy.array(struct.unpack('<{}B'.format(len(data_stream)), data_stream), dtype=numpy.uint8) assert len(output) == data_size return output
def function[hxzip_decode, parameter[data_size, data]]: constant[Decode HxZip data stream :param int data_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array output: an array of ``numpy.uint8`` ] import module[zlib] variable[data_stream] assign[=] call[name[zlib].decompress, parameter[name[data]]] variable[output] assign[=] call[name[numpy].array, parameter[call[name[struct].unpack, parameter[call[constant[<{}B].format, parameter[call[name[len], parameter[name[data_stream]]]]], name[data_stream]]]]] assert[compare[call[name[len], parameter[name[output]]] equal[==] name[data_size]]] return[name[output]]
keyword[def] identifier[hxzip_decode] ( identifier[data_size] , identifier[data] ): literal[string] keyword[import] identifier[zlib] identifier[data_stream] = identifier[zlib] . identifier[decompress] ( identifier[data] ) identifier[output] = identifier[numpy] . identifier[array] ( identifier[struct] . identifier[unpack] ( literal[string] . identifier[format] ( identifier[len] ( identifier[data_stream] )), identifier[data_stream] ), identifier[dtype] = identifier[numpy] . identifier[uint8] ) keyword[assert] identifier[len] ( identifier[output] )== identifier[data_size] keyword[return] identifier[output]
def hxzip_decode(data_size, data): """Decode HxZip data stream :param int data_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array output: an array of ``numpy.uint8`` """ import zlib data_stream = zlib.decompress(data) output = numpy.array(struct.unpack('<{}B'.format(len(data_stream)), data_stream), dtype=numpy.uint8) assert len(output) == data_size return output
def rule_match(component, cmd): '''see if one rule component matches''' if component == cmd: return True expanded = rule_expand(component, cmd) if cmd in expanded: return True return False
def function[rule_match, parameter[component, cmd]]: constant[see if one rule component matches] if compare[name[component] equal[==] name[cmd]] begin[:] return[constant[True]] variable[expanded] assign[=] call[name[rule_expand], parameter[name[component], name[cmd]]] if compare[name[cmd] in name[expanded]] begin[:] return[constant[True]] return[constant[False]]
keyword[def] identifier[rule_match] ( identifier[component] , identifier[cmd] ): literal[string] keyword[if] identifier[component] == identifier[cmd] : keyword[return] keyword[True] identifier[expanded] = identifier[rule_expand] ( identifier[component] , identifier[cmd] ) keyword[if] identifier[cmd] keyword[in] identifier[expanded] : keyword[return] keyword[True] keyword[return] keyword[False]
def rule_match(component, cmd): """see if one rule component matches""" if component == cmd: return True # depends on [control=['if'], data=[]] expanded = rule_expand(component, cmd) if cmd in expanded: return True # depends on [control=['if'], data=[]] return False
def interp(self, *args): """ This method takes a list of SQL snippets and returns a SQL statement and a list of bind variables to be passed to the DB API's execute method. """ sql = "" bind = () def _append_sql(sql, part): "Handle whitespace when appending properly." if len(sql) == 0: return part elif sql[-1] == ' ': return sql + part else: return sql + ' ' + part for arg in args: if type(arg) is str: # Strings are treated as raw SQL. sql = _append_sql(sql, arg) elif isinstance(arg, Esc): # If this is an instance of Esc, ask the object # how to represent the data given the context. arg_sql, arg_bind = arg.to_string(sql) sql = _append_sql(sql, arg_sql) bind += arg_bind else: # Any argument given that is not a string or Esc # is an error. arg_sql, arg_bind = self.esc(arg).to_string(sql) sql = _append_sql(sql, arg_sql) bind += arg_bind return (sql, bind)
def function[interp, parameter[self]]: constant[ This method takes a list of SQL snippets and returns a SQL statement and a list of bind variables to be passed to the DB API's execute method. ] variable[sql] assign[=] constant[] variable[bind] assign[=] tuple[[]] def function[_append_sql, parameter[sql, part]]: constant[Handle whitespace when appending properly.] if compare[call[name[len], parameter[name[sql]]] equal[==] constant[0]] begin[:] return[name[part]] for taget[name[arg]] in starred[name[args]] begin[:] if compare[call[name[type], parameter[name[arg]]] is name[str]] begin[:] variable[sql] assign[=] call[name[_append_sql], parameter[name[sql], name[arg]]] return[tuple[[<ast.Name object at 0x7da18bc73760>, <ast.Name object at 0x7da18bc721a0>]]]
keyword[def] identifier[interp] ( identifier[self] ,* identifier[args] ): literal[string] identifier[sql] = literal[string] identifier[bind] =() keyword[def] identifier[_append_sql] ( identifier[sql] , identifier[part] ): literal[string] keyword[if] identifier[len] ( identifier[sql] )== literal[int] : keyword[return] identifier[part] keyword[elif] identifier[sql] [- literal[int] ]== literal[string] : keyword[return] identifier[sql] + identifier[part] keyword[else] : keyword[return] identifier[sql] + literal[string] + identifier[part] keyword[for] identifier[arg] keyword[in] identifier[args] : keyword[if] identifier[type] ( identifier[arg] ) keyword[is] identifier[str] : identifier[sql] = identifier[_append_sql] ( identifier[sql] , identifier[arg] ) keyword[elif] identifier[isinstance] ( identifier[arg] , identifier[Esc] ): identifier[arg_sql] , identifier[arg_bind] = identifier[arg] . identifier[to_string] ( identifier[sql] ) identifier[sql] = identifier[_append_sql] ( identifier[sql] , identifier[arg_sql] ) identifier[bind] += identifier[arg_bind] keyword[else] : identifier[arg_sql] , identifier[arg_bind] = identifier[self] . identifier[esc] ( identifier[arg] ). identifier[to_string] ( identifier[sql] ) identifier[sql] = identifier[_append_sql] ( identifier[sql] , identifier[arg_sql] ) identifier[bind] += identifier[arg_bind] keyword[return] ( identifier[sql] , identifier[bind] )
def interp(self, *args): """ This method takes a list of SQL snippets and returns a SQL statement and a list of bind variables to be passed to the DB API's execute method. """ sql = '' bind = () def _append_sql(sql, part): """Handle whitespace when appending properly.""" if len(sql) == 0: return part # depends on [control=['if'], data=[]] elif sql[-1] == ' ': return sql + part # depends on [control=['if'], data=[]] else: return sql + ' ' + part for arg in args: if type(arg) is str: # Strings are treated as raw SQL. sql = _append_sql(sql, arg) # depends on [control=['if'], data=[]] elif isinstance(arg, Esc): # If this is an instance of Esc, ask the object # how to represent the data given the context. (arg_sql, arg_bind) = arg.to_string(sql) sql = _append_sql(sql, arg_sql) bind += arg_bind # depends on [control=['if'], data=[]] else: # Any argument given that is not a string or Esc # is an error. (arg_sql, arg_bind) = self.esc(arg).to_string(sql) sql = _append_sql(sql, arg_sql) bind += arg_bind # depends on [control=['for'], data=['arg']] return (sql, bind)
def pause(self): """Set the execution mode to paused """ if self.state_machine_manager.active_state_machine_id is None: logger.info("'Pause' is not a valid action to initiate state machine execution.") return if self.state_machine_manager.get_active_state_machine() is not None: self.state_machine_manager.get_active_state_machine().root_state.recursively_pause_states() logger.debug("Pause execution ...") self.set_execution_mode(StateMachineExecutionStatus.PAUSED)
def function[pause, parameter[self]]: constant[Set the execution mode to paused ] if compare[name[self].state_machine_manager.active_state_machine_id is constant[None]] begin[:] call[name[logger].info, parameter[constant['Pause' is not a valid action to initiate state machine execution.]]] return[None] if compare[call[name[self].state_machine_manager.get_active_state_machine, parameter[]] is_not constant[None]] begin[:] call[call[name[self].state_machine_manager.get_active_state_machine, parameter[]].root_state.recursively_pause_states, parameter[]] call[name[logger].debug, parameter[constant[Pause execution ...]]] call[name[self].set_execution_mode, parameter[name[StateMachineExecutionStatus].PAUSED]]
keyword[def] identifier[pause] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[state_machine_manager] . identifier[active_state_machine_id] keyword[is] keyword[None] : identifier[logger] . identifier[info] ( literal[string] ) keyword[return] keyword[if] identifier[self] . identifier[state_machine_manager] . identifier[get_active_state_machine] () keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[state_machine_manager] . identifier[get_active_state_machine] (). identifier[root_state] . identifier[recursively_pause_states] () identifier[logger] . identifier[debug] ( literal[string] ) identifier[self] . identifier[set_execution_mode] ( identifier[StateMachineExecutionStatus] . identifier[PAUSED] )
def pause(self): """Set the execution mode to paused """ if self.state_machine_manager.active_state_machine_id is None: logger.info("'Pause' is not a valid action to initiate state machine execution.") return # depends on [control=['if'], data=[]] if self.state_machine_manager.get_active_state_machine() is not None: self.state_machine_manager.get_active_state_machine().root_state.recursively_pause_states() # depends on [control=['if'], data=[]] logger.debug('Pause execution ...') self.set_execution_mode(StateMachineExecutionStatus.PAUSED)
def predict_on_batch(self, data: Union[list, tuple], return_indexes: bool = False) -> List[List[str]]: """ Makes predictions on a single batch Args: data: a batch of word sequences together with additional inputs return_indexes: whether to return tag indexes in vocabulary or tags themselves Returns: a batch of label sequences """ X = self._transform_batch(data) objects_number, lengths = len(X[0]), [len(elem) for elem in data[0]] Y = self.model_.predict_on_batch(X) labels = np.argmax(Y, axis=-1) answer: List[List[str]] = [None] * objects_number for i, (elem, length) in enumerate(zip(labels, lengths)): elem = elem[:length] answer[i] = elem if return_indexes else self.tags.idxs2toks(elem) return answer
def function[predict_on_batch, parameter[self, data, return_indexes]]: constant[ Makes predictions on a single batch Args: data: a batch of word sequences together with additional inputs return_indexes: whether to return tag indexes in vocabulary or tags themselves Returns: a batch of label sequences ] variable[X] assign[=] call[name[self]._transform_batch, parameter[name[data]]] <ast.Tuple object at 0x7da1b03564d0> assign[=] tuple[[<ast.Call object at 0x7da1b0354760>, <ast.ListComp object at 0x7da1b03551b0>]] variable[Y] assign[=] call[name[self].model_.predict_on_batch, parameter[name[X]]] variable[labels] assign[=] call[name[np].argmax, parameter[name[Y]]] <ast.AnnAssign object at 0x7da1b0356b00> for taget[tuple[[<ast.Name object at 0x7da1b0354910>, <ast.Tuple object at 0x7da1b0355f60>]]] in starred[call[name[enumerate], parameter[call[name[zip], parameter[name[labels], name[lengths]]]]]] begin[:] variable[elem] assign[=] call[name[elem]][<ast.Slice object at 0x7da1b03550c0>] call[name[answer]][name[i]] assign[=] <ast.IfExp object at 0x7da1b0357ca0> return[name[answer]]
keyword[def] identifier[predict_on_batch] ( identifier[self] , identifier[data] : identifier[Union] [ identifier[list] , identifier[tuple] ], identifier[return_indexes] : identifier[bool] = keyword[False] )-> identifier[List] [ identifier[List] [ identifier[str] ]]: literal[string] identifier[X] = identifier[self] . identifier[_transform_batch] ( identifier[data] ) identifier[objects_number] , identifier[lengths] = identifier[len] ( identifier[X] [ literal[int] ]),[ identifier[len] ( identifier[elem] ) keyword[for] identifier[elem] keyword[in] identifier[data] [ literal[int] ]] identifier[Y] = identifier[self] . identifier[model_] . identifier[predict_on_batch] ( identifier[X] ) identifier[labels] = identifier[np] . identifier[argmax] ( identifier[Y] , identifier[axis] =- literal[int] ) identifier[answer] : identifier[List] [ identifier[List] [ identifier[str] ]]=[ keyword[None] ]* identifier[objects_number] keyword[for] identifier[i] ,( identifier[elem] , identifier[length] ) keyword[in] identifier[enumerate] ( identifier[zip] ( identifier[labels] , identifier[lengths] )): identifier[elem] = identifier[elem] [: identifier[length] ] identifier[answer] [ identifier[i] ]= identifier[elem] keyword[if] identifier[return_indexes] keyword[else] identifier[self] . identifier[tags] . identifier[idxs2toks] ( identifier[elem] ) keyword[return] identifier[answer]
def predict_on_batch(self, data: Union[list, tuple], return_indexes: bool=False) -> List[List[str]]: """ Makes predictions on a single batch Args: data: a batch of word sequences together with additional inputs return_indexes: whether to return tag indexes in vocabulary or tags themselves Returns: a batch of label sequences """ X = self._transform_batch(data) (objects_number, lengths) = (len(X[0]), [len(elem) for elem in data[0]]) Y = self.model_.predict_on_batch(X) labels = np.argmax(Y, axis=-1) answer: List[List[str]] = [None] * objects_number for (i, (elem, length)) in enumerate(zip(labels, lengths)): elem = elem[:length] answer[i] = elem if return_indexes else self.tags.idxs2toks(elem) # depends on [control=['for'], data=[]] return answer
def delete_items_from_dict(d, to_delete): """Recursively deletes items from a dict, if the item's value(s) is in ``to_delete``. """ if not isinstance(to_delete, list): to_delete = [to_delete] if isinstance(d, dict): for single_to_delete in set(to_delete): if single_to_delete in d.values(): for k, v in d.copy().items(): if v == single_to_delete: del d[k] for k, v in d.items(): delete_items_from_dict(v, to_delete) elif isinstance(d, list): for i in d: delete_items_from_dict(i, to_delete) return remove_none(d)
def function[delete_items_from_dict, parameter[d, to_delete]]: constant[Recursively deletes items from a dict, if the item's value(s) is in ``to_delete``. ] if <ast.UnaryOp object at 0x7da207f9b640> begin[:] variable[to_delete] assign[=] list[[<ast.Name object at 0x7da207f99510>]] if call[name[isinstance], parameter[name[d], name[dict]]] begin[:] for taget[name[single_to_delete]] in starred[call[name[set], parameter[name[to_delete]]]] begin[:] if compare[name[single_to_delete] in call[name[d].values, parameter[]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da207f98250>, <ast.Name object at 0x7da207f9a650>]]] in starred[call[call[name[d].copy, parameter[]].items, parameter[]]] begin[:] if compare[name[v] equal[==] name[single_to_delete]] begin[:] <ast.Delete object at 0x7da207f9add0> for taget[tuple[[<ast.Name object at 0x7da207f99f30>, <ast.Name object at 0x7da207f99690>]]] in starred[call[name[d].items, parameter[]]] begin[:] call[name[delete_items_from_dict], parameter[name[v], name[to_delete]]] return[call[name[remove_none], parameter[name[d]]]]
keyword[def] identifier[delete_items_from_dict] ( identifier[d] , identifier[to_delete] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[to_delete] , identifier[list] ): identifier[to_delete] =[ identifier[to_delete] ] keyword[if] identifier[isinstance] ( identifier[d] , identifier[dict] ): keyword[for] identifier[single_to_delete] keyword[in] identifier[set] ( identifier[to_delete] ): keyword[if] identifier[single_to_delete] keyword[in] identifier[d] . identifier[values] (): keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d] . identifier[copy] (). identifier[items] (): keyword[if] identifier[v] == identifier[single_to_delete] : keyword[del] identifier[d] [ identifier[k] ] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d] . identifier[items] (): identifier[delete_items_from_dict] ( identifier[v] , identifier[to_delete] ) keyword[elif] identifier[isinstance] ( identifier[d] , identifier[list] ): keyword[for] identifier[i] keyword[in] identifier[d] : identifier[delete_items_from_dict] ( identifier[i] , identifier[to_delete] ) keyword[return] identifier[remove_none] ( identifier[d] )
def delete_items_from_dict(d, to_delete): """Recursively deletes items from a dict, if the item's value(s) is in ``to_delete``. """ if not isinstance(to_delete, list): to_delete = [to_delete] # depends on [control=['if'], data=[]] if isinstance(d, dict): for single_to_delete in set(to_delete): if single_to_delete in d.values(): for (k, v) in d.copy().items(): if v == single_to_delete: del d[k] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=['single_to_delete']] # depends on [control=['for'], data=['single_to_delete']] for (k, v) in d.items(): delete_items_from_dict(v, to_delete) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]] elif isinstance(d, list): for i in d: delete_items_from_dict(i, to_delete) # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=[]] return remove_none(d)
def coords_from_query(query): """Transform a query line into a (lng, lat) pair of coordinates.""" try: coords = json.loads(query) except ValueError: vals = re.split(r'[,\s]+', query.strip()) coords = [float(v) for v in vals] return tuple(coords[:2])
def function[coords_from_query, parameter[query]]: constant[Transform a query line into a (lng, lat) pair of coordinates.] <ast.Try object at 0x7da1b12a8430> return[call[name[tuple], parameter[call[name[coords]][<ast.Slice object at 0x7da1b12c6fe0>]]]]
keyword[def] identifier[coords_from_query] ( identifier[query] ): literal[string] keyword[try] : identifier[coords] = identifier[json] . identifier[loads] ( identifier[query] ) keyword[except] identifier[ValueError] : identifier[vals] = identifier[re] . identifier[split] ( literal[string] , identifier[query] . identifier[strip] ()) identifier[coords] =[ identifier[float] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[vals] ] keyword[return] identifier[tuple] ( identifier[coords] [: literal[int] ])
def coords_from_query(query): """Transform a query line into a (lng, lat) pair of coordinates.""" try: coords = json.loads(query) # depends on [control=['try'], data=[]] except ValueError: vals = re.split('[,\\s]+', query.strip()) coords = [float(v) for v in vals] # depends on [control=['except'], data=[]] return tuple(coords[:2])
def depth_first_sub(expr,values): "replace SubLit with literals in expr. (expr is mutated)." arr=treepath.sub_slots(expr,lambda elt:elt is sqparse2.SubLit) if len(arr)!=len(values): raise ValueError('len',len(arr),len(values)) for path,val in zip(arr,values): # todo: does ArrayLit get us anything? tree traversal? if isinstance(val,(basestring,int,float,type(None),dict)): expr[path] = sqparse2.Literal(val) elif isinstance(val,(list,tuple)): expr[path] = sqparse2.ArrayLit(val) else: raise TypeError('unk_sub_type',type(val),val) # pragma: no cover return expr
def function[depth_first_sub, parameter[expr, values]]: constant[replace SubLit with literals in expr. (expr is mutated).] variable[arr] assign[=] call[name[treepath].sub_slots, parameter[name[expr], <ast.Lambda object at 0x7da20eb2b070>]] if compare[call[name[len], parameter[name[arr]]] not_equal[!=] call[name[len], parameter[name[values]]]] begin[:] <ast.Raise object at 0x7da18f721cc0> for taget[tuple[[<ast.Name object at 0x7da18f7201f0>, <ast.Name object at 0x7da18f720460>]]] in starred[call[name[zip], parameter[name[arr], name[values]]]] begin[:] if call[name[isinstance], parameter[name[val], tuple[[<ast.Name object at 0x7da18f7207f0>, <ast.Name object at 0x7da18f7223b0>, <ast.Name object at 0x7da18f7230d0>, <ast.Call object at 0x7da18f7218a0>, <ast.Name object at 0x7da18f723550>]]]] begin[:] call[name[expr]][name[path]] assign[=] call[name[sqparse2].Literal, parameter[name[val]]] return[name[expr]]
keyword[def] identifier[depth_first_sub] ( identifier[expr] , identifier[values] ): literal[string] identifier[arr] = identifier[treepath] . identifier[sub_slots] ( identifier[expr] , keyword[lambda] identifier[elt] : identifier[elt] keyword[is] identifier[sqparse2] . identifier[SubLit] ) keyword[if] identifier[len] ( identifier[arr] )!= identifier[len] ( identifier[values] ): keyword[raise] identifier[ValueError] ( literal[string] , identifier[len] ( identifier[arr] ), identifier[len] ( identifier[values] )) keyword[for] identifier[path] , identifier[val] keyword[in] identifier[zip] ( identifier[arr] , identifier[values] ): keyword[if] identifier[isinstance] ( identifier[val] ,( identifier[basestring] , identifier[int] , identifier[float] , identifier[type] ( keyword[None] ), identifier[dict] )): identifier[expr] [ identifier[path] ]= identifier[sqparse2] . identifier[Literal] ( identifier[val] ) keyword[elif] identifier[isinstance] ( identifier[val] ,( identifier[list] , identifier[tuple] )): identifier[expr] [ identifier[path] ]= identifier[sqparse2] . identifier[ArrayLit] ( identifier[val] ) keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] , identifier[type] ( identifier[val] ), identifier[val] ) keyword[return] identifier[expr]
def depth_first_sub(expr, values): """replace SubLit with literals in expr. (expr is mutated).""" arr = treepath.sub_slots(expr, lambda elt: elt is sqparse2.SubLit) if len(arr) != len(values): raise ValueError('len', len(arr), len(values)) # depends on [control=['if'], data=[]] for (path, val) in zip(arr, values): # todo: does ArrayLit get us anything? tree traversal? if isinstance(val, (basestring, int, float, type(None), dict)): expr[path] = sqparse2.Literal(val) # depends on [control=['if'], data=[]] elif isinstance(val, (list, tuple)): expr[path] = sqparse2.ArrayLit(val) # depends on [control=['if'], data=[]] else: raise TypeError('unk_sub_type', type(val), val) # pragma: no cover # depends on [control=['for'], data=[]] return expr
def send_vdp_assoc(self, vsiid=None, mgrid=None, typeid=None, typeid_ver=None, vsiid_frmt=vdp_const.VDP_VSIFRMT_UUID, filter_frmt=vdp_const.VDP_FILTER_GIDMACVID, gid=0, mac="", vlan=0, oui_id="", oui_data="", sw_resp=False): """Sends the VDP Associate Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more detailed information :param vsiid: VSI value, Only UUID supported for now :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsiid_frmt: Format of the following VSI argument :param filter_frmt: Filter Format. Only <GID,MAC,VID> supported for now :param gid: Group ID the vNIC belongs to :param mac: MAC Address of the vNIC :param vlan: VLAN of the vNIC :param oui_id: OUI Type :param oui_data: OUI Data :param sw_resp: Flag indicating if response is required from the daemon :return vlan: VLAN value returned by vdptool which in turn is given : by Switch """ if sw_resp and filter_frmt == vdp_const.VDP_FILTER_GIDMACVID: reply = self.send_vdp_query_msg("assoc", mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data) vlan_resp, fail_reason = self.get_vlan_from_query_reply( reply, vsiid, mac) if vlan_resp != constants.INVALID_VLAN: return vlan_resp, fail_reason reply = self.send_vdp_msg("assoc", mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data, sw_resp) if sw_resp: vlan, fail_reason = self.get_vlan_from_associate_reply( reply, vsiid, mac) return vlan, fail_reason return None, None
def function[send_vdp_assoc, parameter[self, vsiid, mgrid, typeid, typeid_ver, vsiid_frmt, filter_frmt, gid, mac, vlan, oui_id, oui_data, sw_resp]]: constant[Sends the VDP Associate Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more detailed information :param vsiid: VSI value, Only UUID supported for now :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsiid_frmt: Format of the following VSI argument :param filter_frmt: Filter Format. Only <GID,MAC,VID> supported for now :param gid: Group ID the vNIC belongs to :param mac: MAC Address of the vNIC :param vlan: VLAN of the vNIC :param oui_id: OUI Type :param oui_data: OUI Data :param sw_resp: Flag indicating if response is required from the daemon :return vlan: VLAN value returned by vdptool which in turn is given : by Switch ] if <ast.BoolOp object at 0x7da207f98940> begin[:] variable[reply] assign[=] call[name[self].send_vdp_query_msg, parameter[constant[assoc], name[mgrid], name[typeid], name[typeid_ver], name[vsiid_frmt], name[vsiid], name[filter_frmt], name[gid], name[mac], name[vlan], name[oui_id], name[oui_data]]] <ast.Tuple object at 0x7da1b1b7ea10> assign[=] call[name[self].get_vlan_from_query_reply, parameter[name[reply], name[vsiid], name[mac]]] if compare[name[vlan_resp] not_equal[!=] name[constants].INVALID_VLAN] begin[:] return[tuple[[<ast.Name object at 0x7da1b1b7d6c0>, <ast.Name object at 0x7da1b1b7f220>]]] variable[reply] assign[=] call[name[self].send_vdp_msg, parameter[constant[assoc], name[mgrid], name[typeid], name[typeid_ver], name[vsiid_frmt], name[vsiid], name[filter_frmt], name[gid], name[mac], name[vlan], name[oui_id], name[oui_data], name[sw_resp]]] if name[sw_resp] begin[:] <ast.Tuple object at 0x7da1b1b7f910> assign[=] call[name[self].get_vlan_from_associate_reply, parameter[name[reply], name[vsiid], name[mac]]] return[tuple[[<ast.Name object at 0x7da1b1be59c0>, <ast.Name object at 0x7da1b1be79d0>]]] return[tuple[[<ast.Constant object at 0x7da1b1be5c30>, <ast.Constant object at 0x7da1b1be7df0>]]]
keyword[def] identifier[send_vdp_assoc] ( identifier[self] , identifier[vsiid] = keyword[None] , identifier[mgrid] = keyword[None] , identifier[typeid] = keyword[None] , identifier[typeid_ver] = keyword[None] , identifier[vsiid_frmt] = identifier[vdp_const] . identifier[VDP_VSIFRMT_UUID] , identifier[filter_frmt] = identifier[vdp_const] . identifier[VDP_FILTER_GIDMACVID] , identifier[gid] = literal[int] , identifier[mac] = literal[string] , identifier[vlan] = literal[int] , identifier[oui_id] = literal[string] , identifier[oui_data] = literal[string] , identifier[sw_resp] = keyword[False] ): literal[string] keyword[if] identifier[sw_resp] keyword[and] identifier[filter_frmt] == identifier[vdp_const] . identifier[VDP_FILTER_GIDMACVID] : identifier[reply] = identifier[self] . identifier[send_vdp_query_msg] ( literal[string] , identifier[mgrid] , identifier[typeid] , identifier[typeid_ver] , identifier[vsiid_frmt] , identifier[vsiid] , identifier[filter_frmt] , identifier[gid] , identifier[mac] , identifier[vlan] , identifier[oui_id] , identifier[oui_data] ) identifier[vlan_resp] , identifier[fail_reason] = identifier[self] . identifier[get_vlan_from_query_reply] ( identifier[reply] , identifier[vsiid] , identifier[mac] ) keyword[if] identifier[vlan_resp] != identifier[constants] . identifier[INVALID_VLAN] : keyword[return] identifier[vlan_resp] , identifier[fail_reason] identifier[reply] = identifier[self] . identifier[send_vdp_msg] ( literal[string] , identifier[mgrid] , identifier[typeid] , identifier[typeid_ver] , identifier[vsiid_frmt] , identifier[vsiid] , identifier[filter_frmt] , identifier[gid] , identifier[mac] , identifier[vlan] , identifier[oui_id] , identifier[oui_data] , identifier[sw_resp] ) keyword[if] identifier[sw_resp] : identifier[vlan] , identifier[fail_reason] = identifier[self] . identifier[get_vlan_from_associate_reply] ( identifier[reply] , identifier[vsiid] , identifier[mac] ) keyword[return] identifier[vlan] , identifier[fail_reason] keyword[return] keyword[None] , keyword[None]
def send_vdp_assoc(self, vsiid=None, mgrid=None, typeid=None, typeid_ver=None, vsiid_frmt=vdp_const.VDP_VSIFRMT_UUID, filter_frmt=vdp_const.VDP_FILTER_GIDMACVID, gid=0, mac='', vlan=0, oui_id='', oui_data='', sw_resp=False): """Sends the VDP Associate Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more detailed information :param vsiid: VSI value, Only UUID supported for now :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsiid_frmt: Format of the following VSI argument :param filter_frmt: Filter Format. Only <GID,MAC,VID> supported for now :param gid: Group ID the vNIC belongs to :param mac: MAC Address of the vNIC :param vlan: VLAN of the vNIC :param oui_id: OUI Type :param oui_data: OUI Data :param sw_resp: Flag indicating if response is required from the daemon :return vlan: VLAN value returned by vdptool which in turn is given : by Switch """ if sw_resp and filter_frmt == vdp_const.VDP_FILTER_GIDMACVID: reply = self.send_vdp_query_msg('assoc', mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data) (vlan_resp, fail_reason) = self.get_vlan_from_query_reply(reply, vsiid, mac) if vlan_resp != constants.INVALID_VLAN: return (vlan_resp, fail_reason) # depends on [control=['if'], data=['vlan_resp']] # depends on [control=['if'], data=[]] reply = self.send_vdp_msg('assoc', mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data, sw_resp) if sw_resp: (vlan, fail_reason) = self.get_vlan_from_associate_reply(reply, vsiid, mac) return (vlan, fail_reason) # depends on [control=['if'], data=[]] return (None, None)
def replace(self, key, value, expire=0, noreply=None): """ The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional bool, True to not wait for the reply (defaults to self.default_noreply). Returns: If noreply is True, always returns True. Otherwise returns True if the value was stored and False if it wasn't (because the key didn't already exist). """ if noreply is None: noreply = self.default_noreply return self._store_cmd(b'replace', {key: value}, expire, noreply)[key]
def function[replace, parameter[self, key, value, expire, noreply]]: constant[ The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional bool, True to not wait for the reply (defaults to self.default_noreply). Returns: If noreply is True, always returns True. Otherwise returns True if the value was stored and False if it wasn't (because the key didn't already exist). ] if compare[name[noreply] is constant[None]] begin[:] variable[noreply] assign[=] name[self].default_noreply return[call[call[name[self]._store_cmd, parameter[constant[b'replace'], dictionary[[<ast.Name object at 0x7da18f09c730>], [<ast.Name object at 0x7da18f09f9a0>]], name[expire], name[noreply]]]][name[key]]]
keyword[def] identifier[replace] ( identifier[self] , identifier[key] , identifier[value] , identifier[expire] = literal[int] , identifier[noreply] = keyword[None] ): literal[string] keyword[if] identifier[noreply] keyword[is] keyword[None] : identifier[noreply] = identifier[self] . identifier[default_noreply] keyword[return] identifier[self] . identifier[_store_cmd] ( literal[string] ,{ identifier[key] : identifier[value] }, identifier[expire] , identifier[noreply] )[ identifier[key] ]
def replace(self, key, value, expire=0, noreply=None): """ The memcached "replace" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cache, or zero for no expiry (the default). noreply: optional bool, True to not wait for the reply (defaults to self.default_noreply). Returns: If noreply is True, always returns True. Otherwise returns True if the value was stored and False if it wasn't (because the key didn't already exist). """ if noreply is None: noreply = self.default_noreply # depends on [control=['if'], data=['noreply']] return self._store_cmd(b'replace', {key: value}, expire, noreply)[key]
def bug_suggestions_line(err, term_cache=None): """ Get Bug suggestions for a given TextLogError (err). Tries to extract a search term from a clean version of the given error's line. We build a search term from the cleaned line and use that to search for bugs. Returns a dictionary with the cleaned line, the generated search term, and any bugs found with said search term. """ if term_cache is None: term_cache = {} # remove the mozharness prefix clean_line = get_mozharness_substring(err.line) # get a meaningful search term out of the error line search_term = get_error_search_term(clean_line) bugs = dict(open_recent=[], all_others=[]) # collect open recent and all other bugs suggestions search_terms = [] if search_term: search_terms.append(search_term) if search_term not in term_cache: term_cache[search_term] = Bugscache.search(search_term) bugs = term_cache[search_term] if not bugs or not (bugs['open_recent'] or bugs['all_others']): # no suggestions, try to use # the crash signature as search term crash_signature = get_crash_signature(clean_line) if crash_signature: search_terms.append(crash_signature) if crash_signature not in term_cache: term_cache[crash_signature] = Bugscache.search(crash_signature) bugs = term_cache[crash_signature] # TODO: Rename 'search' to 'error_text' or similar, since that's # closer to what it actually represents (bug 1091060). return { "search": clean_line, "search_terms": search_terms, "bugs": bugs, }
def function[bug_suggestions_line, parameter[err, term_cache]]: constant[ Get Bug suggestions for a given TextLogError (err). Tries to extract a search term from a clean version of the given error's line. We build a search term from the cleaned line and use that to search for bugs. Returns a dictionary with the cleaned line, the generated search term, and any bugs found with said search term. ] if compare[name[term_cache] is constant[None]] begin[:] variable[term_cache] assign[=] dictionary[[], []] variable[clean_line] assign[=] call[name[get_mozharness_substring], parameter[name[err].line]] variable[search_term] assign[=] call[name[get_error_search_term], parameter[name[clean_line]]] variable[bugs] assign[=] call[name[dict], parameter[]] variable[search_terms] assign[=] list[[]] if name[search_term] begin[:] call[name[search_terms].append, parameter[name[search_term]]] if compare[name[search_term] <ast.NotIn object at 0x7da2590d7190> name[term_cache]] begin[:] call[name[term_cache]][name[search_term]] assign[=] call[name[Bugscache].search, parameter[name[search_term]]] variable[bugs] assign[=] call[name[term_cache]][name[search_term]] if <ast.BoolOp object at 0x7da1b08820e0> begin[:] variable[crash_signature] assign[=] call[name[get_crash_signature], parameter[name[clean_line]]] if name[crash_signature] begin[:] call[name[search_terms].append, parameter[name[crash_signature]]] if compare[name[crash_signature] <ast.NotIn object at 0x7da2590d7190> name[term_cache]] begin[:] call[name[term_cache]][name[crash_signature]] assign[=] call[name[Bugscache].search, parameter[name[crash_signature]]] variable[bugs] assign[=] call[name[term_cache]][name[crash_signature]] return[dictionary[[<ast.Constant object at 0x7da1b08a70d0>, <ast.Constant object at 0x7da1b08a7d00>, <ast.Constant object at 0x7da1b08a7280>], [<ast.Name object at 0x7da1b08a5930>, <ast.Name object at 0x7da1b08a6b00>, <ast.Name object at 0x7da1b08a6350>]]]
keyword[def] identifier[bug_suggestions_line] ( identifier[err] , identifier[term_cache] = keyword[None] ): literal[string] keyword[if] identifier[term_cache] keyword[is] keyword[None] : identifier[term_cache] ={} identifier[clean_line] = identifier[get_mozharness_substring] ( identifier[err] . identifier[line] ) identifier[search_term] = identifier[get_error_search_term] ( identifier[clean_line] ) identifier[bugs] = identifier[dict] ( identifier[open_recent] =[], identifier[all_others] =[]) identifier[search_terms] =[] keyword[if] identifier[search_term] : identifier[search_terms] . identifier[append] ( identifier[search_term] ) keyword[if] identifier[search_term] keyword[not] keyword[in] identifier[term_cache] : identifier[term_cache] [ identifier[search_term] ]= identifier[Bugscache] . identifier[search] ( identifier[search_term] ) identifier[bugs] = identifier[term_cache] [ identifier[search_term] ] keyword[if] keyword[not] identifier[bugs] keyword[or] keyword[not] ( identifier[bugs] [ literal[string] ] keyword[or] identifier[bugs] [ literal[string] ]): identifier[crash_signature] = identifier[get_crash_signature] ( identifier[clean_line] ) keyword[if] identifier[crash_signature] : identifier[search_terms] . identifier[append] ( identifier[crash_signature] ) keyword[if] identifier[crash_signature] keyword[not] keyword[in] identifier[term_cache] : identifier[term_cache] [ identifier[crash_signature] ]= identifier[Bugscache] . identifier[search] ( identifier[crash_signature] ) identifier[bugs] = identifier[term_cache] [ identifier[crash_signature] ] keyword[return] { literal[string] : identifier[clean_line] , literal[string] : identifier[search_terms] , literal[string] : identifier[bugs] , }
def bug_suggestions_line(err, term_cache=None): """ Get Bug suggestions for a given TextLogError (err). Tries to extract a search term from a clean version of the given error's line. We build a search term from the cleaned line and use that to search for bugs. Returns a dictionary with the cleaned line, the generated search term, and any bugs found with said search term. """ if term_cache is None: term_cache = {} # depends on [control=['if'], data=['term_cache']] # remove the mozharness prefix clean_line = get_mozharness_substring(err.line) # get a meaningful search term out of the error line search_term = get_error_search_term(clean_line) bugs = dict(open_recent=[], all_others=[]) # collect open recent and all other bugs suggestions search_terms = [] if search_term: search_terms.append(search_term) if search_term not in term_cache: term_cache[search_term] = Bugscache.search(search_term) # depends on [control=['if'], data=['search_term', 'term_cache']] bugs = term_cache[search_term] # depends on [control=['if'], data=[]] if not bugs or not (bugs['open_recent'] or bugs['all_others']): # no suggestions, try to use # the crash signature as search term crash_signature = get_crash_signature(clean_line) if crash_signature: search_terms.append(crash_signature) if crash_signature not in term_cache: term_cache[crash_signature] = Bugscache.search(crash_signature) # depends on [control=['if'], data=['crash_signature', 'term_cache']] bugs = term_cache[crash_signature] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # TODO: Rename 'search' to 'error_text' or similar, since that's # closer to what it actually represents (bug 1091060). return {'search': clean_line, 'search_terms': search_terms, 'bugs': bugs}
def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None: """Apply metadata groups to properties. Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which to add the controls. The second is a control group from which to read a list of controls to be added as name value pairs to the dict-path. """ pass
def function[apply_metadata_groups, parameter[self, properties, metatdata_groups]]: constant[Apply metadata groups to properties. Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which to add the controls. The second is a control group from which to read a list of controls to be added as name value pairs to the dict-path. ] pass
keyword[def] identifier[apply_metadata_groups] ( identifier[self] , identifier[properties] : identifier[typing] . identifier[Dict] , identifier[metatdata_groups] : identifier[typing] . identifier[Tuple] [ identifier[typing] . identifier[List] [ identifier[str] ], identifier[str] ])-> keyword[None] : literal[string] keyword[pass]
def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None: """Apply metadata groups to properties. Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which to add the controls. The second is a control group from which to read a list of controls to be added as name value pairs to the dict-path. """ pass
def build_kernel(self): """Build the MNN kernel. Build a mutual nearest neighbors kernel. Returns ------- K : kernel matrix, shape=[n_samples, n_samples] symmetric matrix with ones down the diagonal with no non-negative entries. """ tasklogger.log_start("subgraphs") self.subgraphs = [] from .api import Graph # iterate through sample ids for i, idx in enumerate(self.samples): tasklogger.log_debug("subgraph {}: sample {}, " "n = {}, knn = {}".format( i, idx, np.sum(self.sample_idx == idx), self.knn)) # select data for sample data = self.data_nu[self.sample_idx == idx] # build a kNN graph for cells within sample graph = Graph(data, n_pca=None, knn=self.knn, decay=self.decay, bandwidth=self.bandwidth, distance=self.distance, thresh=self.thresh, verbose=self.verbose, random_state=self.random_state, n_jobs=self.n_jobs, kernel_symm='+', initialize=True) self.subgraphs.append(graph) # append to list of subgraphs tasklogger.log_complete("subgraphs") tasklogger.log_start("MNN kernel") if self.thresh > 0 or self.decay is None: K = sparse.lil_matrix( (self.data_nu.shape[0], self.data_nu.shape[0])) else: K = np.zeros([self.data_nu.shape[0], self.data_nu.shape[0]]) for i, X in enumerate(self.subgraphs): K = set_submatrix(K, self.sample_idx == self.samples[i], self.sample_idx == self.samples[i], X.K) within_batch_norm = np.array(np.sum(X.K, 1)).flatten() for j, Y in enumerate(self.subgraphs): if i == j: continue tasklogger.log_start( "kernel from sample {} to {}".format(self.samples[i], self.samples[j])) Kij = Y.build_kernel_to_data( X.data_nu, knn=self.knn) between_batch_norm = np.array(np.sum(Kij, 1)).flatten() scale = np.minimum(1, within_batch_norm / between_batch_norm) * self.beta if sparse.issparse(Kij): Kij = Kij.multiply(scale[:, None]) else: Kij = Kij * scale[:, None] K = set_submatrix(K, self.sample_idx == self.samples[i], self.sample_idx == self.samples[j], Kij) tasklogger.log_complete( "kernel from sample {} to {}".format(self.samples[i], self.samples[j])) tasklogger.log_complete("MNN kernel") return K
def function[build_kernel, parameter[self]]: constant[Build the MNN kernel. Build a mutual nearest neighbors kernel. Returns ------- K : kernel matrix, shape=[n_samples, n_samples] symmetric matrix with ones down the diagonal with no non-negative entries. ] call[name[tasklogger].log_start, parameter[constant[subgraphs]]] name[self].subgraphs assign[=] list[[]] from relative_module[api] import module[Graph] for taget[tuple[[<ast.Name object at 0x7da1b0b6fbe0>, <ast.Name object at 0x7da1b0b6fbb0>]]] in starred[call[name[enumerate], parameter[name[self].samples]]] begin[:] call[name[tasklogger].log_debug, parameter[call[constant[subgraph {}: sample {}, n = {}, knn = {}].format, parameter[name[i], name[idx], call[name[np].sum, parameter[compare[name[self].sample_idx equal[==] name[idx]]]], name[self].knn]]]] variable[data] assign[=] call[name[self].data_nu][compare[name[self].sample_idx equal[==] name[idx]]] variable[graph] assign[=] call[name[Graph], parameter[name[data]]] call[name[self].subgraphs.append, parameter[name[graph]]] call[name[tasklogger].log_complete, parameter[constant[subgraphs]]] call[name[tasklogger].log_start, parameter[constant[MNN kernel]]] if <ast.BoolOp object at 0x7da1b0b6dba0> begin[:] variable[K] assign[=] call[name[sparse].lil_matrix, parameter[tuple[[<ast.Subscript object at 0x7da1b0b6d8d0>, <ast.Subscript object at 0x7da1b0b6d7e0>]]]] for taget[tuple[[<ast.Name object at 0x7da1b0b6d390>, <ast.Name object at 0x7da1b0b6d360>]]] in starred[call[name[enumerate], parameter[name[self].subgraphs]]] begin[:] variable[K] assign[=] call[name[set_submatrix], parameter[name[K], compare[name[self].sample_idx equal[==] call[name[self].samples][name[i]]], compare[name[self].sample_idx equal[==] call[name[self].samples][name[i]]], name[X].K]] variable[within_batch_norm] assign[=] call[call[name[np].array, parameter[call[name[np].sum, parameter[name[X].K, constant[1]]]]].flatten, parameter[]] for taget[tuple[[<ast.Name object at 0x7da1b0b6cbb0>, <ast.Name object at 0x7da1b0b6cb80>]]] in starred[call[name[enumerate], parameter[name[self].subgraphs]]] begin[:] if compare[name[i] equal[==] name[j]] begin[:] continue call[name[tasklogger].log_start, parameter[call[constant[kernel from sample {} to {}].format, parameter[call[name[self].samples][name[i]], call[name[self].samples][name[j]]]]]] variable[Kij] assign[=] call[name[Y].build_kernel_to_data, parameter[name[X].data_nu]] variable[between_batch_norm] assign[=] call[call[name[np].array, parameter[call[name[np].sum, parameter[name[Kij], constant[1]]]]].flatten, parameter[]] variable[scale] assign[=] binary_operation[call[name[np].minimum, parameter[constant[1], binary_operation[name[within_batch_norm] / name[between_batch_norm]]]] * name[self].beta] if call[name[sparse].issparse, parameter[name[Kij]]] begin[:] variable[Kij] assign[=] call[name[Kij].multiply, parameter[call[name[scale]][tuple[[<ast.Slice object at 0x7da1b0b6c910>, <ast.Constant object at 0x7da1b0b6c8e0>]]]]] variable[K] assign[=] call[name[set_submatrix], parameter[name[K], compare[name[self].sample_idx equal[==] call[name[self].samples][name[i]]], compare[name[self].sample_idx equal[==] call[name[self].samples][name[j]]], name[Kij]]] call[name[tasklogger].log_complete, parameter[call[constant[kernel from sample {} to {}].format, parameter[call[name[self].samples][name[i]], call[name[self].samples][name[j]]]]]] call[name[tasklogger].log_complete, parameter[constant[MNN kernel]]] return[name[K]]
keyword[def] identifier[build_kernel] ( identifier[self] ): literal[string] identifier[tasklogger] . identifier[log_start] ( literal[string] ) identifier[self] . identifier[subgraphs] =[] keyword[from] . identifier[api] keyword[import] identifier[Graph] keyword[for] identifier[i] , identifier[idx] keyword[in] identifier[enumerate] ( identifier[self] . identifier[samples] ): identifier[tasklogger] . identifier[log_debug] ( literal[string] literal[string] . identifier[format] ( identifier[i] , identifier[idx] , identifier[np] . identifier[sum] ( identifier[self] . identifier[sample_idx] == identifier[idx] ), identifier[self] . identifier[knn] )) identifier[data] = identifier[self] . identifier[data_nu] [ identifier[self] . identifier[sample_idx] == identifier[idx] ] identifier[graph] = identifier[Graph] ( identifier[data] , identifier[n_pca] = keyword[None] , identifier[knn] = identifier[self] . identifier[knn] , identifier[decay] = identifier[self] . identifier[decay] , identifier[bandwidth] = identifier[self] . identifier[bandwidth] , identifier[distance] = identifier[self] . identifier[distance] , identifier[thresh] = identifier[self] . identifier[thresh] , identifier[verbose] = identifier[self] . identifier[verbose] , identifier[random_state] = identifier[self] . identifier[random_state] , identifier[n_jobs] = identifier[self] . identifier[n_jobs] , identifier[kernel_symm] = literal[string] , identifier[initialize] = keyword[True] ) identifier[self] . identifier[subgraphs] . identifier[append] ( identifier[graph] ) identifier[tasklogger] . identifier[log_complete] ( literal[string] ) identifier[tasklogger] . identifier[log_start] ( literal[string] ) keyword[if] identifier[self] . identifier[thresh] > literal[int] keyword[or] identifier[self] . identifier[decay] keyword[is] keyword[None] : identifier[K] = identifier[sparse] . identifier[lil_matrix] ( ( identifier[self] . identifier[data_nu] . identifier[shape] [ literal[int] ], identifier[self] . identifier[data_nu] . identifier[shape] [ literal[int] ])) keyword[else] : identifier[K] = identifier[np] . identifier[zeros] ([ identifier[self] . identifier[data_nu] . identifier[shape] [ literal[int] ], identifier[self] . identifier[data_nu] . identifier[shape] [ literal[int] ]]) keyword[for] identifier[i] , identifier[X] keyword[in] identifier[enumerate] ( identifier[self] . identifier[subgraphs] ): identifier[K] = identifier[set_submatrix] ( identifier[K] , identifier[self] . identifier[sample_idx] == identifier[self] . identifier[samples] [ identifier[i] ], identifier[self] . identifier[sample_idx] == identifier[self] . identifier[samples] [ identifier[i] ], identifier[X] . identifier[K] ) identifier[within_batch_norm] = identifier[np] . identifier[array] ( identifier[np] . identifier[sum] ( identifier[X] . identifier[K] , literal[int] )). identifier[flatten] () keyword[for] identifier[j] , identifier[Y] keyword[in] identifier[enumerate] ( identifier[self] . identifier[subgraphs] ): keyword[if] identifier[i] == identifier[j] : keyword[continue] identifier[tasklogger] . identifier[log_start] ( literal[string] . identifier[format] ( identifier[self] . identifier[samples] [ identifier[i] ], identifier[self] . identifier[samples] [ identifier[j] ])) identifier[Kij] = identifier[Y] . identifier[build_kernel_to_data] ( identifier[X] . identifier[data_nu] , identifier[knn] = identifier[self] . identifier[knn] ) identifier[between_batch_norm] = identifier[np] . identifier[array] ( identifier[np] . identifier[sum] ( identifier[Kij] , literal[int] )). identifier[flatten] () identifier[scale] = identifier[np] . identifier[minimum] ( literal[int] , identifier[within_batch_norm] / identifier[between_batch_norm] )* identifier[self] . identifier[beta] keyword[if] identifier[sparse] . identifier[issparse] ( identifier[Kij] ): identifier[Kij] = identifier[Kij] . identifier[multiply] ( identifier[scale] [:, keyword[None] ]) keyword[else] : identifier[Kij] = identifier[Kij] * identifier[scale] [:, keyword[None] ] identifier[K] = identifier[set_submatrix] ( identifier[K] , identifier[self] . identifier[sample_idx] == identifier[self] . identifier[samples] [ identifier[i] ], identifier[self] . identifier[sample_idx] == identifier[self] . identifier[samples] [ identifier[j] ], identifier[Kij] ) identifier[tasklogger] . identifier[log_complete] ( literal[string] . identifier[format] ( identifier[self] . identifier[samples] [ identifier[i] ], identifier[self] . identifier[samples] [ identifier[j] ])) identifier[tasklogger] . identifier[log_complete] ( literal[string] ) keyword[return] identifier[K]
def build_kernel(self): """Build the MNN kernel. Build a mutual nearest neighbors kernel. Returns ------- K : kernel matrix, shape=[n_samples, n_samples] symmetric matrix with ones down the diagonal with no non-negative entries. """ tasklogger.log_start('subgraphs') self.subgraphs = [] from .api import Graph # iterate through sample ids for (i, idx) in enumerate(self.samples): tasklogger.log_debug('subgraph {}: sample {}, n = {}, knn = {}'.format(i, idx, np.sum(self.sample_idx == idx), self.knn)) # select data for sample data = self.data_nu[self.sample_idx == idx] # build a kNN graph for cells within sample graph = Graph(data, n_pca=None, knn=self.knn, decay=self.decay, bandwidth=self.bandwidth, distance=self.distance, thresh=self.thresh, verbose=self.verbose, random_state=self.random_state, n_jobs=self.n_jobs, kernel_symm='+', initialize=True) self.subgraphs.append(graph) # append to list of subgraphs # depends on [control=['for'], data=[]] tasklogger.log_complete('subgraphs') tasklogger.log_start('MNN kernel') if self.thresh > 0 or self.decay is None: K = sparse.lil_matrix((self.data_nu.shape[0], self.data_nu.shape[0])) # depends on [control=['if'], data=[]] else: K = np.zeros([self.data_nu.shape[0], self.data_nu.shape[0]]) for (i, X) in enumerate(self.subgraphs): K = set_submatrix(K, self.sample_idx == self.samples[i], self.sample_idx == self.samples[i], X.K) within_batch_norm = np.array(np.sum(X.K, 1)).flatten() for (j, Y) in enumerate(self.subgraphs): if i == j: continue # depends on [control=['if'], data=[]] tasklogger.log_start('kernel from sample {} to {}'.format(self.samples[i], self.samples[j])) Kij = Y.build_kernel_to_data(X.data_nu, knn=self.knn) between_batch_norm = np.array(np.sum(Kij, 1)).flatten() scale = np.minimum(1, within_batch_norm / between_batch_norm) * self.beta if sparse.issparse(Kij): Kij = Kij.multiply(scale[:, None]) # depends on [control=['if'], data=[]] else: Kij = Kij * scale[:, None] K = set_submatrix(K, self.sample_idx == self.samples[i], self.sample_idx == self.samples[j], Kij) tasklogger.log_complete('kernel from sample {} to {}'.format(self.samples[i], self.samples[j])) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] tasklogger.log_complete('MNN kernel') return K
def collection(self, code): """ Retrieve the collection ids according to the given 3 letters acronym """ result = None result = self.dispatcher( 'get_collection', code=code ) if not result: logger.info('Collection not found for: %s', code) return None return result
def function[collection, parameter[self, code]]: constant[ Retrieve the collection ids according to the given 3 letters acronym ] variable[result] assign[=] constant[None] variable[result] assign[=] call[name[self].dispatcher, parameter[constant[get_collection]]] if <ast.UnaryOp object at 0x7da1b0ed5810> begin[:] call[name[logger].info, parameter[constant[Collection not found for: %s], name[code]]] return[constant[None]] return[name[result]]
keyword[def] identifier[collection] ( identifier[self] , identifier[code] ): literal[string] identifier[result] = keyword[None] identifier[result] = identifier[self] . identifier[dispatcher] ( literal[string] , identifier[code] = identifier[code] ) keyword[if] keyword[not] identifier[result] : identifier[logger] . identifier[info] ( literal[string] , identifier[code] ) keyword[return] keyword[None] keyword[return] identifier[result]
def collection(self, code): """ Retrieve the collection ids according to the given 3 letters acronym """ result = None result = self.dispatcher('get_collection', code=code) if not result: logger.info('Collection not found for: %s', code) return None # depends on [control=['if'], data=[]] return result
def _to_str(self, value, field_begin, field_len): """ Convert value (int) to a field string, considering precision. """ value_str = '{0:0{1}d}'.format(value, field_len) if self.precision is not None and \ self.precision < field_begin + field_len: # field is partly or completely affected by precision # -> replace insignificant digits with asterisks precision_index = max(0, self.precision - field_begin) value_str = value_str[:precision_index] + \ '*' * (field_len - precision_index) return value_str
def function[_to_str, parameter[self, value, field_begin, field_len]]: constant[ Convert value (int) to a field string, considering precision. ] variable[value_str] assign[=] call[constant[{0:0{1}d}].format, parameter[name[value], name[field_len]]] if <ast.BoolOp object at 0x7da18f09d480> begin[:] variable[precision_index] assign[=] call[name[max], parameter[constant[0], binary_operation[name[self].precision - name[field_begin]]]] variable[value_str] assign[=] binary_operation[call[name[value_str]][<ast.Slice object at 0x7da20c76c610>] + binary_operation[constant[*] * binary_operation[name[field_len] - name[precision_index]]]] return[name[value_str]]
keyword[def] identifier[_to_str] ( identifier[self] , identifier[value] , identifier[field_begin] , identifier[field_len] ): literal[string] identifier[value_str] = literal[string] . identifier[format] ( identifier[value] , identifier[field_len] ) keyword[if] identifier[self] . identifier[precision] keyword[is] keyword[not] keyword[None] keyword[and] identifier[self] . identifier[precision] < identifier[field_begin] + identifier[field_len] : identifier[precision_index] = identifier[max] ( literal[int] , identifier[self] . identifier[precision] - identifier[field_begin] ) identifier[value_str] = identifier[value_str] [: identifier[precision_index] ]+ literal[string] *( identifier[field_len] - identifier[precision_index] ) keyword[return] identifier[value_str]
def _to_str(self, value, field_begin, field_len): """ Convert value (int) to a field string, considering precision. """ value_str = '{0:0{1}d}'.format(value, field_len) if self.precision is not None and self.precision < field_begin + field_len: # field is partly or completely affected by precision # -> replace insignificant digits with asterisks precision_index = max(0, self.precision - field_begin) value_str = value_str[:precision_index] + '*' * (field_len - precision_index) # depends on [control=['if'], data=[]] return value_str
def before_content(self): """Called before parsing content. Push the class name onto the class name stack. Used to construct the full name for members. """ ChapelObject.before_content(self) if self.names: self.env.temp_data['chpl:class'] = self.names[0][0] self.clsname_set = True
def function[before_content, parameter[self]]: constant[Called before parsing content. Push the class name onto the class name stack. Used to construct the full name for members. ] call[name[ChapelObject].before_content, parameter[name[self]]] if name[self].names begin[:] call[name[self].env.temp_data][constant[chpl:class]] assign[=] call[call[name[self].names][constant[0]]][constant[0]] name[self].clsname_set assign[=] constant[True]
keyword[def] identifier[before_content] ( identifier[self] ): literal[string] identifier[ChapelObject] . identifier[before_content] ( identifier[self] ) keyword[if] identifier[self] . identifier[names] : identifier[self] . identifier[env] . identifier[temp_data] [ literal[string] ]= identifier[self] . identifier[names] [ literal[int] ][ literal[int] ] identifier[self] . identifier[clsname_set] = keyword[True]
def before_content(self): """Called before parsing content. Push the class name onto the class name stack. Used to construct the full name for members. """ ChapelObject.before_content(self) if self.names: self.env.temp_data['chpl:class'] = self.names[0][0] self.clsname_set = True # depends on [control=['if'], data=[]]
def geom_dup(geom): """Create duplicate geometry Needed to avoid segfault when passing geom around. See: http://trac.osgeo.org/gdal/wiki/PythonGotchas """ g = ogr.CreateGeometryFromWkt(geom.ExportToWkt()) g.AssignSpatialReference(geom.GetSpatialReference()) return g
def function[geom_dup, parameter[geom]]: constant[Create duplicate geometry Needed to avoid segfault when passing geom around. See: http://trac.osgeo.org/gdal/wiki/PythonGotchas ] variable[g] assign[=] call[name[ogr].CreateGeometryFromWkt, parameter[call[name[geom].ExportToWkt, parameter[]]]] call[name[g].AssignSpatialReference, parameter[call[name[geom].GetSpatialReference, parameter[]]]] return[name[g]]
keyword[def] identifier[geom_dup] ( identifier[geom] ): literal[string] identifier[g] = identifier[ogr] . identifier[CreateGeometryFromWkt] ( identifier[geom] . identifier[ExportToWkt] ()) identifier[g] . identifier[AssignSpatialReference] ( identifier[geom] . identifier[GetSpatialReference] ()) keyword[return] identifier[g]
def geom_dup(geom): """Create duplicate geometry Needed to avoid segfault when passing geom around. See: http://trac.osgeo.org/gdal/wiki/PythonGotchas """ g = ogr.CreateGeometryFromWkt(geom.ExportToWkt()) g.AssignSpatialReference(geom.GetSpatialReference()) return g
def to_XML(self): """ Serialize object back to XML string. Returns: str: String which should be same as original input, if everything\ works as expected. """ marcxml_template = """<record xmlns="http://www.loc.gov/MARC21/slim/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> $LEADER $CONTROL_FIELDS $DATA_FIELDS </record> """ oai_template = """<record> <metadata> <oai_marc> $LEADER$CONTROL_FIELDS $DATA_FIELDS </oai_marc> </metadata> </record> """ # serialize leader, if it is present and record is marc xml leader = self.leader if self.leader is not None else "" if leader: # print only visible leaders leader = "<leader>" + leader + "</leader>" # discard leader for oai if self.oai_marc: leader = "" # serialize xml_template = oai_template if self.oai_marc else marcxml_template xml_output = Template(xml_template).substitute( LEADER=leader.strip(), CONTROL_FIELDS=self._serialize_ctl_fields().strip(), DATA_FIELDS=self._serialize_data_fields().strip() ) return xml_output
def function[to_XML, parameter[self]]: constant[ Serialize object back to XML string. Returns: str: String which should be same as original input, if everything works as expected. ] variable[marcxml_template] assign[=] constant[<record xmlns="http://www.loc.gov/MARC21/slim/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> $LEADER $CONTROL_FIELDS $DATA_FIELDS </record> ] variable[oai_template] assign[=] constant[<record> <metadata> <oai_marc> $LEADER$CONTROL_FIELDS $DATA_FIELDS </oai_marc> </metadata> </record> ] variable[leader] assign[=] <ast.IfExp object at 0x7da1afef8b20> if name[leader] begin[:] variable[leader] assign[=] binary_operation[binary_operation[constant[<leader>] + name[leader]] + constant[</leader>]] if name[self].oai_marc begin[:] variable[leader] assign[=] constant[] variable[xml_template] assign[=] <ast.IfExp object at 0x7da1afe0d990> variable[xml_output] assign[=] call[call[name[Template], parameter[name[xml_template]]].substitute, parameter[]] return[name[xml_output]]
keyword[def] identifier[to_XML] ( identifier[self] ): literal[string] identifier[marcxml_template] = literal[string] identifier[oai_template] = literal[string] identifier[leader] = identifier[self] . identifier[leader] keyword[if] identifier[self] . identifier[leader] keyword[is] keyword[not] keyword[None] keyword[else] literal[string] keyword[if] identifier[leader] : identifier[leader] = literal[string] + identifier[leader] + literal[string] keyword[if] identifier[self] . identifier[oai_marc] : identifier[leader] = literal[string] identifier[xml_template] = identifier[oai_template] keyword[if] identifier[self] . identifier[oai_marc] keyword[else] identifier[marcxml_template] identifier[xml_output] = identifier[Template] ( identifier[xml_template] ). identifier[substitute] ( identifier[LEADER] = identifier[leader] . identifier[strip] (), identifier[CONTROL_FIELDS] = identifier[self] . identifier[_serialize_ctl_fields] (). identifier[strip] (), identifier[DATA_FIELDS] = identifier[self] . identifier[_serialize_data_fields] (). identifier[strip] () ) keyword[return] identifier[xml_output]
def to_XML(self): """ Serialize object back to XML string. Returns: str: String which should be same as original input, if everything works as expected. """ marcxml_template = '<record xmlns="http://www.loc.gov/MARC21/slim/"\nxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\nxsi:schemaLocation="http://www.loc.gov/MARC21/slim\nhttp://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">\n$LEADER\n$CONTROL_FIELDS\n$DATA_FIELDS\n</record>\n' oai_template = '<record>\n<metadata>\n<oai_marc>\n$LEADER$CONTROL_FIELDS\n$DATA_FIELDS\n</oai_marc>\n</metadata>\n</record>\n' # serialize leader, if it is present and record is marc xml leader = self.leader if self.leader is not None else '' if leader: # print only visible leaders leader = '<leader>' + leader + '</leader>' # depends on [control=['if'], data=[]] # discard leader for oai if self.oai_marc: leader = '' # depends on [control=['if'], data=[]] # serialize xml_template = oai_template if self.oai_marc else marcxml_template xml_output = Template(xml_template).substitute(LEADER=leader.strip(), CONTROL_FIELDS=self._serialize_ctl_fields().strip(), DATA_FIELDS=self._serialize_data_fields().strip()) return xml_output
def enum_mark_last(iterable, start=0): """ Returns a generator over iterable that tells whether the current item is the last one. Usage: >>> iterable = range(10) >>> for index, is_last, item in enum_mark_last(iterable): >>> print(index, item, end='\n' if is_last else ', ') """ it = iter(iterable) count = start try: last = next(it) except StopIteration: return for val in it: yield count, False, last last = val count += 1 yield count, True, last
def function[enum_mark_last, parameter[iterable, start]]: constant[ Returns a generator over iterable that tells whether the current item is the last one. Usage: >>> iterable = range(10) >>> for index, is_last, item in enum_mark_last(iterable): >>> print(index, item, end=' ' if is_last else ', ') ] variable[it] assign[=] call[name[iter], parameter[name[iterable]]] variable[count] assign[=] name[start] <ast.Try object at 0x7da2054a7610> for taget[name[val]] in starred[name[it]] begin[:] <ast.Yield object at 0x7da2054a6e90> variable[last] assign[=] name[val] <ast.AugAssign object at 0x7da2054a6fe0> <ast.Yield object at 0x7da2054a4be0>
keyword[def] identifier[enum_mark_last] ( identifier[iterable] , identifier[start] = literal[int] ): literal[string] identifier[it] = identifier[iter] ( identifier[iterable] ) identifier[count] = identifier[start] keyword[try] : identifier[last] = identifier[next] ( identifier[it] ) keyword[except] identifier[StopIteration] : keyword[return] keyword[for] identifier[val] keyword[in] identifier[it] : keyword[yield] identifier[count] , keyword[False] , identifier[last] identifier[last] = identifier[val] identifier[count] += literal[int] keyword[yield] identifier[count] , keyword[True] , identifier[last]
def enum_mark_last(iterable, start=0): """ Returns a generator over iterable that tells whether the current item is the last one. Usage: >>> iterable = range(10) >>> for index, is_last, item in enum_mark_last(iterable): >>> print(index, item, end=' ' if is_last else ', ') """ it = iter(iterable) count = start try: last = next(it) # depends on [control=['try'], data=[]] except StopIteration: return # depends on [control=['except'], data=[]] for val in it: yield (count, False, last) last = val count += 1 # depends on [control=['for'], data=['val']] yield (count, True, last)
def BCS(self, params): """ BCS label Branch to the instruction at label if the C flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BCS label def BCS_func(): if self.is_C_set(): self.register['PC'] = self.labels[label] return BCS_func
def function[BCS, parameter[self, params]]: constant[ BCS label Branch to the instruction at label if the C flag is set ] variable[label] assign[=] call[name[self].get_one_parameter, parameter[name[self].ONE_PARAMETER, name[params]]] call[name[self].check_arguments, parameter[]] def function[BCS_func, parameter[]]: if call[name[self].is_C_set, parameter[]] begin[:] call[name[self].register][constant[PC]] assign[=] call[name[self].labels][name[label]] return[name[BCS_func]]
keyword[def] identifier[BCS] ( identifier[self] , identifier[params] ): literal[string] identifier[label] = identifier[self] . identifier[get_one_parameter] ( identifier[self] . identifier[ONE_PARAMETER] , identifier[params] ) identifier[self] . identifier[check_arguments] ( identifier[label_exists] =( identifier[label] ,)) keyword[def] identifier[BCS_func] (): keyword[if] identifier[self] . identifier[is_C_set] (): identifier[self] . identifier[register] [ literal[string] ]= identifier[self] . identifier[labels] [ identifier[label] ] keyword[return] identifier[BCS_func]
def BCS(self, params): """ BCS label Branch to the instruction at label if the C flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BCS label def BCS_func(): if self.is_C_set(): self.register['PC'] = self.labels[label] # depends on [control=['if'], data=[]] return BCS_func
def add_features_to_nglview(self, view, seqprop=None, structprop=None, chain_id=None, use_representatives=False): """Add select features from the selected SeqProp object to an NGLWidget view object. Currently parsing for: * Single residue features (ie. metal binding sites) * Disulfide bonds Args: view (NGLWidget): NGLWidget view object seqprop (SeqProp): SeqProp object structprop (StructProp): StructProp object chain_id (str): ID of the structure's chain to get annotation from use_representatives (bool): If the representative sequence/structure/chain IDs should be used """ if use_representatives: if seqprop and structprop and chain_id: raise ValueError('Overriding sequence, structure, and chain IDs with representatives. ' 'Set use_representatives to False if custom IDs are to be used.') else: if not seqprop or not structprop or not chain_id: raise ValueError('Input sequence, structure, and chain to map between, or set use_representatives ' 'to True.') if use_representatives: seqprop = self.representative_sequence structprop = self.representative_structure chain_id = self.representative_chain # Parse and store chain seq if not already stored if not structprop.chains.has_id(chain_id): structprop.parse_structure() if not structprop.chains.has_id(chain_id): raise ValueError('Chain {} not present in structure {}'.format(chain_id, structprop.id)) if not seqprop.features: log.warning('{}: no stored features'.format(seqprop.id)) # Loop through any stored features for f in seqprop.features: # Display disulfide bonds if f.type.lower() == 'disulfide bond': # TODO: double check if .start or .start + 1 disulfide = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) to_view = [str(x)+'.CA' for x in list(disulfide.values())] view.add_distance(atom_pair=[to_view], color='black') log.info('Disulfide bridge at residues {} & {}'.format(f.location.start + 1, f.location.end)) # Display DNA-binding regions if f.type.lower() == 'dna-binding region' or f.type.lower() == 'nucleotide phosphate-binding region': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_ball_and_stick(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), color='black') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end)) # Display other single residues if f.location.end - 1 == f.location.start: if f.type.lower() == 'sequence variant' or f.type.lower() == 'mutagenesis site': continue impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=f.location.end, seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) if f.location.end in impres: impres_mapped = impres[f.location.end] view.add_ball_and_stick(selection=str(impres_mapped), color='black') view.add_label(selection=':{} and {}'.format(chain_id, impres_mapped), label_type='res', color='black') log.info('{} at sequence residue {}, structure residue {}'.format(f.type, f.location.end, impres_mapped)) # Display transmembrane regions if f.type.lower() == 'transmembrane region': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_cartoon(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), aspectRatio=9, color='black') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end)) # Display topological domains if f.type.lower() == 'topological domain': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_cartoon(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), aspectRatio=9, color='green') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end))
def function[add_features_to_nglview, parameter[self, view, seqprop, structprop, chain_id, use_representatives]]: constant[Add select features from the selected SeqProp object to an NGLWidget view object. Currently parsing for: * Single residue features (ie. metal binding sites) * Disulfide bonds Args: view (NGLWidget): NGLWidget view object seqprop (SeqProp): SeqProp object structprop (StructProp): StructProp object chain_id (str): ID of the structure's chain to get annotation from use_representatives (bool): If the representative sequence/structure/chain IDs should be used ] if name[use_representatives] begin[:] if <ast.BoolOp object at 0x7da1b0cb43a0> begin[:] <ast.Raise object at 0x7da1b0cb7a30> if name[use_representatives] begin[:] variable[seqprop] assign[=] name[self].representative_sequence variable[structprop] assign[=] name[self].representative_structure variable[chain_id] assign[=] name[self].representative_chain if <ast.UnaryOp object at 0x7da1b0cb73d0> begin[:] call[name[structprop].parse_structure, parameter[]] if <ast.UnaryOp object at 0x7da1b0cb5900> begin[:] <ast.Raise object at 0x7da1b0cb4340> if <ast.UnaryOp object at 0x7da1b0cb6200> begin[:] call[name[log].warning, parameter[call[constant[{}: no stored features].format, parameter[name[seqprop].id]]]] for taget[name[f]] in starred[name[seqprop].features] begin[:] if compare[call[name[f].type.lower, parameter[]] equal[==] constant[disulfide bond]] begin[:] variable[disulfide] assign[=] call[name[self].map_seqprop_resnums_to_structprop_resnums, parameter[]] variable[to_view] assign[=] <ast.ListComp object at 0x7da1b0cb5b40> call[name[view].add_distance, parameter[]] call[name[log].info, parameter[call[constant[Disulfide bridge at residues {} & {}].format, parameter[binary_operation[name[f].location.start + constant[1]], name[f].location.end]]]] if <ast.BoolOp object at 0x7da1b0cb6560> begin[:] variable[impres] assign[=] call[name[self].map_seqprop_resnums_to_structprop_resnums, parameter[]] if <ast.BoolOp object at 0x7da1b0efbd90> begin[:] variable[mapped_start] assign[=] call[name[impres]][binary_operation[name[f].location.start + constant[1]]] variable[mapped_end] assign[=] call[name[impres]][name[f].location.end] call[name[view].add_ball_and_stick, parameter[]] call[name[log].info, parameter[call[constant[{} at sequence region {}-{}, structure residues {}-{}].format, parameter[name[f].type, name[f].location.start, name[f].location.end, name[mapped_start], name[mapped_end]]]]] if compare[binary_operation[name[f].location.end - constant[1]] equal[==] name[f].location.start] begin[:] if <ast.BoolOp object at 0x7da1b0efafe0> begin[:] continue variable[impres] assign[=] call[name[self].map_seqprop_resnums_to_structprop_resnums, parameter[]] if compare[name[f].location.end in name[impres]] begin[:] variable[impres_mapped] assign[=] call[name[impres]][name[f].location.end] call[name[view].add_ball_and_stick, parameter[]] call[name[view].add_label, parameter[]] call[name[log].info, parameter[call[constant[{} at sequence residue {}, structure residue {}].format, parameter[name[f].type, name[f].location.end, name[impres_mapped]]]]] if compare[call[name[f].type.lower, parameter[]] equal[==] constant[transmembrane region]] begin[:] variable[impres] assign[=] call[name[self].map_seqprop_resnums_to_structprop_resnums, parameter[]] if <ast.BoolOp object at 0x7da1b0ef99c0> begin[:] variable[mapped_start] assign[=] call[name[impres]][binary_operation[name[f].location.start + constant[1]]] variable[mapped_end] assign[=] call[name[impres]][name[f].location.end] call[name[view].add_cartoon, parameter[]] call[name[log].info, parameter[call[constant[{} at sequence region {}-{}, structure residues {}-{}].format, parameter[name[f].type, name[f].location.start, name[f].location.end, name[mapped_start], name[mapped_end]]]]] if compare[call[name[f].type.lower, parameter[]] equal[==] constant[topological domain]] begin[:] variable[impres] assign[=] call[name[self].map_seqprop_resnums_to_structprop_resnums, parameter[]] if <ast.BoolOp object at 0x7da1b0ef87c0> begin[:] variable[mapped_start] assign[=] call[name[impres]][binary_operation[name[f].location.start + constant[1]]] variable[mapped_end] assign[=] call[name[impres]][name[f].location.end] call[name[view].add_cartoon, parameter[]] call[name[log].info, parameter[call[constant[{} at sequence region {}-{}, structure residues {}-{}].format, parameter[name[f].type, name[f].location.start, name[f].location.end, name[mapped_start], name[mapped_end]]]]]
keyword[def] identifier[add_features_to_nglview] ( identifier[self] , identifier[view] , identifier[seqprop] = keyword[None] , identifier[structprop] = keyword[None] , identifier[chain_id] = keyword[None] , identifier[use_representatives] = keyword[False] ): literal[string] keyword[if] identifier[use_representatives] : keyword[if] identifier[seqprop] keyword[and] identifier[structprop] keyword[and] identifier[chain_id] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[else] : keyword[if] keyword[not] identifier[seqprop] keyword[or] keyword[not] identifier[structprop] keyword[or] keyword[not] identifier[chain_id] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[if] identifier[use_representatives] : identifier[seqprop] = identifier[self] . identifier[representative_sequence] identifier[structprop] = identifier[self] . identifier[representative_structure] identifier[chain_id] = identifier[self] . identifier[representative_chain] keyword[if] keyword[not] identifier[structprop] . identifier[chains] . identifier[has_id] ( identifier[chain_id] ): identifier[structprop] . identifier[parse_structure] () keyword[if] keyword[not] identifier[structprop] . identifier[chains] . identifier[has_id] ( identifier[chain_id] ): keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[chain_id] , identifier[structprop] . identifier[id] )) keyword[if] keyword[not] identifier[seqprop] . identifier[features] : identifier[log] . identifier[warning] ( literal[string] . identifier[format] ( identifier[seqprop] . identifier[id] )) keyword[for] identifier[f] keyword[in] identifier[seqprop] . identifier[features] : keyword[if] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] : identifier[disulfide] = identifier[self] . identifier[map_seqprop_resnums_to_structprop_resnums] ( identifier[resnums] =[ identifier[f] . identifier[location] . identifier[start] + literal[int] , identifier[f] . identifier[location] . identifier[end] ], identifier[seqprop] = identifier[seqprop] , identifier[structprop] = identifier[structprop] , identifier[chain_id] = identifier[chain_id] , identifier[use_representatives] = identifier[use_representatives] ) identifier[to_view] =[ identifier[str] ( identifier[x] )+ literal[string] keyword[for] identifier[x] keyword[in] identifier[list] ( identifier[disulfide] . identifier[values] ())] identifier[view] . identifier[add_distance] ( identifier[atom_pair] =[ identifier[to_view] ], identifier[color] = literal[string] ) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[f] . identifier[location] . identifier[start] + literal[int] , identifier[f] . identifier[location] . identifier[end] )) keyword[if] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] keyword[or] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] : identifier[impres] = identifier[self] . identifier[map_seqprop_resnums_to_structprop_resnums] ( identifier[resnums] =[ identifier[f] . identifier[location] . identifier[start] + literal[int] , identifier[f] . identifier[location] . identifier[end] ], identifier[seqprop] = identifier[seqprop] , identifier[structprop] = identifier[structprop] , identifier[chain_id] = identifier[chain_id] , identifier[use_representatives] = identifier[use_representatives] ) keyword[if] identifier[f] . identifier[location] . identifier[start] + literal[int] keyword[in] identifier[impres] keyword[and] identifier[f] . identifier[location] . identifier[end] keyword[in] identifier[impres] : identifier[mapped_start] = identifier[impres] [ identifier[f] . identifier[location] . identifier[start] + literal[int] ] identifier[mapped_end] = identifier[impres] [ identifier[f] . identifier[location] . identifier[end] ] identifier[view] . identifier[add_ball_and_stick] ( identifier[selection] = literal[string] . identifier[format] ( identifier[chain_id] , identifier[mapped_start] , identifier[mapped_end] ), identifier[color] = literal[string] ) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[f] . identifier[type] , identifier[f] . identifier[location] . identifier[start] , identifier[f] . identifier[location] . identifier[end] , identifier[mapped_start] , identifier[mapped_end] )) keyword[if] identifier[f] . identifier[location] . identifier[end] - literal[int] == identifier[f] . identifier[location] . identifier[start] : keyword[if] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] keyword[or] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] : keyword[continue] identifier[impres] = identifier[self] . identifier[map_seqprop_resnums_to_structprop_resnums] ( identifier[resnums] = identifier[f] . identifier[location] . identifier[end] , identifier[seqprop] = identifier[seqprop] , identifier[structprop] = identifier[structprop] , identifier[chain_id] = identifier[chain_id] , identifier[use_representatives] = identifier[use_representatives] ) keyword[if] identifier[f] . identifier[location] . identifier[end] keyword[in] identifier[impres] : identifier[impres_mapped] = identifier[impres] [ identifier[f] . identifier[location] . identifier[end] ] identifier[view] . identifier[add_ball_and_stick] ( identifier[selection] = identifier[str] ( identifier[impres_mapped] ), identifier[color] = literal[string] ) identifier[view] . identifier[add_label] ( identifier[selection] = literal[string] . identifier[format] ( identifier[chain_id] , identifier[impres_mapped] ), identifier[label_type] = literal[string] , identifier[color] = literal[string] ) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[f] . identifier[type] , identifier[f] . identifier[location] . identifier[end] , identifier[impres_mapped] )) keyword[if] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] : identifier[impres] = identifier[self] . identifier[map_seqprop_resnums_to_structprop_resnums] ( identifier[resnums] =[ identifier[f] . identifier[location] . identifier[start] + literal[int] , identifier[f] . identifier[location] . identifier[end] ], identifier[seqprop] = identifier[seqprop] , identifier[structprop] = identifier[structprop] , identifier[chain_id] = identifier[chain_id] , identifier[use_representatives] = identifier[use_representatives] ) keyword[if] identifier[f] . identifier[location] . identifier[start] + literal[int] keyword[in] identifier[impres] keyword[and] identifier[f] . identifier[location] . identifier[end] keyword[in] identifier[impres] : identifier[mapped_start] = identifier[impres] [ identifier[f] . identifier[location] . identifier[start] + literal[int] ] identifier[mapped_end] = identifier[impres] [ identifier[f] . identifier[location] . identifier[end] ] identifier[view] . identifier[add_cartoon] ( identifier[selection] = literal[string] . identifier[format] ( identifier[chain_id] , identifier[mapped_start] , identifier[mapped_end] ), identifier[aspectRatio] = literal[int] , identifier[color] = literal[string] ) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[f] . identifier[type] , identifier[f] . identifier[location] . identifier[start] , identifier[f] . identifier[location] . identifier[end] , identifier[mapped_start] , identifier[mapped_end] )) keyword[if] identifier[f] . identifier[type] . identifier[lower] ()== literal[string] : identifier[impres] = identifier[self] . identifier[map_seqprop_resnums_to_structprop_resnums] ( identifier[resnums] =[ identifier[f] . identifier[location] . identifier[start] + literal[int] , identifier[f] . identifier[location] . identifier[end] ], identifier[seqprop] = identifier[seqprop] , identifier[structprop] = identifier[structprop] , identifier[chain_id] = identifier[chain_id] , identifier[use_representatives] = identifier[use_representatives] ) keyword[if] identifier[f] . identifier[location] . identifier[start] + literal[int] keyword[in] identifier[impres] keyword[and] identifier[f] . identifier[location] . identifier[end] keyword[in] identifier[impres] : identifier[mapped_start] = identifier[impres] [ identifier[f] . identifier[location] . identifier[start] + literal[int] ] identifier[mapped_end] = identifier[impres] [ identifier[f] . identifier[location] . identifier[end] ] identifier[view] . identifier[add_cartoon] ( identifier[selection] = literal[string] . identifier[format] ( identifier[chain_id] , identifier[mapped_start] , identifier[mapped_end] ), identifier[aspectRatio] = literal[int] , identifier[color] = literal[string] ) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[f] . identifier[type] , identifier[f] . identifier[location] . identifier[start] , identifier[f] . identifier[location] . identifier[end] , identifier[mapped_start] , identifier[mapped_end] ))
def add_features_to_nglview(self, view, seqprop=None, structprop=None, chain_id=None, use_representatives=False): """Add select features from the selected SeqProp object to an NGLWidget view object. Currently parsing for: * Single residue features (ie. metal binding sites) * Disulfide bonds Args: view (NGLWidget): NGLWidget view object seqprop (SeqProp): SeqProp object structprop (StructProp): StructProp object chain_id (str): ID of the structure's chain to get annotation from use_representatives (bool): If the representative sequence/structure/chain IDs should be used """ if use_representatives: if seqprop and structprop and chain_id: raise ValueError('Overriding sequence, structure, and chain IDs with representatives. Set use_representatives to False if custom IDs are to be used.') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif not seqprop or not structprop or (not chain_id): raise ValueError('Input sequence, structure, and chain to map between, or set use_representatives to True.') # depends on [control=['if'], data=[]] if use_representatives: seqprop = self.representative_sequence structprop = self.representative_structure chain_id = self.representative_chain # depends on [control=['if'], data=[]] # Parse and store chain seq if not already stored if not structprop.chains.has_id(chain_id): structprop.parse_structure() if not structprop.chains.has_id(chain_id): raise ValueError('Chain {} not present in structure {}'.format(chain_id, structprop.id)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if not seqprop.features: log.warning('{}: no stored features'.format(seqprop.id)) # depends on [control=['if'], data=[]] # Loop through any stored features for f in seqprop.features: # Display disulfide bonds if f.type.lower() == 'disulfide bond': # TODO: double check if .start or .start + 1 disulfide = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) to_view = [str(x) + '.CA' for x in list(disulfide.values())] view.add_distance(atom_pair=[to_view], color='black') log.info('Disulfide bridge at residues {} & {}'.format(f.location.start + 1, f.location.end)) # depends on [control=['if'], data=[]] # Display DNA-binding regions if f.type.lower() == 'dna-binding region' or f.type.lower() == 'nucleotide phosphate-binding region': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_ball_and_stick(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), color='black') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Display other single residues if f.location.end - 1 == f.location.start: if f.type.lower() == 'sequence variant' or f.type.lower() == 'mutagenesis site': continue # depends on [control=['if'], data=[]] impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=f.location.end, seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) if f.location.end in impres: impres_mapped = impres[f.location.end] view.add_ball_and_stick(selection=str(impres_mapped), color='black') view.add_label(selection=':{} and {}'.format(chain_id, impres_mapped), label_type='res', color='black') log.info('{} at sequence residue {}, structure residue {}'.format(f.type, f.location.end, impres_mapped)) # depends on [control=['if'], data=['impres']] # depends on [control=['if'], data=[]] # Display transmembrane regions if f.type.lower() == 'transmembrane region': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_cartoon(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), aspectRatio=9, color='black') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Display topological domains if f.type.lower() == 'topological domain': impres = self.map_seqprop_resnums_to_structprop_resnums(resnums=[f.location.start + 1, f.location.end], seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives) # TODO: need to check if f.location.start was mapped and if not, try incrementing. or input the list # of resnums, not just the start and end if f.location.start + 1 in impres and f.location.end in impres: mapped_start = impres[f.location.start + 1] mapped_end = impres[f.location.end] view.add_cartoon(selection=':{} and ( {}-{} )'.format(chain_id, mapped_start, mapped_end), aspectRatio=9, color='green') log.info('{} at sequence region {}-{}, structure residues {}-{}'.format(f.type, f.location.start, f.location.end, mapped_start, mapped_end)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']]
def _project(reference_sources, C): """Project images using pre-computed filters C reference_sources are nsrc X nsampl X nchan C is nsrc X nchan X filters_len X nchan """ # shapes: ensure that input is 3d (comprising the source index) if len(reference_sources.shape) == 2: reference_sources = reference_sources[None, ...] C = C[None, ...] (nsrc, nsampl, nchan) = reference_sources.shape filters_len = C.shape[-2] # zero pad reference_sources = _zeropad(reference_sources, filters_len - 1, axis=1) sproj = np.zeros((nchan, nsampl + filters_len - 1)) for (j, cj, c) in itertools.product( list(range(nsrc)), list(range(nchan)), list(range(nchan)) ): sproj[c] += fftconvolve( C[j, cj, :, c], reference_sources[j, :, cj] )[:nsampl + filters_len - 1] return sproj.T
def function[_project, parameter[reference_sources, C]]: constant[Project images using pre-computed filters C reference_sources are nsrc X nsampl X nchan C is nsrc X nchan X filters_len X nchan ] if compare[call[name[len], parameter[name[reference_sources].shape]] equal[==] constant[2]] begin[:] variable[reference_sources] assign[=] call[name[reference_sources]][tuple[[<ast.Constant object at 0x7da1b0301690>, <ast.Constant object at 0x7da1b0302560>]]] variable[C] assign[=] call[name[C]][tuple[[<ast.Constant object at 0x7da1b0300d30>, <ast.Constant object at 0x7da1b0300940>]]] <ast.Tuple object at 0x7da1b0303d60> assign[=] name[reference_sources].shape variable[filters_len] assign[=] call[name[C].shape][<ast.UnaryOp object at 0x7da1b03005e0>] variable[reference_sources] assign[=] call[name[_zeropad], parameter[name[reference_sources], binary_operation[name[filters_len] - constant[1]]]] variable[sproj] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Name object at 0x7da1b0302140>, <ast.BinOp object at 0x7da1b0300ca0>]]]] for taget[tuple[[<ast.Name object at 0x7da1b0302cb0>, <ast.Name object at 0x7da1b0303b50>, <ast.Name object at 0x7da1b0302ec0>]]] in starred[call[name[itertools].product, parameter[call[name[list], parameter[call[name[range], parameter[name[nsrc]]]]], call[name[list], parameter[call[name[range], parameter[name[nchan]]]]], call[name[list], parameter[call[name[range], parameter[name[nchan]]]]]]]] begin[:] <ast.AugAssign object at 0x7da1b0302da0> return[name[sproj].T]
keyword[def] identifier[_project] ( identifier[reference_sources] , identifier[C] ): literal[string] keyword[if] identifier[len] ( identifier[reference_sources] . identifier[shape] )== literal[int] : identifier[reference_sources] = identifier[reference_sources] [ keyword[None] ,...] identifier[C] = identifier[C] [ keyword[None] ,...] ( identifier[nsrc] , identifier[nsampl] , identifier[nchan] )= identifier[reference_sources] . identifier[shape] identifier[filters_len] = identifier[C] . identifier[shape] [- literal[int] ] identifier[reference_sources] = identifier[_zeropad] ( identifier[reference_sources] , identifier[filters_len] - literal[int] , identifier[axis] = literal[int] ) identifier[sproj] = identifier[np] . identifier[zeros] (( identifier[nchan] , identifier[nsampl] + identifier[filters_len] - literal[int] )) keyword[for] ( identifier[j] , identifier[cj] , identifier[c] ) keyword[in] identifier[itertools] . identifier[product] ( identifier[list] ( identifier[range] ( identifier[nsrc] )), identifier[list] ( identifier[range] ( identifier[nchan] )), identifier[list] ( identifier[range] ( identifier[nchan] )) ): identifier[sproj] [ identifier[c] ]+= identifier[fftconvolve] ( identifier[C] [ identifier[j] , identifier[cj] ,:, identifier[c] ], identifier[reference_sources] [ identifier[j] ,:, identifier[cj] ] )[: identifier[nsampl] + identifier[filters_len] - literal[int] ] keyword[return] identifier[sproj] . identifier[T]
def _project(reference_sources, C): """Project images using pre-computed filters C reference_sources are nsrc X nsampl X nchan C is nsrc X nchan X filters_len X nchan """ # shapes: ensure that input is 3d (comprising the source index) if len(reference_sources.shape) == 2: reference_sources = reference_sources[None, ...] C = C[None, ...] # depends on [control=['if'], data=[]] (nsrc, nsampl, nchan) = reference_sources.shape filters_len = C.shape[-2] # zero pad reference_sources = _zeropad(reference_sources, filters_len - 1, axis=1) sproj = np.zeros((nchan, nsampl + filters_len - 1)) for (j, cj, c) in itertools.product(list(range(nsrc)), list(range(nchan)), list(range(nchan))): sproj[c] += fftconvolve(C[j, cj, :, c], reference_sources[j, :, cj])[:nsampl + filters_len - 1] # depends on [control=['for'], data=[]] return sproj.T
def attach_file(self, filename, page_id=None, title=None, space=None, comment=None): """ Attach (upload) a file to a page, if it exists it will update the automatically version the new file and keep the old one. :param title: The page name :type title: ``str`` :param space: The space name :type space: ``str`` :param page_id: The page id to which we would like to upload the file :type page_id: ``str`` :param filename: The file to upload :type filename: ``str`` :param comment: A comment describing this upload/file :type comment: ``str`` """ page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id type = 'attachment' if page_id is not None: extension = os.path.splitext(filename)[-1] content_type = self.content_types.get(extension, "application/binary") comment = comment if comment else "Uploaded {filename}.".format(filename=filename) data = { 'type': type, "fileName": filename, "contentType": content_type, "comment": comment, "minorEdit": "true"} headers = { 'X-Atlassian-Token': 'nocheck', 'Accept': 'application/json'} path = 'rest/api/content/{page_id}/child/attachment'.format(page_id=page_id) # get base name of the file to get the attachment from confluence. file_base_name = os.path.basename(filename) # Check if there is already a file with the same name attachments = self.get(path=path, headers=headers, params={'filename': file_base_name}) if attachments['size']: path = path + '/' + attachments['results'][0]['id'] + '/data' with open(filename, 'rb') as infile: return self.post(path=path, data=data, headers=headers, files={'file': (filename, infile, content_type)}) else: log.warning("No 'page_id' found, not uploading attachments") return None
def function[attach_file, parameter[self, filename, page_id, title, space, comment]]: constant[ Attach (upload) a file to a page, if it exists it will update the automatically version the new file and keep the old one. :param title: The page name :type title: ``str`` :param space: The space name :type space: ``str`` :param page_id: The page id to which we would like to upload the file :type page_id: ``str`` :param filename: The file to upload :type filename: ``str`` :param comment: A comment describing this upload/file :type comment: ``str`` ] variable[page_id] assign[=] <ast.IfExp object at 0x7da20c6a9ab0> variable[type] assign[=] constant[attachment] if compare[name[page_id] is_not constant[None]] begin[:] variable[extension] assign[=] call[call[name[os].path.splitext, parameter[name[filename]]]][<ast.UnaryOp object at 0x7da20c6a81f0>] variable[content_type] assign[=] call[name[self].content_types.get, parameter[name[extension], constant[application/binary]]] variable[comment] assign[=] <ast.IfExp object at 0x7da20c6a8b50> variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20c6abc40>, <ast.Constant object at 0x7da20c6a90c0>, <ast.Constant object at 0x7da20c6a9ff0>, <ast.Constant object at 0x7da20c6aa140>, <ast.Constant object at 0x7da20c6aa5f0>], [<ast.Name object at 0x7da20c6a96c0>, <ast.Name object at 0x7da20c6aa560>, <ast.Name object at 0x7da20c6ab160>, <ast.Name object at 0x7da20c6a8ac0>, <ast.Constant object at 0x7da20c6a9450>]] variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da20c6ab1c0>, <ast.Constant object at 0x7da20c6aba90>], [<ast.Constant object at 0x7da20c6aabf0>, <ast.Constant object at 0x7da20c6abb50>]] variable[path] assign[=] call[constant[rest/api/content/{page_id}/child/attachment].format, parameter[]] variable[file_base_name] assign[=] call[name[os].path.basename, parameter[name[filename]]] variable[attachments] assign[=] call[name[self].get, parameter[]] if call[name[attachments]][constant[size]] begin[:] variable[path] assign[=] binary_operation[binary_operation[binary_operation[name[path] + constant[/]] + call[call[call[name[attachments]][constant[results]]][constant[0]]][constant[id]]] + constant[/data]] with call[name[open], parameter[name[filename], constant[rb]]] begin[:] return[call[name[self].post, parameter[]]]
keyword[def] identifier[attach_file] ( identifier[self] , identifier[filename] , identifier[page_id] = keyword[None] , identifier[title] = keyword[None] , identifier[space] = keyword[None] , identifier[comment] = keyword[None] ): literal[string] identifier[page_id] = identifier[self] . identifier[get_page_id] ( identifier[space] = identifier[space] , identifier[title] = identifier[title] ) keyword[if] identifier[page_id] keyword[is] keyword[None] keyword[else] identifier[page_id] identifier[type] = literal[string] keyword[if] identifier[page_id] keyword[is] keyword[not] keyword[None] : identifier[extension] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[filename] )[- literal[int] ] identifier[content_type] = identifier[self] . identifier[content_types] . identifier[get] ( identifier[extension] , literal[string] ) identifier[comment] = identifier[comment] keyword[if] identifier[comment] keyword[else] literal[string] . identifier[format] ( identifier[filename] = identifier[filename] ) identifier[data] ={ literal[string] : identifier[type] , literal[string] : identifier[filename] , literal[string] : identifier[content_type] , literal[string] : identifier[comment] , literal[string] : literal[string] } identifier[headers] ={ literal[string] : literal[string] , literal[string] : literal[string] } identifier[path] = literal[string] . identifier[format] ( identifier[page_id] = identifier[page_id] ) identifier[file_base_name] = identifier[os] . identifier[path] . identifier[basename] ( identifier[filename] ) identifier[attachments] = identifier[self] . identifier[get] ( identifier[path] = identifier[path] , identifier[headers] = identifier[headers] , identifier[params] ={ literal[string] : identifier[file_base_name] }) keyword[if] identifier[attachments] [ literal[string] ]: identifier[path] = identifier[path] + literal[string] + identifier[attachments] [ literal[string] ][ literal[int] ][ literal[string] ]+ literal[string] keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[infile] : keyword[return] identifier[self] . identifier[post] ( identifier[path] = identifier[path] , identifier[data] = identifier[data] , identifier[headers] = identifier[headers] , identifier[files] ={ literal[string] :( identifier[filename] , identifier[infile] , identifier[content_type] )}) keyword[else] : identifier[log] . identifier[warning] ( literal[string] ) keyword[return] keyword[None]
def attach_file(self, filename, page_id=None, title=None, space=None, comment=None): """ Attach (upload) a file to a page, if it exists it will update the automatically version the new file and keep the old one. :param title: The page name :type title: ``str`` :param space: The space name :type space: ``str`` :param page_id: The page id to which we would like to upload the file :type page_id: ``str`` :param filename: The file to upload :type filename: ``str`` :param comment: A comment describing this upload/file :type comment: ``str`` """ page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id type = 'attachment' if page_id is not None: extension = os.path.splitext(filename)[-1] content_type = self.content_types.get(extension, 'application/binary') comment = comment if comment else 'Uploaded {filename}.'.format(filename=filename) data = {'type': type, 'fileName': filename, 'contentType': content_type, 'comment': comment, 'minorEdit': 'true'} headers = {'X-Atlassian-Token': 'nocheck', 'Accept': 'application/json'} path = 'rest/api/content/{page_id}/child/attachment'.format(page_id=page_id) # get base name of the file to get the attachment from confluence. file_base_name = os.path.basename(filename) # Check if there is already a file with the same name attachments = self.get(path=path, headers=headers, params={'filename': file_base_name}) if attachments['size']: path = path + '/' + attachments['results'][0]['id'] + '/data' # depends on [control=['if'], data=[]] with open(filename, 'rb') as infile: return self.post(path=path, data=data, headers=headers, files={'file': (filename, infile, content_type)}) # depends on [control=['with'], data=['infile']] # depends on [control=['if'], data=['page_id']] else: log.warning("No 'page_id' found, not uploading attachments") return None
def arg_bool(name, default=False): """ Fetch a query argument, as a boolean. """ v = request.args.get(name, '') if not len(v): return default return v in BOOL_TRUISH
def function[arg_bool, parameter[name, default]]: constant[ Fetch a query argument, as a boolean. ] variable[v] assign[=] call[name[request].args.get, parameter[name[name], constant[]]] if <ast.UnaryOp object at 0x7da1b0a48580> begin[:] return[name[default]] return[compare[name[v] in name[BOOL_TRUISH]]]
keyword[def] identifier[arg_bool] ( identifier[name] , identifier[default] = keyword[False] ): literal[string] identifier[v] = identifier[request] . identifier[args] . identifier[get] ( identifier[name] , literal[string] ) keyword[if] keyword[not] identifier[len] ( identifier[v] ): keyword[return] identifier[default] keyword[return] identifier[v] keyword[in] identifier[BOOL_TRUISH]
def arg_bool(name, default=False): """ Fetch a query argument, as a boolean. """ v = request.args.get(name, '') if not len(v): return default # depends on [control=['if'], data=[]] return v in BOOL_TRUISH
def send_id(self, tok, force_auth): ''' Send the minion id to the master so that the master may better track the connection state of the minion. In case of authentication errors, try to renegotiate authentication and retry the method. ''' load = {'id': self.opts['id'], 'tok': tok} @tornado.gen.coroutine def _do_transfer(): msg = self._package_load(self.auth.crypticle.dumps(load)) package = salt.transport.frame.frame_msg(msg, header=None) yield self.message_client.write_to_stream(package) raise tornado.gen.Return(True) if force_auth or not self.auth.authenticated: count = 0 while count <= self.opts['tcp_authentication_retries'] or self.opts['tcp_authentication_retries'] < 0: try: yield self.auth.authenticate() break except SaltClientError as exc: log.debug(exc) count += 1 try: ret = yield _do_transfer() raise tornado.gen.Return(ret) except salt.crypt.AuthenticationError: yield self.auth.authenticate() ret = yield _do_transfer() raise tornado.gen.Return(ret)
def function[send_id, parameter[self, tok, force_auth]]: constant[ Send the minion id to the master so that the master may better track the connection state of the minion. In case of authentication errors, try to renegotiate authentication and retry the method. ] variable[load] assign[=] dictionary[[<ast.Constant object at 0x7da1b1f601f0>, <ast.Constant object at 0x7da1b1f60220>], [<ast.Subscript object at 0x7da1b1fe7400>, <ast.Name object at 0x7da1b1fe6f80>]] def function[_do_transfer, parameter[]]: variable[msg] assign[=] call[name[self]._package_load, parameter[call[name[self].auth.crypticle.dumps, parameter[name[load]]]]] variable[package] assign[=] call[name[salt].transport.frame.frame_msg, parameter[name[msg]]] <ast.Yield object at 0x7da1b1f483a0> <ast.Raise object at 0x7da1b1fd6650> if <ast.BoolOp object at 0x7da1b2185750> begin[:] variable[count] assign[=] constant[0] while <ast.BoolOp object at 0x7da1b2186cb0> begin[:] <ast.Try object at 0x7da1b1f2e620> <ast.Try object at 0x7da1b1f2e200>
keyword[def] identifier[send_id] ( identifier[self] , identifier[tok] , identifier[force_auth] ): literal[string] identifier[load] ={ literal[string] : identifier[self] . identifier[opts] [ literal[string] ], literal[string] : identifier[tok] } @ identifier[tornado] . identifier[gen] . identifier[coroutine] keyword[def] identifier[_do_transfer] (): identifier[msg] = identifier[self] . identifier[_package_load] ( identifier[self] . identifier[auth] . identifier[crypticle] . identifier[dumps] ( identifier[load] )) identifier[package] = identifier[salt] . identifier[transport] . identifier[frame] . identifier[frame_msg] ( identifier[msg] , identifier[header] = keyword[None] ) keyword[yield] identifier[self] . identifier[message_client] . identifier[write_to_stream] ( identifier[package] ) keyword[raise] identifier[tornado] . identifier[gen] . identifier[Return] ( keyword[True] ) keyword[if] identifier[force_auth] keyword[or] keyword[not] identifier[self] . identifier[auth] . identifier[authenticated] : identifier[count] = literal[int] keyword[while] identifier[count] <= identifier[self] . identifier[opts] [ literal[string] ] keyword[or] identifier[self] . identifier[opts] [ literal[string] ]< literal[int] : keyword[try] : keyword[yield] identifier[self] . identifier[auth] . identifier[authenticate] () keyword[break] keyword[except] identifier[SaltClientError] keyword[as] identifier[exc] : identifier[log] . identifier[debug] ( identifier[exc] ) identifier[count] += literal[int] keyword[try] : identifier[ret] = keyword[yield] identifier[_do_transfer] () keyword[raise] identifier[tornado] . identifier[gen] . identifier[Return] ( identifier[ret] ) keyword[except] identifier[salt] . identifier[crypt] . identifier[AuthenticationError] : keyword[yield] identifier[self] . identifier[auth] . identifier[authenticate] () identifier[ret] = keyword[yield] identifier[_do_transfer] () keyword[raise] identifier[tornado] . identifier[gen] . identifier[Return] ( identifier[ret] )
def send_id(self, tok, force_auth): """ Send the minion id to the master so that the master may better track the connection state of the minion. In case of authentication errors, try to renegotiate authentication and retry the method. """ load = {'id': self.opts['id'], 'tok': tok} @tornado.gen.coroutine def _do_transfer(): msg = self._package_load(self.auth.crypticle.dumps(load)) package = salt.transport.frame.frame_msg(msg, header=None) yield self.message_client.write_to_stream(package) raise tornado.gen.Return(True) if force_auth or not self.auth.authenticated: count = 0 while count <= self.opts['tcp_authentication_retries'] or self.opts['tcp_authentication_retries'] < 0: try: yield self.auth.authenticate() break # depends on [control=['try'], data=[]] except SaltClientError as exc: log.debug(exc) count += 1 # depends on [control=['except'], data=['exc']] # depends on [control=['while'], data=[]] # depends on [control=['if'], data=[]] try: ret = (yield _do_transfer()) raise tornado.gen.Return(ret) # depends on [control=['try'], data=[]] except salt.crypt.AuthenticationError: yield self.auth.authenticate() ret = (yield _do_transfer()) raise tornado.gen.Return(ret) # depends on [control=['except'], data=[]]
def print_mem(unit="MB"): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info("memory usage: %.2f(%s)" % (result, unit)) return result except ImportError: print_info("pip install psutil first.")
def function[print_mem, parameter[unit]]: constant[Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. ] <ast.Try object at 0x7da20c993bb0>
keyword[def] identifier[print_mem] ( identifier[unit] = literal[string] ): literal[string] keyword[try] : keyword[import] identifier[psutil] identifier[B] = identifier[float] ( identifier[psutil] . identifier[Process] ( identifier[os] . identifier[getpid] ()). identifier[memory_info] (). identifier[vms] ) identifier[KB] = identifier[B] / literal[int] identifier[MB] = identifier[KB] / literal[int] identifier[GB] = identifier[MB] / literal[int] identifier[result] = identifier[vars] ()[ identifier[unit] ] identifier[print_info] ( literal[string] %( identifier[result] , identifier[unit] )) keyword[return] identifier[result] keyword[except] identifier[ImportError] : identifier[print_info] ( literal[string] )
def print_mem(unit='MB'): """Show the proc-mem-cost with psutil, use this only for lazinesssss. :param unit: B, KB, MB, GB. """ try: import psutil B = float(psutil.Process(os.getpid()).memory_info().vms) KB = B / 1024 MB = KB / 1024 GB = MB / 1024 result = vars()[unit] print_info('memory usage: %.2f(%s)' % (result, unit)) return result # depends on [control=['try'], data=[]] except ImportError: print_info('pip install psutil first.') # depends on [control=['except'], data=[]]
def get_command_header(parser, usage_message="", usage=False): """ Return the command line header :param parser: :param usage_message: :param usage: :return: The command header """ loader = template.Loader(os.path.join( firenado.conf.ROOT, 'management', 'templates', 'help')) return loader.load("header.txt").generate( parser=parser, usage_message=usage_message, usage=usage, firenado_version=".".join(map(str, firenado.__version__))).decode( sys.stdout.encoding)
def function[get_command_header, parameter[parser, usage_message, usage]]: constant[ Return the command line header :param parser: :param usage_message: :param usage: :return: The command header ] variable[loader] assign[=] call[name[template].Loader, parameter[call[name[os].path.join, parameter[name[firenado].conf.ROOT, constant[management], constant[templates], constant[help]]]]] return[call[call[call[name[loader].load, parameter[constant[header.txt]]].generate, parameter[]].decode, parameter[name[sys].stdout.encoding]]]
keyword[def] identifier[get_command_header] ( identifier[parser] , identifier[usage_message] = literal[string] , identifier[usage] = keyword[False] ): literal[string] identifier[loader] = identifier[template] . identifier[Loader] ( identifier[os] . identifier[path] . identifier[join] ( identifier[firenado] . identifier[conf] . identifier[ROOT] , literal[string] , literal[string] , literal[string] )) keyword[return] identifier[loader] . identifier[load] ( literal[string] ). identifier[generate] ( identifier[parser] = identifier[parser] , identifier[usage_message] = identifier[usage_message] , identifier[usage] = identifier[usage] , identifier[firenado_version] = literal[string] . identifier[join] ( identifier[map] ( identifier[str] , identifier[firenado] . identifier[__version__] ))). identifier[decode] ( identifier[sys] . identifier[stdout] . identifier[encoding] )
def get_command_header(parser, usage_message='', usage=False): """ Return the command line header :param parser: :param usage_message: :param usage: :return: The command header """ loader = template.Loader(os.path.join(firenado.conf.ROOT, 'management', 'templates', 'help')) return loader.load('header.txt').generate(parser=parser, usage_message=usage_message, usage=usage, firenado_version='.'.join(map(str, firenado.__version__))).decode(sys.stdout.encoding)
def save_ldamodel_to_pickle(picklefile, model, vocab, doc_labels, dtm=None, **kwargs): """Save a LDA model as pickle file.""" pickle_data({'model': model, 'vocab': vocab, 'doc_labels': doc_labels, 'dtm': dtm}, picklefile)
def function[save_ldamodel_to_pickle, parameter[picklefile, model, vocab, doc_labels, dtm]]: constant[Save a LDA model as pickle file.] call[name[pickle_data], parameter[dictionary[[<ast.Constant object at 0x7da20c6ab400>, <ast.Constant object at 0x7da20c6a9030>, <ast.Constant object at 0x7da20c6a8c70>, <ast.Constant object at 0x7da20c6aab60>], [<ast.Name object at 0x7da20c6a9090>, <ast.Name object at 0x7da20c6aabc0>, <ast.Name object at 0x7da20c6a88e0>, <ast.Name object at 0x7da20c6abe50>]], name[picklefile]]]
keyword[def] identifier[save_ldamodel_to_pickle] ( identifier[picklefile] , identifier[model] , identifier[vocab] , identifier[doc_labels] , identifier[dtm] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[pickle_data] ({ literal[string] : identifier[model] , literal[string] : identifier[vocab] , literal[string] : identifier[doc_labels] , literal[string] : identifier[dtm] }, identifier[picklefile] )
def save_ldamodel_to_pickle(picklefile, model, vocab, doc_labels, dtm=None, **kwargs): """Save a LDA model as pickle file.""" pickle_data({'model': model, 'vocab': vocab, 'doc_labels': doc_labels, 'dtm': dtm}, picklefile)
def del_layer(self, layer_num): """ Delete mesh layer """ del self.layer_stack[layer_num] # Adjust current layer if needed if layer_num < self.current_layer(): self.set_current_layer(self.current_layer() - 1) return None
def function[del_layer, parameter[self, layer_num]]: constant[ Delete mesh layer ] <ast.Delete object at 0x7da18f721c30> if compare[name[layer_num] less[<] call[name[self].current_layer, parameter[]]] begin[:] call[name[self].set_current_layer, parameter[binary_operation[call[name[self].current_layer, parameter[]] - constant[1]]]] return[constant[None]]
keyword[def] identifier[del_layer] ( identifier[self] , identifier[layer_num] ): literal[string] keyword[del] identifier[self] . identifier[layer_stack] [ identifier[layer_num] ] keyword[if] identifier[layer_num] < identifier[self] . identifier[current_layer] (): identifier[self] . identifier[set_current_layer] ( identifier[self] . identifier[current_layer] ()- literal[int] ) keyword[return] keyword[None]
def del_layer(self, layer_num): """ Delete mesh layer """ del self.layer_stack[layer_num] # Adjust current layer if needed if layer_num < self.current_layer(): self.set_current_layer(self.current_layer() - 1) # depends on [control=['if'], data=[]] return None
def requires_open_handle(method): # pylint: disable=invalid-name """Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method: A class method on a subclass of UsbHandle Raises: HandleClosedError: If this handle has been closed. Returns: A wrapper around method that ensures the handle is open before calling through to the wrapped method. """ @functools.wraps(method) def wrapper_requiring_open_handle(self, *args, **kwargs): """The wrapper to be returned.""" if self.is_closed(): raise usb_exceptions.HandleClosedError() return method(self, *args, **kwargs) return wrapper_requiring_open_handle
def function[requires_open_handle, parameter[method]]: constant[Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method: A class method on a subclass of UsbHandle Raises: HandleClosedError: If this handle has been closed. Returns: A wrapper around method that ensures the handle is open before calling through to the wrapped method. ] def function[wrapper_requiring_open_handle, parameter[self]]: constant[The wrapper to be returned.] if call[name[self].is_closed, parameter[]] begin[:] <ast.Raise object at 0x7da1b18de260> return[call[name[method], parameter[name[self], <ast.Starred object at 0x7da1b18dc130>]]] return[name[wrapper_requiring_open_handle]]
keyword[def] identifier[requires_open_handle] ( identifier[method] ): literal[string] @ identifier[functools] . identifier[wraps] ( identifier[method] ) keyword[def] identifier[wrapper_requiring_open_handle] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[self] . identifier[is_closed] (): keyword[raise] identifier[usb_exceptions] . identifier[HandleClosedError] () keyword[return] identifier[method] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ) keyword[return] identifier[wrapper_requiring_open_handle]
def requires_open_handle(method): # pylint: disable=invalid-name 'Decorator to ensure a handle is open for certain methods.\n\n Subclasses should decorate their Read() and Write() with this rather than\n checking their own internal state, keeping all "is this handle open" logic\n in is_closed().\n\n Args:\n method: A class method on a subclass of UsbHandle\n\n Raises:\n HandleClosedError: If this handle has been closed.\n\n Returns:\n A wrapper around method that ensures the handle is open before calling through\n to the wrapped method.\n ' @functools.wraps(method) def wrapper_requiring_open_handle(self, *args, **kwargs): """The wrapper to be returned.""" if self.is_closed(): raise usb_exceptions.HandleClosedError() # depends on [control=['if'], data=[]] return method(self, *args, **kwargs) return wrapper_requiring_open_handle
def sendLocalVoiceClips( self, clip_paths, message=None, thread_id=None, thread_type=ThreadType.USER ): """ Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType :return: :ref:`Message ID <intro_message_ids>` of the sent files :raises: FBchatException if request failed """ clip_paths = require_list(clip_paths) with get_files_from_paths(clip_paths) as x: files = self._upload(x, voice_clip=True) return self._sendFiles( files=files, message=message, thread_id=thread_id, thread_type=thread_type )
def function[sendLocalVoiceClips, parameter[self, clip_paths, message, thread_id, thread_type]]: constant[ Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType :return: :ref:`Message ID <intro_message_ids>` of the sent files :raises: FBchatException if request failed ] variable[clip_paths] assign[=] call[name[require_list], parameter[name[clip_paths]]] with call[name[get_files_from_paths], parameter[name[clip_paths]]] begin[:] variable[files] assign[=] call[name[self]._upload, parameter[name[x]]] return[call[name[self]._sendFiles, parameter[]]]
keyword[def] identifier[sendLocalVoiceClips] ( identifier[self] , identifier[clip_paths] , identifier[message] = keyword[None] , identifier[thread_id] = keyword[None] , identifier[thread_type] = identifier[ThreadType] . identifier[USER] ): literal[string] identifier[clip_paths] = identifier[require_list] ( identifier[clip_paths] ) keyword[with] identifier[get_files_from_paths] ( identifier[clip_paths] ) keyword[as] identifier[x] : identifier[files] = identifier[self] . identifier[_upload] ( identifier[x] , identifier[voice_clip] = keyword[True] ) keyword[return] identifier[self] . identifier[_sendFiles] ( identifier[files] = identifier[files] , identifier[message] = identifier[message] , identifier[thread_id] = identifier[thread_id] , identifier[thread_type] = identifier[thread_type] )
def sendLocalVoiceClips(self, clip_paths, message=None, thread_id=None, thread_type=ThreadType.USER): """ Sends local voice clips to a thread :param clip_paths: Paths of clips to upload and send :param message: Additional message :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType :return: :ref:`Message ID <intro_message_ids>` of the sent files :raises: FBchatException if request failed """ clip_paths = require_list(clip_paths) with get_files_from_paths(clip_paths) as x: files = self._upload(x, voice_clip=True) # depends on [control=['with'], data=['x']] return self._sendFiles(files=files, message=message, thread_id=thread_id, thread_type=thread_type)
def _size_fmt(num): ''' Format bytes as human-readable file sizes ''' try: num = int(num) if num < 1024: return '{0} bytes'.format(num) num /= 1024.0 for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'): if num < 1024.0: return '{0:3.1f} {1}'.format(num, unit) num /= 1024.0 except Exception: log.error('Unable to format file size for \'%s\'', num) return 'unknown'
def function[_size_fmt, parameter[num]]: constant[ Format bytes as human-readable file sizes ] <ast.Try object at 0x7da1b2095870>
keyword[def] identifier[_size_fmt] ( identifier[num] ): literal[string] keyword[try] : identifier[num] = identifier[int] ( identifier[num] ) keyword[if] identifier[num] < literal[int] : keyword[return] literal[string] . identifier[format] ( identifier[num] ) identifier[num] /= literal[int] keyword[for] identifier[unit] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ): keyword[if] identifier[num] < literal[int] : keyword[return] literal[string] . identifier[format] ( identifier[num] , identifier[unit] ) identifier[num] /= literal[int] keyword[except] identifier[Exception] : identifier[log] . identifier[error] ( literal[string] , identifier[num] ) keyword[return] literal[string]
def _size_fmt(num): """ Format bytes as human-readable file sizes """ try: num = int(num) if num < 1024: return '{0} bytes'.format(num) # depends on [control=['if'], data=['num']] num /= 1024.0 for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'): if num < 1024.0: return '{0:3.1f} {1}'.format(num, unit) # depends on [control=['if'], data=['num']] num /= 1024.0 # depends on [control=['for'], data=['unit']] # depends on [control=['try'], data=[]] except Exception: log.error("Unable to format file size for '%s'", num) return 'unknown' # depends on [control=['except'], data=[]]
def ensure_dir_exists(cls, filepath): """Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. """ directory = os.path.dirname(filepath) if directory != '' and not os.path.exists(directory): try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
def function[ensure_dir_exists, parameter[cls, filepath]]: constant[Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. ] variable[directory] assign[=] call[name[os].path.dirname, parameter[name[filepath]]] if <ast.BoolOp object at 0x7da18f812050> begin[:] <ast.Try object at 0x7da1b1d8c250>
keyword[def] identifier[ensure_dir_exists] ( identifier[cls] , identifier[filepath] ): literal[string] identifier[directory] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[filepath] ) keyword[if] identifier[directory] != literal[string] keyword[and] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[directory] ): keyword[try] : identifier[os] . identifier[makedirs] ( identifier[directory] ) keyword[except] identifier[OSError] keyword[as] identifier[e] : keyword[if] identifier[e] . identifier[errno] != identifier[errno] . identifier[EEXIST] : keyword[raise]
def ensure_dir_exists(cls, filepath): """Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. """ directory = os.path.dirname(filepath) if directory != '' and (not os.path.exists(directory)): try: os.makedirs(directory) # depends on [control=['try'], data=[]] except OSError as e: if e.errno != errno.EEXIST: raise # depends on [control=['if'], data=[]] # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=[]]
def port_profile_vlan_profile_switchport_trunk_allowed_vlan_all(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name") name_key.text = kwargs.pop('name') vlan_profile = ET.SubElement(port_profile, "vlan-profile") switchport = ET.SubElement(vlan_profile, "switchport") trunk = ET.SubElement(switchport, "trunk") allowed = ET.SubElement(trunk, "allowed") vlan = ET.SubElement(allowed, "vlan") all = ET.SubElement(vlan, "all") callback = kwargs.pop('callback', self._callback) return callback(config)
def function[port_profile_vlan_profile_switchport_trunk_allowed_vlan_all, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[port_profile] assign[=] call[name[ET].SubElement, parameter[name[config], constant[port-profile]]] variable[name_key] assign[=] call[name[ET].SubElement, parameter[name[port_profile], constant[name]]] name[name_key].text assign[=] call[name[kwargs].pop, parameter[constant[name]]] variable[vlan_profile] assign[=] call[name[ET].SubElement, parameter[name[port_profile], constant[vlan-profile]]] variable[switchport] assign[=] call[name[ET].SubElement, parameter[name[vlan_profile], constant[switchport]]] variable[trunk] assign[=] call[name[ET].SubElement, parameter[name[switchport], constant[trunk]]] variable[allowed] assign[=] call[name[ET].SubElement, parameter[name[trunk], constant[allowed]]] variable[vlan] assign[=] call[name[ET].SubElement, parameter[name[allowed], constant[vlan]]] variable[all] assign[=] call[name[ET].SubElement, parameter[name[vlan], constant[all]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[port_profile_vlan_profile_switchport_trunk_allowed_vlan_all] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[port_profile] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifier[xmlns] = literal[string] ) identifier[name_key] = identifier[ET] . identifier[SubElement] ( identifier[port_profile] , literal[string] ) identifier[name_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[vlan_profile] = identifier[ET] . identifier[SubElement] ( identifier[port_profile] , literal[string] ) identifier[switchport] = identifier[ET] . identifier[SubElement] ( identifier[vlan_profile] , literal[string] ) identifier[trunk] = identifier[ET] . identifier[SubElement] ( identifier[switchport] , literal[string] ) identifier[allowed] = identifier[ET] . identifier[SubElement] ( identifier[trunk] , literal[string] ) identifier[vlan] = identifier[ET] . identifier[SubElement] ( identifier[allowed] , literal[string] ) identifier[all] = identifier[ET] . identifier[SubElement] ( identifier[vlan] , literal[string] ) identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] ) keyword[return] identifier[callback] ( identifier[config] )
def port_profile_vlan_profile_switchport_trunk_allowed_vlan_all(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') port_profile = ET.SubElement(config, 'port-profile', xmlns='urn:brocade.com:mgmt:brocade-port-profile') name_key = ET.SubElement(port_profile, 'name') name_key.text = kwargs.pop('name') vlan_profile = ET.SubElement(port_profile, 'vlan-profile') switchport = ET.SubElement(vlan_profile, 'switchport') trunk = ET.SubElement(switchport, 'trunk') allowed = ET.SubElement(trunk, 'allowed') vlan = ET.SubElement(allowed, 'vlan') all = ET.SubElement(vlan, 'all') callback = kwargs.pop('callback', self._callback) return callback(config)
def _to_gzipfile(self, file_generator): """Convert file to gzip-compressed file. :return: None :rtype: :py:obj:`None` """ with gzip.GzipFile(file_generator.to_path, mode="wb") as outfile: for f in file_generator: outfile.write(f.writestr(file_generator.to_format).encode())
def function[_to_gzipfile, parameter[self, file_generator]]: constant[Convert file to gzip-compressed file. :return: None :rtype: :py:obj:`None` ] with call[name[gzip].GzipFile, parameter[name[file_generator].to_path]] begin[:] for taget[name[f]] in starred[name[file_generator]] begin[:] call[name[outfile].write, parameter[call[call[name[f].writestr, parameter[name[file_generator].to_format]].encode, parameter[]]]]
keyword[def] identifier[_to_gzipfile] ( identifier[self] , identifier[file_generator] ): literal[string] keyword[with] identifier[gzip] . identifier[GzipFile] ( identifier[file_generator] . identifier[to_path] , identifier[mode] = literal[string] ) keyword[as] identifier[outfile] : keyword[for] identifier[f] keyword[in] identifier[file_generator] : identifier[outfile] . identifier[write] ( identifier[f] . identifier[writestr] ( identifier[file_generator] . identifier[to_format] ). identifier[encode] ())
def _to_gzipfile(self, file_generator): """Convert file to gzip-compressed file. :return: None :rtype: :py:obj:`None` """ with gzip.GzipFile(file_generator.to_path, mode='wb') as outfile: for f in file_generator: outfile.write(f.writestr(file_generator.to_format).encode()) # depends on [control=['for'], data=['f']] # depends on [control=['with'], data=['outfile']]
def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end)
def function[day_interval, parameter[year, month, day, milliseconds, return_string]]: constant[ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) ] if name[milliseconds] begin[:] variable[delta] assign[=] call[name[timedelta], parameter[]] variable[start] assign[=] call[name[datetime], parameter[name[year], name[month], name[day]]] variable[end] assign[=] binary_operation[binary_operation[call[name[datetime], parameter[name[year], name[month], name[day]]] + call[name[timedelta], parameter[]]] - name[delta]] if <ast.UnaryOp object at 0x7da20cabeb00> begin[:] return[tuple[[<ast.Name object at 0x7da1b2886110>, <ast.Name object at 0x7da1b2884c70>]]]
keyword[def] identifier[day_interval] ( identifier[year] , identifier[month] , identifier[day] , identifier[milliseconds] = keyword[False] , identifier[return_string] = keyword[False] ): literal[string] keyword[if] identifier[milliseconds] : identifier[delta] = identifier[timedelta] ( identifier[milliseconds] = literal[int] ) keyword[else] : identifier[delta] = identifier[timedelta] ( identifier[seconds] = literal[int] ) identifier[start] = identifier[datetime] ( identifier[year] , identifier[month] , identifier[day] ) identifier[end] = identifier[datetime] ( identifier[year] , identifier[month] , identifier[day] )+ identifier[timedelta] ( identifier[days] = literal[int] )- identifier[delta] keyword[if] keyword[not] identifier[return_string] : keyword[return] identifier[start] , identifier[end] keyword[else] : keyword[return] identifier[str] ( identifier[start] ), identifier[str] ( identifier[end] )
def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) # depends on [control=['if'], data=[]] else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return (start, end) # depends on [control=['if'], data=[]] else: return (str(start), str(end))
def then_by(self, key_selector=identity): '''Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable. ''' if self.closed(): raise ValueError("Attempt to call then_by() on a " "closed OrderedQueryable.") if not is_callable(key_selector): raise TypeError("then_by() parameter key_selector={key_selector} " "is not callable".format(key_selector=repr(key_selector))) self._funcs.append((-1, key_selector)) return self
def function[then_by, parameter[self, key_selector]]: constant[Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable. ] if call[name[self].closed, parameter[]] begin[:] <ast.Raise object at 0x7da1b1930ca0> if <ast.UnaryOp object at 0x7da1b19319c0> begin[:] <ast.Raise object at 0x7da1b1933190> call[name[self]._funcs.append, parameter[tuple[[<ast.UnaryOp object at 0x7da1b1931ba0>, <ast.Name object at 0x7da1b1932f20>]]]] return[name[self]]
keyword[def] identifier[then_by] ( identifier[self] , identifier[key_selector] = identifier[identity] ): literal[string] keyword[if] identifier[self] . identifier[closed] (): keyword[raise] identifier[ValueError] ( literal[string] literal[string] ) keyword[if] keyword[not] identifier[is_callable] ( identifier[key_selector] ): keyword[raise] identifier[TypeError] ( literal[string] literal[string] . identifier[format] ( identifier[key_selector] = identifier[repr] ( identifier[key_selector] ))) identifier[self] . identifier[_funcs] . identifier[append] ((- literal[int] , identifier[key_selector] )) keyword[return] identifier[self]
def then_by(self, key_selector=identity): """Introduce subsequent ordering to the sequence with an optional key. The returned sequence will be sorted in ascending order by the selected key. Note: This method uses deferred execution. Args: key_selector: A unary function the only positional argument to which is the element value from which the key will be selected. The return value should be the key from that element. Returns: An OrderedQueryable over the sorted items. Raises: ValueError: If the OrderedQueryable is closed(). TypeError: If key_selector is not callable. """ if self.closed(): raise ValueError('Attempt to call then_by() on a closed OrderedQueryable.') # depends on [control=['if'], data=[]] if not is_callable(key_selector): raise TypeError('then_by() parameter key_selector={key_selector} is not callable'.format(key_selector=repr(key_selector))) # depends on [control=['if'], data=[]] self._funcs.append((-1, key_selector)) return self
def get_queryset(self): """Replicates Django CBV `get_queryset()` method, but for MongoEngine. """ if hasattr(self, "queryset") and self.queryset: return self.queryset self.set_mongonaut_base() self.set_mongoadmin() self.document = getattr(self.models, self.document_name) queryset = self.document.objects.all() if self.mongoadmin.ordering: queryset = queryset.order_by(*self.mongoadmin.ordering) # search. move this to get_queryset # search. move this to get_queryset q = self.request.GET.get('q') queryset = self.get_qset(queryset, q) ### Start pagination ### Note: ### Can't use Paginator in Django because mongoengine querysets are ### not the same as Django ORM querysets and it broke. # Make sure page request is an int. If not, deliver first page. try: self.page = int(self.request.GET.get('page', '1')) except ValueError: self.page = 1 obj_count = queryset.count() self.total_pages = math.ceil(obj_count / self.documents_per_page) if self.page > self.total_pages: self.page = self.total_pages if self.page < 1: self.page = 1 start = (self.page - 1) * self.documents_per_page end = self.page * self.documents_per_page queryset = queryset[start:end] if obj_count else queryset self.queryset = queryset return queryset
def function[get_queryset, parameter[self]]: constant[Replicates Django CBV `get_queryset()` method, but for MongoEngine. ] if <ast.BoolOp object at 0x7da1b01e5bd0> begin[:] return[name[self].queryset] call[name[self].set_mongonaut_base, parameter[]] call[name[self].set_mongoadmin, parameter[]] name[self].document assign[=] call[name[getattr], parameter[name[self].models, name[self].document_name]] variable[queryset] assign[=] call[name[self].document.objects.all, parameter[]] if name[self].mongoadmin.ordering begin[:] variable[queryset] assign[=] call[name[queryset].order_by, parameter[<ast.Starred object at 0x7da1b01e61a0>]] variable[q] assign[=] call[name[self].request.GET.get, parameter[constant[q]]] variable[queryset] assign[=] call[name[self].get_qset, parameter[name[queryset], name[q]]] <ast.Try object at 0x7da1b01e5780> variable[obj_count] assign[=] call[name[queryset].count, parameter[]] name[self].total_pages assign[=] call[name[math].ceil, parameter[binary_operation[name[obj_count] / name[self].documents_per_page]]] if compare[name[self].page greater[>] name[self].total_pages] begin[:] name[self].page assign[=] name[self].total_pages if compare[name[self].page less[<] constant[1]] begin[:] name[self].page assign[=] constant[1] variable[start] assign[=] binary_operation[binary_operation[name[self].page - constant[1]] * name[self].documents_per_page] variable[end] assign[=] binary_operation[name[self].page * name[self].documents_per_page] variable[queryset] assign[=] <ast.IfExp object at 0x7da1b0035300> name[self].queryset assign[=] name[queryset] return[name[queryset]]
keyword[def] identifier[get_queryset] ( identifier[self] ): literal[string] keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[queryset] : keyword[return] identifier[self] . identifier[queryset] identifier[self] . identifier[set_mongonaut_base] () identifier[self] . identifier[set_mongoadmin] () identifier[self] . identifier[document] = identifier[getattr] ( identifier[self] . identifier[models] , identifier[self] . identifier[document_name] ) identifier[queryset] = identifier[self] . identifier[document] . identifier[objects] . identifier[all] () keyword[if] identifier[self] . identifier[mongoadmin] . identifier[ordering] : identifier[queryset] = identifier[queryset] . identifier[order_by] (* identifier[self] . identifier[mongoadmin] . identifier[ordering] ) identifier[q] = identifier[self] . identifier[request] . identifier[GET] . identifier[get] ( literal[string] ) identifier[queryset] = identifier[self] . identifier[get_qset] ( identifier[queryset] , identifier[q] ) keyword[try] : identifier[self] . identifier[page] = identifier[int] ( identifier[self] . identifier[request] . identifier[GET] . identifier[get] ( literal[string] , literal[string] )) keyword[except] identifier[ValueError] : identifier[self] . identifier[page] = literal[int] identifier[obj_count] = identifier[queryset] . identifier[count] () identifier[self] . identifier[total_pages] = identifier[math] . identifier[ceil] ( identifier[obj_count] / identifier[self] . identifier[documents_per_page] ) keyword[if] identifier[self] . identifier[page] > identifier[self] . identifier[total_pages] : identifier[self] . identifier[page] = identifier[self] . identifier[total_pages] keyword[if] identifier[self] . identifier[page] < literal[int] : identifier[self] . identifier[page] = literal[int] identifier[start] =( identifier[self] . identifier[page] - literal[int] )* identifier[self] . identifier[documents_per_page] identifier[end] = identifier[self] . identifier[page] * identifier[self] . identifier[documents_per_page] identifier[queryset] = identifier[queryset] [ identifier[start] : identifier[end] ] keyword[if] identifier[obj_count] keyword[else] identifier[queryset] identifier[self] . identifier[queryset] = identifier[queryset] keyword[return] identifier[queryset]
def get_queryset(self): """Replicates Django CBV `get_queryset()` method, but for MongoEngine. """ if hasattr(self, 'queryset') and self.queryset: return self.queryset # depends on [control=['if'], data=[]] self.set_mongonaut_base() self.set_mongoadmin() self.document = getattr(self.models, self.document_name) queryset = self.document.objects.all() if self.mongoadmin.ordering: queryset = queryset.order_by(*self.mongoadmin.ordering) # depends on [control=['if'], data=[]] # search. move this to get_queryset # search. move this to get_queryset q = self.request.GET.get('q') queryset = self.get_qset(queryset, q) ### Start pagination ### Note: ### Can't use Paginator in Django because mongoengine querysets are ### not the same as Django ORM querysets and it broke. # Make sure page request is an int. If not, deliver first page. try: self.page = int(self.request.GET.get('page', '1')) # depends on [control=['try'], data=[]] except ValueError: self.page = 1 # depends on [control=['except'], data=[]] obj_count = queryset.count() self.total_pages = math.ceil(obj_count / self.documents_per_page) if self.page > self.total_pages: self.page = self.total_pages # depends on [control=['if'], data=[]] if self.page < 1: self.page = 1 # depends on [control=['if'], data=[]] start = (self.page - 1) * self.documents_per_page end = self.page * self.documents_per_page queryset = queryset[start:end] if obj_count else queryset self.queryset = queryset return queryset
def set_GW_options(self, nv_band=10, nc_band=10, n_iteration=5, n_grid=6, dE_grid=0.5): """ Set parameters in cell.in for a GW computation :param nv__band: number of valence bands to correct with GW :param nc_band: number of conduction bands to correct with GW :param n_iteration: number of iteration :param n_grid and dE_grid:: number of points and spacing in eV for correlation grid """ self.GW_options.update(nv_corr=nv_band, nc_corr=nc_band, nit_gw=n_iteration) self.correlation_grid.update(dE_grid=dE_grid, n_grid=n_grid)
def function[set_GW_options, parameter[self, nv_band, nc_band, n_iteration, n_grid, dE_grid]]: constant[ Set parameters in cell.in for a GW computation :param nv__band: number of valence bands to correct with GW :param nc_band: number of conduction bands to correct with GW :param n_iteration: number of iteration :param n_grid and dE_grid:: number of points and spacing in eV for correlation grid ] call[name[self].GW_options.update, parameter[]] call[name[self].correlation_grid.update, parameter[]]
keyword[def] identifier[set_GW_options] ( identifier[self] , identifier[nv_band] = literal[int] , identifier[nc_band] = literal[int] , identifier[n_iteration] = literal[int] , identifier[n_grid] = literal[int] , identifier[dE_grid] = literal[int] ): literal[string] identifier[self] . identifier[GW_options] . identifier[update] ( identifier[nv_corr] = identifier[nv_band] , identifier[nc_corr] = identifier[nc_band] , identifier[nit_gw] = identifier[n_iteration] ) identifier[self] . identifier[correlation_grid] . identifier[update] ( identifier[dE_grid] = identifier[dE_grid] , identifier[n_grid] = identifier[n_grid] )
def set_GW_options(self, nv_band=10, nc_band=10, n_iteration=5, n_grid=6, dE_grid=0.5): """ Set parameters in cell.in for a GW computation :param nv__band: number of valence bands to correct with GW :param nc_band: number of conduction bands to correct with GW :param n_iteration: number of iteration :param n_grid and dE_grid:: number of points and spacing in eV for correlation grid """ self.GW_options.update(nv_corr=nv_band, nc_corr=nc_band, nit_gw=n_iteration) self.correlation_grid.update(dE_grid=dE_grid, n_grid=n_grid)
def run_filter(vrn_file, align_bam, ref_file, data, items): """Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants. Moves damage estimation to INFO field, instead of leaving in FILTER. """ if not should_filter(items) or not vcfutils.vcf_has_variants(vrn_file): return data else: raw_file = "%s-damage.vcf" % utils.splitext_plus(vrn_file)[0] out_plot_files = ["%s%s" % (utils.splitext_plus(raw_file)[0], ext) for ext in ["_seq_bias_simplified.pdf", "_pcr_bias_simplified.pdf"]] if not utils.file_uptodate(raw_file, vrn_file) and not utils.file_uptodate(raw_file + ".gz", vrn_file): with file_transaction(items[0], raw_file) as tx_out_file: # Does not apply --qcSummary plotting due to slow runtimes cmd = ["dkfzbiasfilter.py", "--filterCycles", "1", "--passOnly", "--tempFolder", os.path.dirname(tx_out_file), vrn_file, align_bam, ref_file, tx_out_file] do.run(cmd, "Filter low frequency variants for DNA damage and strand bias") for out_plot in out_plot_files: tx_plot_file = os.path.join("%s_qcSummary" % utils.splitext_plus(tx_out_file)[0], "plots", os.path.basename(out_plot)) if utils.file_exists(tx_plot_file): shutil.move(tx_plot_file, out_plot) raw_file = vcfutils.bgzip_and_index(raw_file, items[0]["config"]) data["vrn_file"] = _filter_to_info(raw_file, items[0]) out_plot_files = [x for x in out_plot_files if utils.file_exists(x)] data["damage_plots"] = out_plot_files return data
def function[run_filter, parameter[vrn_file, align_bam, ref_file, data, items]]: constant[Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants. Moves damage estimation to INFO field, instead of leaving in FILTER. ] if <ast.BoolOp object at 0x7da1b18847c0> begin[:] return[name[data]]
keyword[def] identifier[run_filter] ( identifier[vrn_file] , identifier[align_bam] , identifier[ref_file] , identifier[data] , identifier[items] ): literal[string] keyword[if] keyword[not] identifier[should_filter] ( identifier[items] ) keyword[or] keyword[not] identifier[vcfutils] . identifier[vcf_has_variants] ( identifier[vrn_file] ): keyword[return] identifier[data] keyword[else] : identifier[raw_file] = literal[string] % identifier[utils] . identifier[splitext_plus] ( identifier[vrn_file] )[ literal[int] ] identifier[out_plot_files] =[ literal[string] %( identifier[utils] . identifier[splitext_plus] ( identifier[raw_file] )[ literal[int] ], identifier[ext] ) keyword[for] identifier[ext] keyword[in] [ literal[string] , literal[string] ]] keyword[if] keyword[not] identifier[utils] . identifier[file_uptodate] ( identifier[raw_file] , identifier[vrn_file] ) keyword[and] keyword[not] identifier[utils] . identifier[file_uptodate] ( identifier[raw_file] + literal[string] , identifier[vrn_file] ): keyword[with] identifier[file_transaction] ( identifier[items] [ literal[int] ], identifier[raw_file] ) keyword[as] identifier[tx_out_file] : identifier[cmd] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , identifier[os] . identifier[path] . identifier[dirname] ( identifier[tx_out_file] ), identifier[vrn_file] , identifier[align_bam] , identifier[ref_file] , identifier[tx_out_file] ] identifier[do] . identifier[run] ( identifier[cmd] , literal[string] ) keyword[for] identifier[out_plot] keyword[in] identifier[out_plot_files] : identifier[tx_plot_file] = identifier[os] . identifier[path] . identifier[join] ( literal[string] % identifier[utils] . identifier[splitext_plus] ( identifier[tx_out_file] )[ literal[int] ], literal[string] , identifier[os] . identifier[path] . identifier[basename] ( identifier[out_plot] )) keyword[if] identifier[utils] . identifier[file_exists] ( identifier[tx_plot_file] ): identifier[shutil] . identifier[move] ( identifier[tx_plot_file] , identifier[out_plot] ) identifier[raw_file] = identifier[vcfutils] . identifier[bgzip_and_index] ( identifier[raw_file] , identifier[items] [ literal[int] ][ literal[string] ]) identifier[data] [ literal[string] ]= identifier[_filter_to_info] ( identifier[raw_file] , identifier[items] [ literal[int] ]) identifier[out_plot_files] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[out_plot_files] keyword[if] identifier[utils] . identifier[file_exists] ( identifier[x] )] identifier[data] [ literal[string] ]= identifier[out_plot_files] keyword[return] identifier[data]
def run_filter(vrn_file, align_bam, ref_file, data, items): """Filter and annotate somatic VCFs with damage/bias artifacts on low frequency variants. Moves damage estimation to INFO field, instead of leaving in FILTER. """ if not should_filter(items) or not vcfutils.vcf_has_variants(vrn_file): return data # depends on [control=['if'], data=[]] else: raw_file = '%s-damage.vcf' % utils.splitext_plus(vrn_file)[0] out_plot_files = ['%s%s' % (utils.splitext_plus(raw_file)[0], ext) for ext in ['_seq_bias_simplified.pdf', '_pcr_bias_simplified.pdf']] if not utils.file_uptodate(raw_file, vrn_file) and (not utils.file_uptodate(raw_file + '.gz', vrn_file)): with file_transaction(items[0], raw_file) as tx_out_file: # Does not apply --qcSummary plotting due to slow runtimes cmd = ['dkfzbiasfilter.py', '--filterCycles', '1', '--passOnly', '--tempFolder', os.path.dirname(tx_out_file), vrn_file, align_bam, ref_file, tx_out_file] do.run(cmd, 'Filter low frequency variants for DNA damage and strand bias') for out_plot in out_plot_files: tx_plot_file = os.path.join('%s_qcSummary' % utils.splitext_plus(tx_out_file)[0], 'plots', os.path.basename(out_plot)) if utils.file_exists(tx_plot_file): shutil.move(tx_plot_file, out_plot) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['out_plot']] # depends on [control=['with'], data=['tx_out_file']] # depends on [control=['if'], data=[]] raw_file = vcfutils.bgzip_and_index(raw_file, items[0]['config']) data['vrn_file'] = _filter_to_info(raw_file, items[0]) out_plot_files = [x for x in out_plot_files if utils.file_exists(x)] data['damage_plots'] = out_plot_files return data
def _group_same_samples(ldetails): """Move samples into groups -- same groups have identical names. """ sample_groups = collections.defaultdict(list) for ldetail in ldetails: sample_groups[ldetail["name"]].append(ldetail) return sorted(sample_groups.values(), key=lambda xs: xs[0]["name"])
def function[_group_same_samples, parameter[ldetails]]: constant[Move samples into groups -- same groups have identical names. ] variable[sample_groups] assign[=] call[name[collections].defaultdict, parameter[name[list]]] for taget[name[ldetail]] in starred[name[ldetails]] begin[:] call[call[name[sample_groups]][call[name[ldetail]][constant[name]]].append, parameter[name[ldetail]]] return[call[name[sorted], parameter[call[name[sample_groups].values, parameter[]]]]]
keyword[def] identifier[_group_same_samples] ( identifier[ldetails] ): literal[string] identifier[sample_groups] = identifier[collections] . identifier[defaultdict] ( identifier[list] ) keyword[for] identifier[ldetail] keyword[in] identifier[ldetails] : identifier[sample_groups] [ identifier[ldetail] [ literal[string] ]]. identifier[append] ( identifier[ldetail] ) keyword[return] identifier[sorted] ( identifier[sample_groups] . identifier[values] (), identifier[key] = keyword[lambda] identifier[xs] : identifier[xs] [ literal[int] ][ literal[string] ])
def _group_same_samples(ldetails): """Move samples into groups -- same groups have identical names. """ sample_groups = collections.defaultdict(list) for ldetail in ldetails: sample_groups[ldetail['name']].append(ldetail) # depends on [control=['for'], data=['ldetail']] return sorted(sample_groups.values(), key=lambda xs: xs[0]['name'])
def pieces(array, chunk_size): """Yield successive chunks from array/list/string. Final chunk may be truncated if array is not evenly divisible by chunk_size.""" for i in range(0, len(array), chunk_size): yield array[i:i+chunk_size]
def function[pieces, parameter[array, chunk_size]]: constant[Yield successive chunks from array/list/string. Final chunk may be truncated if array is not evenly divisible by chunk_size.] for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[array]]], name[chunk_size]]]] begin[:] <ast.Yield object at 0x7da1b0a3aa70>
keyword[def] identifier[pieces] ( identifier[array] , identifier[chunk_size] ): literal[string] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[array] ), identifier[chunk_size] ): keyword[yield] identifier[array] [ identifier[i] : identifier[i] + identifier[chunk_size] ]
def pieces(array, chunk_size): """Yield successive chunks from array/list/string. Final chunk may be truncated if array is not evenly divisible by chunk_size.""" for i in range(0, len(array), chunk_size): yield array[i:i + chunk_size] # depends on [control=['for'], data=['i']]
def export_output(dskey, calc_id, datadir, target_dir, export_types): """ Simple UI wrapper around :func:`openquake.engine.export.core.export_from_db` yielding a summary of files exported, if any. """ outkey = get_outkey(dskey, export_types.split(',')) if export_types and not outkey: yield 'There is no exporter for %s, %s' % (dskey, export_types) return yield from export_from_db(outkey, calc_id, datadir, target_dir)
def function[export_output, parameter[dskey, calc_id, datadir, target_dir, export_types]]: constant[ Simple UI wrapper around :func:`openquake.engine.export.core.export_from_db` yielding a summary of files exported, if any. ] variable[outkey] assign[=] call[name[get_outkey], parameter[name[dskey], call[name[export_types].split, parameter[constant[,]]]]] if <ast.BoolOp object at 0x7da18ede5b40> begin[:] <ast.Yield object at 0x7da18ede61d0> return[None] <ast.YieldFrom object at 0x7da18ede5c90>
keyword[def] identifier[export_output] ( identifier[dskey] , identifier[calc_id] , identifier[datadir] , identifier[target_dir] , identifier[export_types] ): literal[string] identifier[outkey] = identifier[get_outkey] ( identifier[dskey] , identifier[export_types] . identifier[split] ( literal[string] )) keyword[if] identifier[export_types] keyword[and] keyword[not] identifier[outkey] : keyword[yield] literal[string] %( identifier[dskey] , identifier[export_types] ) keyword[return] keyword[yield] keyword[from] identifier[export_from_db] ( identifier[outkey] , identifier[calc_id] , identifier[datadir] , identifier[target_dir] )
def export_output(dskey, calc_id, datadir, target_dir, export_types): """ Simple UI wrapper around :func:`openquake.engine.export.core.export_from_db` yielding a summary of files exported, if any. """ outkey = get_outkey(dskey, export_types.split(',')) if export_types and (not outkey): yield ('There is no exporter for %s, %s' % (dskey, export_types)) return # depends on [control=['if'], data=[]] yield from export_from_db(outkey, calc_id, datadir, target_dir)
def reconstruct(self, b, X=None): """Reconstruct representation of signal b in signal set.""" if X is None: X = self.getcoef() Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),)*self.dimN + \ (slice(self.chncs[b], self.chncs[b+1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) return sl.irfftn(Sf, self.cbpdn.cri.Nv, self.cbpdn.cri.axisN)
def function[reconstruct, parameter[self, b, X]]: constant[Reconstruct representation of signal b in signal set.] if compare[name[X] is constant[None]] begin[:] variable[X] assign[=] call[name[self].getcoef, parameter[]] variable[Xf] assign[=] call[name[sl].rfftn, parameter[name[X], constant[None], name[self].cbpdn.cri.axisN]] variable[slc] assign[=] binary_operation[binary_operation[tuple[[<ast.Call object at 0x7da1b078ace0>]] * name[self].dimN] + tuple[[<ast.Call object at 0x7da1b078ad10>]]] variable[Sf] assign[=] call[name[np].sum, parameter[binary_operation[call[name[self].cbpdn.Df][name[slc]] * name[Xf]]]] return[call[name[sl].irfftn, parameter[name[Sf], name[self].cbpdn.cri.Nv, name[self].cbpdn.cri.axisN]]]
keyword[def] identifier[reconstruct] ( identifier[self] , identifier[b] , identifier[X] = keyword[None] ): literal[string] keyword[if] identifier[X] keyword[is] keyword[None] : identifier[X] = identifier[self] . identifier[getcoef] () identifier[Xf] = identifier[sl] . identifier[rfftn] ( identifier[X] , keyword[None] , identifier[self] . identifier[cbpdn] . identifier[cri] . identifier[axisN] ) identifier[slc] =( identifier[slice] ( keyword[None] ),)* identifier[self] . identifier[dimN] +( identifier[slice] ( identifier[self] . identifier[chncs] [ identifier[b] ], identifier[self] . identifier[chncs] [ identifier[b] + literal[int] ]),) identifier[Sf] = identifier[np] . identifier[sum] ( identifier[self] . identifier[cbpdn] . identifier[Df] [ identifier[slc] ]* identifier[Xf] , identifier[axis] = identifier[self] . identifier[cbpdn] . identifier[cri] . identifier[axisM] ) keyword[return] identifier[sl] . identifier[irfftn] ( identifier[Sf] , identifier[self] . identifier[cbpdn] . identifier[cri] . identifier[Nv] , identifier[self] . identifier[cbpdn] . identifier[cri] . identifier[axisN] )
def reconstruct(self, b, X=None): """Reconstruct representation of signal b in signal set.""" if X is None: X = self.getcoef() # depends on [control=['if'], data=['X']] Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),) * self.dimN + (slice(self.chncs[b], self.chncs[b + 1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) return sl.irfftn(Sf, self.cbpdn.cri.Nv, self.cbpdn.cri.axisN)
def Draw(self, stoplist=None, triplist=None, height=520): """Main interface for drawing the marey graph. If called without arguments, the data generated in the previous call will be used. New decorators can be added between calls. Args: # Class Stop is defined in transitfeed.py stoplist: [Stop, Stop, ...] # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] Returns: # A string that contain a svg/xml web-page with a marey graph. " <svg width="1440" height="520" version="1.1" ... " """ output = str() if not triplist: triplist = [] if not stoplist: stoplist = [] if not self._cache or triplist or stoplist: self._gheight = height self._tlist=triplist self._slist=stoplist self._decorators = [] self._stations = self._BuildStations(stoplist) self._cache = "%s %s %s %s" % (self._DrawBox(), self._DrawHours(), self._DrawStations(), self._DrawTrips(triplist)) output = "%s %s %s %s" % (self._DrawHeader(), self._cache, self._DrawDecorators(), self._DrawFooter()) return output
def function[Draw, parameter[self, stoplist, triplist, height]]: constant[Main interface for drawing the marey graph. If called without arguments, the data generated in the previous call will be used. New decorators can be added between calls. Args: # Class Stop is defined in transitfeed.py stoplist: [Stop, Stop, ...] # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] Returns: # A string that contain a svg/xml web-page with a marey graph. " <svg width="1440" height="520" version="1.1" ... " ] variable[output] assign[=] call[name[str], parameter[]] if <ast.UnaryOp object at 0x7da1b17abd90> begin[:] variable[triplist] assign[=] list[[]] if <ast.UnaryOp object at 0x7da1b17a9ba0> begin[:] variable[stoplist] assign[=] list[[]] if <ast.BoolOp object at 0x7da1b17ab1c0> begin[:] name[self]._gheight assign[=] name[height] name[self]._tlist assign[=] name[triplist] name[self]._slist assign[=] name[stoplist] name[self]._decorators assign[=] list[[]] name[self]._stations assign[=] call[name[self]._BuildStations, parameter[name[stoplist]]] name[self]._cache assign[=] binary_operation[constant[%s %s %s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b17b5cf0>, <ast.Call object at 0x7da1b17b5f00>, <ast.Call object at 0x7da1b17b6350>, <ast.Call object at 0x7da1b17b6230>]]] variable[output] assign[=] binary_operation[constant[%s %s %s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b17b62c0>, <ast.Attribute object at 0x7da1b17b7160>, <ast.Call object at 0x7da1b17b7130>, <ast.Call object at 0x7da1b17b63e0>]]] return[name[output]]
keyword[def] identifier[Draw] ( identifier[self] , identifier[stoplist] = keyword[None] , identifier[triplist] = keyword[None] , identifier[height] = literal[int] ): literal[string] identifier[output] = identifier[str] () keyword[if] keyword[not] identifier[triplist] : identifier[triplist] =[] keyword[if] keyword[not] identifier[stoplist] : identifier[stoplist] =[] keyword[if] keyword[not] identifier[self] . identifier[_cache] keyword[or] identifier[triplist] keyword[or] identifier[stoplist] : identifier[self] . identifier[_gheight] = identifier[height] identifier[self] . identifier[_tlist] = identifier[triplist] identifier[self] . identifier[_slist] = identifier[stoplist] identifier[self] . identifier[_decorators] =[] identifier[self] . identifier[_stations] = identifier[self] . identifier[_BuildStations] ( identifier[stoplist] ) identifier[self] . identifier[_cache] = literal[string] %( identifier[self] . identifier[_DrawBox] (), identifier[self] . identifier[_DrawHours] (), identifier[self] . identifier[_DrawStations] (), identifier[self] . identifier[_DrawTrips] ( identifier[triplist] )) identifier[output] = literal[string] %( identifier[self] . identifier[_DrawHeader] (), identifier[self] . identifier[_cache] , identifier[self] . identifier[_DrawDecorators] (), identifier[self] . identifier[_DrawFooter] ()) keyword[return] identifier[output]
def Draw(self, stoplist=None, triplist=None, height=520): """Main interface for drawing the marey graph. If called without arguments, the data generated in the previous call will be used. New decorators can be added between calls. Args: # Class Stop is defined in transitfeed.py stoplist: [Stop, Stop, ...] # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] Returns: # A string that contain a svg/xml web-page with a marey graph. " <svg width="1440" height="520" version="1.1" ... " """ output = str() if not triplist: triplist = [] # depends on [control=['if'], data=[]] if not stoplist: stoplist = [] # depends on [control=['if'], data=[]] if not self._cache or triplist or stoplist: self._gheight = height self._tlist = triplist self._slist = stoplist self._decorators = [] self._stations = self._BuildStations(stoplist) self._cache = '%s %s %s %s' % (self._DrawBox(), self._DrawHours(), self._DrawStations(), self._DrawTrips(triplist)) # depends on [control=['if'], data=[]] output = '%s %s %s %s' % (self._DrawHeader(), self._cache, self._DrawDecorators(), self._DrawFooter()) return output
def _api_query(self, protection=None, path_dict=None, options=None): """ Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict """ if not options: options = {} if self.api_version not in path_dict: raise Exception('method call not available under API version {}'.format(self.api_version)) request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1 request_url = request_url.format(path=path_dict[self.api_version]) nonce = str(int(time.time() * 1000)) if protection != PROTECTION_PUB: request_url = "{0}apikey={1}&nonce={2}&".format(request_url, self.api_key, nonce) request_url += urlencode(options) try: if sys.version_info >= (3, 0) and protection != PROTECTION_PUB: apisign = hmac.new(bytearray(self.api_secret, 'ascii'), bytearray(request_url, 'ascii'), hashlib.sha512).hexdigest() else: apisign = hmac.new(self.api_secret.encode(), request_url.encode(), hashlib.sha512).hexdigest() self.wait() return self.dispatch(request_url, apisign) except Exception: return { 'success': False, 'message': 'NO_API_RESPONSE', 'result': None }
def function[_api_query, parameter[self, protection, path_dict, options]]: constant[ Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict ] if <ast.UnaryOp object at 0x7da2044c3f40> begin[:] variable[options] assign[=] dictionary[[], []] if compare[name[self].api_version <ast.NotIn object at 0x7da2590d7190> name[path_dict]] begin[:] <ast.Raise object at 0x7da2044c3b80> variable[request_url] assign[=] <ast.IfExp object at 0x7da2044c3520> variable[request_url] assign[=] call[name[request_url].format, parameter[]] variable[nonce] assign[=] call[name[str], parameter[call[name[int], parameter[binary_operation[call[name[time].time, parameter[]] * constant[1000]]]]]] if compare[name[protection] not_equal[!=] name[PROTECTION_PUB]] begin[:] variable[request_url] assign[=] call[constant[{0}apikey={1}&nonce={2}&].format, parameter[name[request_url], name[self].api_key, name[nonce]]] <ast.AugAssign object at 0x7da18eb57640> <ast.Try object at 0x7da18eb56410>
keyword[def] identifier[_api_query] ( identifier[self] , identifier[protection] = keyword[None] , identifier[path_dict] = keyword[None] , identifier[options] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[options] : identifier[options] ={} keyword[if] identifier[self] . identifier[api_version] keyword[not] keyword[in] identifier[path_dict] : keyword[raise] identifier[Exception] ( literal[string] . identifier[format] ( identifier[self] . identifier[api_version] )) identifier[request_url] = identifier[BASE_URL_V2_0] keyword[if] identifier[self] . identifier[api_version] == identifier[API_V2_0] keyword[else] identifier[BASE_URL_V1_1] identifier[request_url] = identifier[request_url] . identifier[format] ( identifier[path] = identifier[path_dict] [ identifier[self] . identifier[api_version] ]) identifier[nonce] = identifier[str] ( identifier[int] ( identifier[time] . identifier[time] ()* literal[int] )) keyword[if] identifier[protection] != identifier[PROTECTION_PUB] : identifier[request_url] = literal[string] . identifier[format] ( identifier[request_url] , identifier[self] . identifier[api_key] , identifier[nonce] ) identifier[request_url] += identifier[urlencode] ( identifier[options] ) keyword[try] : keyword[if] identifier[sys] . identifier[version_info] >=( literal[int] , literal[int] ) keyword[and] identifier[protection] != identifier[PROTECTION_PUB] : identifier[apisign] = identifier[hmac] . identifier[new] ( identifier[bytearray] ( identifier[self] . identifier[api_secret] , literal[string] ), identifier[bytearray] ( identifier[request_url] , literal[string] ), identifier[hashlib] . identifier[sha512] ). identifier[hexdigest] () keyword[else] : identifier[apisign] = identifier[hmac] . identifier[new] ( identifier[self] . identifier[api_secret] . identifier[encode] (), identifier[request_url] . identifier[encode] (), identifier[hashlib] . identifier[sha512] ). identifier[hexdigest] () identifier[self] . identifier[wait] () keyword[return] identifier[self] . identifier[dispatch] ( identifier[request_url] , identifier[apisign] ) keyword[except] identifier[Exception] : keyword[return] { literal[string] : keyword[False] , literal[string] : literal[string] , literal[string] : keyword[None] }
def _api_query(self, protection=None, path_dict=None, options=None): """ Queries Bittrex :param request_url: fully-formed URL to request :type options: dict :return: JSON response from Bittrex :rtype : dict """ if not options: options = {} # depends on [control=['if'], data=[]] if self.api_version not in path_dict: raise Exception('method call not available under API version {}'.format(self.api_version)) # depends on [control=['if'], data=[]] request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1 request_url = request_url.format(path=path_dict[self.api_version]) nonce = str(int(time.time() * 1000)) if protection != PROTECTION_PUB: request_url = '{0}apikey={1}&nonce={2}&'.format(request_url, self.api_key, nonce) # depends on [control=['if'], data=[]] request_url += urlencode(options) try: if sys.version_info >= (3, 0) and protection != PROTECTION_PUB: apisign = hmac.new(bytearray(self.api_secret, 'ascii'), bytearray(request_url, 'ascii'), hashlib.sha512).hexdigest() # depends on [control=['if'], data=[]] else: apisign = hmac.new(self.api_secret.encode(), request_url.encode(), hashlib.sha512).hexdigest() self.wait() return self.dispatch(request_url, apisign) # depends on [control=['try'], data=[]] except Exception: return {'success': False, 'message': 'NO_API_RESPONSE', 'result': None} # depends on [control=['except'], data=[]]
def get_bounding_box(self): """ Get the bounding box of a pointlist. """ pointlist = self.get_pointlist() # Initialize bounding box parameters to save values minx, maxx = pointlist[0][0]["x"], pointlist[0][0]["x"] miny, maxy = pointlist[0][0]["y"], pointlist[0][0]["y"] mint, maxt = pointlist[0][0]["time"], pointlist[0][0]["time"] # Adjust parameters for stroke in pointlist: for p in stroke: minx, maxx = min(minx, p["x"]), max(maxx, p["x"]) miny, maxy = min(miny, p["y"]), max(maxy, p["y"]) mint, maxt = min(mint, p["time"]), max(maxt, p["time"]) return {"minx": minx, "maxx": maxx, "miny": miny, "maxy": maxy, "mint": mint, "maxt": maxt}
def function[get_bounding_box, parameter[self]]: constant[ Get the bounding box of a pointlist. ] variable[pointlist] assign[=] call[name[self].get_pointlist, parameter[]] <ast.Tuple object at 0x7da1b2829bd0> assign[=] tuple[[<ast.Subscript object at 0x7da1b282b7c0>, <ast.Subscript object at 0x7da1b2829f90>]] <ast.Tuple object at 0x7da1b282a230> assign[=] tuple[[<ast.Subscript object at 0x7da1b282a380>, <ast.Subscript object at 0x7da1b282ba60>]] <ast.Tuple object at 0x7da1b282ab90> assign[=] tuple[[<ast.Subscript object at 0x7da1b282b5b0>, <ast.Subscript object at 0x7da1b282bcd0>]] for taget[name[stroke]] in starred[name[pointlist]] begin[:] for taget[name[p]] in starred[name[stroke]] begin[:] <ast.Tuple object at 0x7da1b283a6b0> assign[=] tuple[[<ast.Call object at 0x7da1b283af20>, <ast.Call object at 0x7da1b283a3e0>]] <ast.Tuple object at 0x7da1b2838850> assign[=] tuple[[<ast.Call object at 0x7da1b28381f0>, <ast.Call object at 0x7da1b283aec0>]] <ast.Tuple object at 0x7da1b283a0b0> assign[=] tuple[[<ast.Call object at 0x7da1b2866e30>, <ast.Call object at 0x7da1b28536a0>]] return[dictionary[[<ast.Constant object at 0x7da1b2852650>, <ast.Constant object at 0x7da1b2853580>, <ast.Constant object at 0x7da1b2852050>, <ast.Constant object at 0x7da1b2850370>, <ast.Constant object at 0x7da1b2853df0>, <ast.Constant object at 0x7da1b2853100>], [<ast.Name object at 0x7da1b2850ac0>, <ast.Name object at 0x7da1b2852c20>, <ast.Name object at 0x7da1b2851690>, <ast.Name object at 0x7da1b2850130>, <ast.Name object at 0x7da1b2850940>, <ast.Name object at 0x7da1b2853fd0>]]]
keyword[def] identifier[get_bounding_box] ( identifier[self] ): literal[string] identifier[pointlist] = identifier[self] . identifier[get_pointlist] () identifier[minx] , identifier[maxx] = identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ], identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ] identifier[miny] , identifier[maxy] = identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ], identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ] identifier[mint] , identifier[maxt] = identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ], identifier[pointlist] [ literal[int] ][ literal[int] ][ literal[string] ] keyword[for] identifier[stroke] keyword[in] identifier[pointlist] : keyword[for] identifier[p] keyword[in] identifier[stroke] : identifier[minx] , identifier[maxx] = identifier[min] ( identifier[minx] , identifier[p] [ literal[string] ]), identifier[max] ( identifier[maxx] , identifier[p] [ literal[string] ]) identifier[miny] , identifier[maxy] = identifier[min] ( identifier[miny] , identifier[p] [ literal[string] ]), identifier[max] ( identifier[maxy] , identifier[p] [ literal[string] ]) identifier[mint] , identifier[maxt] = identifier[min] ( identifier[mint] , identifier[p] [ literal[string] ]), identifier[max] ( identifier[maxt] , identifier[p] [ literal[string] ]) keyword[return] { literal[string] : identifier[minx] , literal[string] : identifier[maxx] , literal[string] : identifier[miny] , literal[string] : identifier[maxy] , literal[string] : identifier[mint] , literal[string] : identifier[maxt] }
def get_bounding_box(self): """ Get the bounding box of a pointlist. """ pointlist = self.get_pointlist() # Initialize bounding box parameters to save values (minx, maxx) = (pointlist[0][0]['x'], pointlist[0][0]['x']) (miny, maxy) = (pointlist[0][0]['y'], pointlist[0][0]['y']) (mint, maxt) = (pointlist[0][0]['time'], pointlist[0][0]['time']) # Adjust parameters for stroke in pointlist: for p in stroke: (minx, maxx) = (min(minx, p['x']), max(maxx, p['x'])) (miny, maxy) = (min(miny, p['y']), max(maxy, p['y'])) (mint, maxt) = (min(mint, p['time']), max(maxt, p['time'])) # depends on [control=['for'], data=['p']] # depends on [control=['for'], data=['stroke']] return {'minx': minx, 'maxx': maxx, 'miny': miny, 'maxy': maxy, 'mint': mint, 'maxt': maxt}
def raise_acknowledge_log_entry(self): """Raise HOST ACKNOWLEDGE ALERT entry (critical level) :return: None """ if not self.__class__.log_acknowledgements: return brok = make_monitoring_log( 'info', "HOST ACKNOWLEDGE ALERT: %s;STARTED; " "Host problem has been acknowledged" % self.get_name() ) self.broks.append(brok)
def function[raise_acknowledge_log_entry, parameter[self]]: constant[Raise HOST ACKNOWLEDGE ALERT entry (critical level) :return: None ] if <ast.UnaryOp object at 0x7da207f03460> begin[:] return[None] variable[brok] assign[=] call[name[make_monitoring_log], parameter[constant[info], binary_operation[constant[HOST ACKNOWLEDGE ALERT: %s;STARTED; Host problem has been acknowledged] <ast.Mod object at 0x7da2590d6920> call[name[self].get_name, parameter[]]]]] call[name[self].broks.append, parameter[name[brok]]]
keyword[def] identifier[raise_acknowledge_log_entry] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[__class__] . identifier[log_acknowledgements] : keyword[return] identifier[brok] = identifier[make_monitoring_log] ( literal[string] , literal[string] literal[string] % identifier[self] . identifier[get_name] () ) identifier[self] . identifier[broks] . identifier[append] ( identifier[brok] )
def raise_acknowledge_log_entry(self): """Raise HOST ACKNOWLEDGE ALERT entry (critical level) :return: None """ if not self.__class__.log_acknowledgements: return # depends on [control=['if'], data=[]] brok = make_monitoring_log('info', 'HOST ACKNOWLEDGE ALERT: %s;STARTED; Host problem has been acknowledged' % self.get_name()) self.broks.append(brok)
def notify(self, *args, **kwargs): '''Call all the callback handlers with given arguments.''' for handler in tuple(self.handlers): handler(*args, **kwargs)
def function[notify, parameter[self]]: constant[Call all the callback handlers with given arguments.] for taget[name[handler]] in starred[call[name[tuple], parameter[name[self].handlers]]] begin[:] call[name[handler], parameter[<ast.Starred object at 0x7da20eb29de0>]]
keyword[def] identifier[notify] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[for] identifier[handler] keyword[in] identifier[tuple] ( identifier[self] . identifier[handlers] ): identifier[handler] (* identifier[args] ,** identifier[kwargs] )
def notify(self, *args, **kwargs): """Call all the callback handlers with given arguments.""" for handler in tuple(self.handlers): handler(*args, **kwargs) # depends on [control=['for'], data=['handler']]
def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if np.any(notna(other)) and not self._can_hold_element(other): # coercion issues # let higher levels handle raise TypeError("cannot convert {} to an {}".format( type(other).__name__, type(self).__name__.lower().replace('Block', ''))) return values, other
def function[_try_coerce_args, parameter[self, values, other]]: constant[ provide coercion to our input arguments ] if <ast.BoolOp object at 0x7da18fe92cb0> begin[:] <ast.Raise object at 0x7da18fe92b00> return[tuple[[<ast.Name object at 0x7da1b206abf0>, <ast.Name object at 0x7da1b206b100>]]]
keyword[def] identifier[_try_coerce_args] ( identifier[self] , identifier[values] , identifier[other] ): literal[string] keyword[if] identifier[np] . identifier[any] ( identifier[notna] ( identifier[other] )) keyword[and] keyword[not] identifier[self] . identifier[_can_hold_element] ( identifier[other] ): keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[type] ( identifier[other] ). identifier[__name__] , identifier[type] ( identifier[self] ). identifier[__name__] . identifier[lower] (). identifier[replace] ( literal[string] , literal[string] ))) keyword[return] identifier[values] , identifier[other]
def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if np.any(notna(other)) and (not self._can_hold_element(other)): # coercion issues # let higher levels handle raise TypeError('cannot convert {} to an {}'.format(type(other).__name__, type(self).__name__.lower().replace('Block', ''))) # depends on [control=['if'], data=[]] return (values, other)
def get_conf_value(self, value, header="", plugin_name=None): """Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var. """ if plugin_name is None: # If not default use the current plugin name plugin_name = self.plugin_name if header != "": # Add the header plugin_name = plugin_name + '_' + header try: return self._limits[plugin_name + '_' + value] except KeyError: return []
def function[get_conf_value, parameter[self, value, header, plugin_name]]: constant[Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var. ] if compare[name[plugin_name] is constant[None]] begin[:] variable[plugin_name] assign[=] name[self].plugin_name if compare[name[header] not_equal[!=] constant[]] begin[:] variable[plugin_name] assign[=] binary_operation[binary_operation[name[plugin_name] + constant[_]] + name[header]] <ast.Try object at 0x7da18dc07f10>
keyword[def] identifier[get_conf_value] ( identifier[self] , identifier[value] , identifier[header] = literal[string] , identifier[plugin_name] = keyword[None] ): literal[string] keyword[if] identifier[plugin_name] keyword[is] keyword[None] : identifier[plugin_name] = identifier[self] . identifier[plugin_name] keyword[if] identifier[header] != literal[string] : identifier[plugin_name] = identifier[plugin_name] + literal[string] + identifier[header] keyword[try] : keyword[return] identifier[self] . identifier[_limits] [ identifier[plugin_name] + literal[string] + identifier[value] ] keyword[except] identifier[KeyError] : keyword[return] []
def get_conf_value(self, value, header='', plugin_name=None): """Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var. """ if plugin_name is None: # If not default use the current plugin name plugin_name = self.plugin_name # depends on [control=['if'], data=['plugin_name']] if header != '': # Add the header plugin_name = plugin_name + '_' + header # depends on [control=['if'], data=['header']] try: return self._limits[plugin_name + '_' + value] # depends on [control=['try'], data=[]] except KeyError: return [] # depends on [control=['except'], data=[]]
def get_any_node(self, addr, is_syscall=None, anyaddr=False, force_fastpath=False): """ Get an arbitrary CFGNode (without considering their contexts) from our graph. :param int addr: Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address. :param bool is_syscall: Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the targer it returns to. None means get either, True means get a syscall node, False means get something that isn't a syscall node. :param bool anyaddr: If anyaddr is True, then addr doesn't have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which is slow. If you need to do many such queries, you may first call `generate_index()` to create some indices that may speed up the query. :param bool force_fastpath: If force_fastpath is True, it will only perform a dict lookup in the _nodes_by_addr dict. :return: A CFGNode if there is any that satisfies given conditions, or None otherwise """ # fastpath: directly look in the nodes list if not anyaddr: try: return self._nodes_by_addr[addr][0] except (KeyError, IndexError): pass if force_fastpath: return None # slower path #if self._node_lookup_index is not None: # pass # the slowest path # try to show a warning first # TODO: re-enable it once the segment tree is implemented #if self._node_lookup_index_warned == False: # l.warning('Calling get_any_node() with anyaddr=True is slow on large programs. ' # 'For better performance, you may first call generate_index() to generate some indices that may ' # 'speed the node lookup.') # self._node_lookup_index_warned = True for n in self.graph.nodes(): if self.ident == "CFGEmulated": cond = n.looping_times == 0 else: cond = True if anyaddr and n.size is not None: cond = cond and n.addr <= addr < n.addr + n.size else: cond = cond and (addr == n.addr) if cond: if is_syscall is None: return n if n.is_syscall == is_syscall: return n return None
def function[get_any_node, parameter[self, addr, is_syscall, anyaddr, force_fastpath]]: constant[ Get an arbitrary CFGNode (without considering their contexts) from our graph. :param int addr: Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address. :param bool is_syscall: Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the targer it returns to. None means get either, True means get a syscall node, False means get something that isn't a syscall node. :param bool anyaddr: If anyaddr is True, then addr doesn't have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which is slow. If you need to do many such queries, you may first call `generate_index()` to create some indices that may speed up the query. :param bool force_fastpath: If force_fastpath is True, it will only perform a dict lookup in the _nodes_by_addr dict. :return: A CFGNode if there is any that satisfies given conditions, or None otherwise ] if <ast.UnaryOp object at 0x7da18bc71180> begin[:] <ast.Try object at 0x7da18bc715d0> if name[force_fastpath] begin[:] return[constant[None]] for taget[name[n]] in starred[call[name[self].graph.nodes, parameter[]]] begin[:] if compare[name[self].ident equal[==] constant[CFGEmulated]] begin[:] variable[cond] assign[=] compare[name[n].looping_times equal[==] constant[0]] if <ast.BoolOp object at 0x7da18bc73f70> begin[:] variable[cond] assign[=] <ast.BoolOp object at 0x7da18bc720b0> if name[cond] begin[:] if compare[name[is_syscall] is constant[None]] begin[:] return[name[n]] if compare[name[n].is_syscall equal[==] name[is_syscall]] begin[:] return[name[n]] return[constant[None]]
keyword[def] identifier[get_any_node] ( identifier[self] , identifier[addr] , identifier[is_syscall] = keyword[None] , identifier[anyaddr] = keyword[False] , identifier[force_fastpath] = keyword[False] ): literal[string] keyword[if] keyword[not] identifier[anyaddr] : keyword[try] : keyword[return] identifier[self] . identifier[_nodes_by_addr] [ identifier[addr] ][ literal[int] ] keyword[except] ( identifier[KeyError] , identifier[IndexError] ): keyword[pass] keyword[if] identifier[force_fastpath] : keyword[return] keyword[None] keyword[for] identifier[n] keyword[in] identifier[self] . identifier[graph] . identifier[nodes] (): keyword[if] identifier[self] . identifier[ident] == literal[string] : identifier[cond] = identifier[n] . identifier[looping_times] == literal[int] keyword[else] : identifier[cond] = keyword[True] keyword[if] identifier[anyaddr] keyword[and] identifier[n] . identifier[size] keyword[is] keyword[not] keyword[None] : identifier[cond] = identifier[cond] keyword[and] identifier[n] . identifier[addr] <= identifier[addr] < identifier[n] . identifier[addr] + identifier[n] . identifier[size] keyword[else] : identifier[cond] = identifier[cond] keyword[and] ( identifier[addr] == identifier[n] . identifier[addr] ) keyword[if] identifier[cond] : keyword[if] identifier[is_syscall] keyword[is] keyword[None] : keyword[return] identifier[n] keyword[if] identifier[n] . identifier[is_syscall] == identifier[is_syscall] : keyword[return] identifier[n] keyword[return] keyword[None]
def get_any_node(self, addr, is_syscall=None, anyaddr=False, force_fastpath=False): """ Get an arbitrary CFGNode (without considering their contexts) from our graph. :param int addr: Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address. :param bool is_syscall: Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the targer it returns to. None means get either, True means get a syscall node, False means get something that isn't a syscall node. :param bool anyaddr: If anyaddr is True, then addr doesn't have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which is slow. If you need to do many such queries, you may first call `generate_index()` to create some indices that may speed up the query. :param bool force_fastpath: If force_fastpath is True, it will only perform a dict lookup in the _nodes_by_addr dict. :return: A CFGNode if there is any that satisfies given conditions, or None otherwise """ # fastpath: directly look in the nodes list if not anyaddr: try: return self._nodes_by_addr[addr][0] # depends on [control=['try'], data=[]] except (KeyError, IndexError): pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if force_fastpath: return None # depends on [control=['if'], data=[]] # slower path #if self._node_lookup_index is not None: # pass # the slowest path # try to show a warning first # TODO: re-enable it once the segment tree is implemented #if self._node_lookup_index_warned == False: # l.warning('Calling get_any_node() with anyaddr=True is slow on large programs. ' # 'For better performance, you may first call generate_index() to generate some indices that may ' # 'speed the node lookup.') # self._node_lookup_index_warned = True for n in self.graph.nodes(): if self.ident == 'CFGEmulated': cond = n.looping_times == 0 # depends on [control=['if'], data=[]] else: cond = True if anyaddr and n.size is not None: cond = cond and n.addr <= addr < n.addr + n.size # depends on [control=['if'], data=[]] else: cond = cond and addr == n.addr if cond: if is_syscall is None: return n # depends on [control=['if'], data=[]] if n.is_syscall == is_syscall: return n # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['n']] return None
def tx_max(tasmax, freq='YS'): r"""Highest max temperature The maximum value of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Maximum value of daily maximum temperature. Notes ----- Let :math:`TX_{ij}` be the maximum temperature at day :math:`i` of period :math:`j`. Then the maximum daily maximum temperature for period :math:`j` is: .. math:: TXx_j = max(TX_{ij}) """ return tasmax.resample(time=freq).max(dim='time', keep_attrs=True)
def function[tx_max, parameter[tasmax, freq]]: constant[Highest max temperature The maximum value of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Maximum value of daily maximum temperature. Notes ----- Let :math:`TX_{ij}` be the maximum temperature at day :math:`i` of period :math:`j`. Then the maximum daily maximum temperature for period :math:`j` is: .. math:: TXx_j = max(TX_{ij}) ] return[call[call[name[tasmax].resample, parameter[]].max, parameter[]]]
keyword[def] identifier[tx_max] ( identifier[tasmax] , identifier[freq] = literal[string] ): literal[string] keyword[return] identifier[tasmax] . identifier[resample] ( identifier[time] = identifier[freq] ). identifier[max] ( identifier[dim] = literal[string] , identifier[keep_attrs] = keyword[True] )
def tx_max(tasmax, freq='YS'): """Highest max temperature The maximum value of daily maximum temperature. Parameters ---------- tasmax : xarray.DataArray Maximum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Maximum value of daily maximum temperature. Notes ----- Let :math:`TX_{ij}` be the maximum temperature at day :math:`i` of period :math:`j`. Then the maximum daily maximum temperature for period :math:`j` is: .. math:: TXx_j = max(TX_{ij}) """ return tasmax.resample(time=freq).max(dim='time', keep_attrs=True)
def _get_newsfeeds(self, uri, detail_level = None): '''General purpose function to get newsfeeds Args: uri uri for the feed base detail_level arguments for req str ['ALL', 'CONDENSED'] return list of feed dicts parse at your convenience ''' if detail_level: if detail_level not in ['ALL', 'CONDENSED']: return requests.codes.bad_request, {'success' : 'False', 'error': 'detailLevel needs to be provided and field_type needs to be \'ALL\' or \'CONDENSED\''} uri += self.detail_level_suffix + detail_level return self._req('get', uri)
def function[_get_newsfeeds, parameter[self, uri, detail_level]]: constant[General purpose function to get newsfeeds Args: uri uri for the feed base detail_level arguments for req str ['ALL', 'CONDENSED'] return list of feed dicts parse at your convenience ] if name[detail_level] begin[:] if compare[name[detail_level] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7da18dc9b310>, <ast.Constant object at 0x7da18dc9a0e0>]]] begin[:] return[tuple[[<ast.Attribute object at 0x7da18dc9bdf0>, <ast.Dict object at 0x7da18dc9af50>]]] <ast.AugAssign object at 0x7da18dc98820> return[call[name[self]._req, parameter[constant[get], name[uri]]]]
keyword[def] identifier[_get_newsfeeds] ( identifier[self] , identifier[uri] , identifier[detail_level] = keyword[None] ): literal[string] keyword[if] identifier[detail_level] : keyword[if] identifier[detail_level] keyword[not] keyword[in] [ literal[string] , literal[string] ]: keyword[return] identifier[requests] . identifier[codes] . identifier[bad_request] ,{ literal[string] : literal[string] , literal[string] : literal[string] } identifier[uri] += identifier[self] . identifier[detail_level_suffix] + identifier[detail_level] keyword[return] identifier[self] . identifier[_req] ( literal[string] , identifier[uri] )
def _get_newsfeeds(self, uri, detail_level=None): """General purpose function to get newsfeeds Args: uri uri for the feed base detail_level arguments for req str ['ALL', 'CONDENSED'] return list of feed dicts parse at your convenience """ if detail_level: if detail_level not in ['ALL', 'CONDENSED']: return (requests.codes.bad_request, {'success': 'False', 'error': "detailLevel needs to be provided and field_type needs to be 'ALL' or 'CONDENSED'"}) # depends on [control=['if'], data=[]] uri += self.detail_level_suffix + detail_level # depends on [control=['if'], data=[]] return self._req('get', uri)
def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]: """ Transforms transactions for ledger! Returns: Whether catchup reply corresponding to seq_no Name of node from which txns came Number of transactions ready to be processed """ # TODO: Remove after stop passing seqNo here assert seq_no == txns_to_process[0][0] # Here seqNo has to be the seqNo of first transaction of # `catchupReplies` # Get the transactions in the catchup reply which has sequence # number `seqNo` node_name, catchup_rep = self._find_catchup_reply_for_seq_no(seq_no) txns = catchup_rep.txns # Add only those transaction in the temporary tree from the above # batch which are not present in the ledger # Integer keys being converted to strings when marshaled to JSON txns = [self._provider.transform_txn_for_ledger(txn) for s, txn in txns_to_process[:len(txns)] if str(s) in txns] # Creating a temporary tree which will be used to verify consistency # proof, by inserting transactions. Duplicating a merkle tree is not # expensive since we are using a compact merkle tree. temp_tree = self._ledger.treeWithAppliedTxns(txns) proof = catchup_rep.consProof final_size = self._catchup_till.final_size final_hash = self._catchup_till.final_hash try: logger.info("{} verifying proof for {}, {}, {}, {}, {}". format(self, temp_tree.tree_size, final_size, temp_tree.root_hash, final_hash, proof)) verified = self._provider.verifier(self._ledger_id).verify_tree_consistency( temp_tree.tree_size, final_size, temp_tree.root_hash, Ledger.strToHash(final_hash), [Ledger.strToHash(p) for p in proof] ) except Exception as ex: logger.info("{} could not verify catchup reply {} since {}".format(self, catchup_rep, ex)) verified = False return bool(verified), node_name, len(txns)
def function[_has_valid_catchup_replies, parameter[self, seq_no, txns_to_process]]: constant[ Transforms transactions for ledger! Returns: Whether catchup reply corresponding to seq_no Name of node from which txns came Number of transactions ready to be processed ] assert[compare[name[seq_no] equal[==] call[call[name[txns_to_process]][constant[0]]][constant[0]]]] <ast.Tuple object at 0x7da2054a7730> assign[=] call[name[self]._find_catchup_reply_for_seq_no, parameter[name[seq_no]]] variable[txns] assign[=] name[catchup_rep].txns variable[txns] assign[=] <ast.ListComp object at 0x7da2054a4640> variable[temp_tree] assign[=] call[name[self]._ledger.treeWithAppliedTxns, parameter[name[txns]]] variable[proof] assign[=] name[catchup_rep].consProof variable[final_size] assign[=] name[self]._catchup_till.final_size variable[final_hash] assign[=] name[self]._catchup_till.final_hash <ast.Try object at 0x7da2054a72b0> return[tuple[[<ast.Call object at 0x7da2054a7370>, <ast.Name object at 0x7da2054a4160>, <ast.Call object at 0x7da2054a55a0>]]]
keyword[def] identifier[_has_valid_catchup_replies] ( identifier[self] , identifier[seq_no] : identifier[int] , identifier[txns_to_process] : identifier[List] [ identifier[Tuple] [ identifier[int] , identifier[Any] ]])-> identifier[Tuple] [ identifier[bool] , identifier[str] , identifier[int] ]: literal[string] keyword[assert] identifier[seq_no] == identifier[txns_to_process] [ literal[int] ][ literal[int] ] identifier[node_name] , identifier[catchup_rep] = identifier[self] . identifier[_find_catchup_reply_for_seq_no] ( identifier[seq_no] ) identifier[txns] = identifier[catchup_rep] . identifier[txns] identifier[txns] =[ identifier[self] . identifier[_provider] . identifier[transform_txn_for_ledger] ( identifier[txn] ) keyword[for] identifier[s] , identifier[txn] keyword[in] identifier[txns_to_process] [: identifier[len] ( identifier[txns] )] keyword[if] identifier[str] ( identifier[s] ) keyword[in] identifier[txns] ] identifier[temp_tree] = identifier[self] . identifier[_ledger] . identifier[treeWithAppliedTxns] ( identifier[txns] ) identifier[proof] = identifier[catchup_rep] . identifier[consProof] identifier[final_size] = identifier[self] . identifier[_catchup_till] . identifier[final_size] identifier[final_hash] = identifier[self] . identifier[_catchup_till] . identifier[final_hash] keyword[try] : identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[self] , identifier[temp_tree] . identifier[tree_size] , identifier[final_size] , identifier[temp_tree] . identifier[root_hash] , identifier[final_hash] , identifier[proof] )) identifier[verified] = identifier[self] . identifier[_provider] . identifier[verifier] ( identifier[self] . identifier[_ledger_id] ). identifier[verify_tree_consistency] ( identifier[temp_tree] . identifier[tree_size] , identifier[final_size] , identifier[temp_tree] . identifier[root_hash] , identifier[Ledger] . identifier[strToHash] ( identifier[final_hash] ), [ identifier[Ledger] . identifier[strToHash] ( identifier[p] ) keyword[for] identifier[p] keyword[in] identifier[proof] ] ) keyword[except] identifier[Exception] keyword[as] identifier[ex] : identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[self] , identifier[catchup_rep] , identifier[ex] )) identifier[verified] = keyword[False] keyword[return] identifier[bool] ( identifier[verified] ), identifier[node_name] , identifier[len] ( identifier[txns] )
def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]: """ Transforms transactions for ledger! Returns: Whether catchup reply corresponding to seq_no Name of node from which txns came Number of transactions ready to be processed """ # TODO: Remove after stop passing seqNo here assert seq_no == txns_to_process[0][0] # Here seqNo has to be the seqNo of first transaction of # `catchupReplies` # Get the transactions in the catchup reply which has sequence # number `seqNo` (node_name, catchup_rep) = self._find_catchup_reply_for_seq_no(seq_no) txns = catchup_rep.txns # Add only those transaction in the temporary tree from the above # batch which are not present in the ledger # Integer keys being converted to strings when marshaled to JSON txns = [self._provider.transform_txn_for_ledger(txn) for (s, txn) in txns_to_process[:len(txns)] if str(s) in txns] # Creating a temporary tree which will be used to verify consistency # proof, by inserting transactions. Duplicating a merkle tree is not # expensive since we are using a compact merkle tree. temp_tree = self._ledger.treeWithAppliedTxns(txns) proof = catchup_rep.consProof final_size = self._catchup_till.final_size final_hash = self._catchup_till.final_hash try: logger.info('{} verifying proof for {}, {}, {}, {}, {}'.format(self, temp_tree.tree_size, final_size, temp_tree.root_hash, final_hash, proof)) verified = self._provider.verifier(self._ledger_id).verify_tree_consistency(temp_tree.tree_size, final_size, temp_tree.root_hash, Ledger.strToHash(final_hash), [Ledger.strToHash(p) for p in proof]) # depends on [control=['try'], data=[]] except Exception as ex: logger.info('{} could not verify catchup reply {} since {}'.format(self, catchup_rep, ex)) verified = False # depends on [control=['except'], data=['ex']] return (bool(verified), node_name, len(txns))
def RemoveActiveConnection(self, dev_path, active_connection_path): '''Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ''' self.SetDeviceDisconnected(dev_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') if active_connection_path not in active_connections: return active_connections.remove(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) self.object_manager_emit_removed(active_connection_path) self.RemoveObject(active_connection_path)
def function[RemoveActiveConnection, parameter[self, dev_path, active_connection_path]]: constant[Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ] call[name[self].SetDeviceDisconnected, parameter[name[dev_path]]] variable[NM] assign[=] call[name[dbusmock].get_object, parameter[name[MANAGER_OBJ]]] variable[active_connections] assign[=] call[name[NM].Get, parameter[name[MANAGER_IFACE], constant[ActiveConnections]]] if compare[name[active_connection_path] <ast.NotIn object at 0x7da2590d7190> name[active_connections]] begin[:] return[None] call[name[active_connections].remove, parameter[call[name[dbus].ObjectPath, parameter[name[active_connection_path]]]]] call[name[NM].SetProperty, parameter[name[MANAGER_OBJ], name[MANAGER_IFACE], constant[ActiveConnections], name[active_connections]]] call[name[self].object_manager_emit_removed, parameter[name[active_connection_path]]] call[name[self].RemoveObject, parameter[name[active_connection_path]]]
keyword[def] identifier[RemoveActiveConnection] ( identifier[self] , identifier[dev_path] , identifier[active_connection_path] ): literal[string] identifier[self] . identifier[SetDeviceDisconnected] ( identifier[dev_path] ) identifier[NM] = identifier[dbusmock] . identifier[get_object] ( identifier[MANAGER_OBJ] ) identifier[active_connections] = identifier[NM] . identifier[Get] ( identifier[MANAGER_IFACE] , literal[string] ) keyword[if] identifier[active_connection_path] keyword[not] keyword[in] identifier[active_connections] : keyword[return] identifier[active_connections] . identifier[remove] ( identifier[dbus] . identifier[ObjectPath] ( identifier[active_connection_path] )) identifier[NM] . identifier[SetProperty] ( identifier[MANAGER_OBJ] , identifier[MANAGER_IFACE] , literal[string] , identifier[active_connections] ) identifier[self] . identifier[object_manager_emit_removed] ( identifier[active_connection_path] ) identifier[self] . identifier[RemoveObject] ( identifier[active_connection_path] )
def RemoveActiveConnection(self, dev_path, active_connection_path): """Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. """ self.SetDeviceDisconnected(dev_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') if active_connection_path not in active_connections: return # depends on [control=['if'], data=[]] active_connections.remove(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) self.object_manager_emit_removed(active_connection_path) self.RemoveObject(active_connection_path)
def expect_keyword(parser, value): # type: (Parser, str) -> Token """If the next token is a keyword with the given value, return that token after advancing the parser. Otherwise, do not change the parser state and return False.""" token = parser.token if token.kind == TokenKind.NAME and token.value == value: advance(parser) return token raise GraphQLSyntaxError( parser.source, token.start, u'Expected "{}", found {}'.format(value, get_token_desc(token)), )
def function[expect_keyword, parameter[parser, value]]: constant[If the next token is a keyword with the given value, return that token after advancing the parser. Otherwise, do not change the parser state and return False.] variable[token] assign[=] name[parser].token if <ast.BoolOp object at 0x7da2041db070> begin[:] call[name[advance], parameter[name[parser]]] return[name[token]] <ast.Raise object at 0x7da2041d8760>
keyword[def] identifier[expect_keyword] ( identifier[parser] , identifier[value] ): literal[string] identifier[token] = identifier[parser] . identifier[token] keyword[if] identifier[token] . identifier[kind] == identifier[TokenKind] . identifier[NAME] keyword[and] identifier[token] . identifier[value] == identifier[value] : identifier[advance] ( identifier[parser] ) keyword[return] identifier[token] keyword[raise] identifier[GraphQLSyntaxError] ( identifier[parser] . identifier[source] , identifier[token] . identifier[start] , literal[string] . identifier[format] ( identifier[value] , identifier[get_token_desc] ( identifier[token] )), )
def expect_keyword(parser, value): # type: (Parser, str) -> Token 'If the next token is a keyword with the given value, return that\n token after advancing the parser. Otherwise, do not change the parser\n state and return False.' token = parser.token if token.kind == TokenKind.NAME and token.value == value: advance(parser) return token # depends on [control=['if'], data=[]] raise GraphQLSyntaxError(parser.source, token.start, u'Expected "{}", found {}'.format(value, get_token_desc(token)))
def _replace_link_brackets(msg_body): """ Normalize links i.e. replace '<', '>' wrapping the link with some symbols so that '>' closing the link couldn't be mistakenly taken for quotation marker. Converts msg_body into a unicode """ if isinstance(msg_body, bytes): msg_body = msg_body.decode('utf8') def link_wrapper(link): newline_index = msg_body[:link.start()].rfind("\n") if msg_body[newline_index + 1] == ">": return link.group() else: return "@@%s@@" % link.group(1) msg_body = re.sub(RE_LINK, link_wrapper, msg_body) return msg_body
def function[_replace_link_brackets, parameter[msg_body]]: constant[ Normalize links i.e. replace '<', '>' wrapping the link with some symbols so that '>' closing the link couldn't be mistakenly taken for quotation marker. Converts msg_body into a unicode ] if call[name[isinstance], parameter[name[msg_body], name[bytes]]] begin[:] variable[msg_body] assign[=] call[name[msg_body].decode, parameter[constant[utf8]]] def function[link_wrapper, parameter[link]]: variable[newline_index] assign[=] call[call[name[msg_body]][<ast.Slice object at 0x7da1b1ecc6a0>].rfind, parameter[constant[ ]]] if compare[call[name[msg_body]][binary_operation[name[newline_index] + constant[1]]] equal[==] constant[>]] begin[:] return[call[name[link].group, parameter[]]] variable[msg_body] assign[=] call[name[re].sub, parameter[name[RE_LINK], name[link_wrapper], name[msg_body]]] return[name[msg_body]]
keyword[def] identifier[_replace_link_brackets] ( identifier[msg_body] ): literal[string] keyword[if] identifier[isinstance] ( identifier[msg_body] , identifier[bytes] ): identifier[msg_body] = identifier[msg_body] . identifier[decode] ( literal[string] ) keyword[def] identifier[link_wrapper] ( identifier[link] ): identifier[newline_index] = identifier[msg_body] [: identifier[link] . identifier[start] ()]. identifier[rfind] ( literal[string] ) keyword[if] identifier[msg_body] [ identifier[newline_index] + literal[int] ]== literal[string] : keyword[return] identifier[link] . identifier[group] () keyword[else] : keyword[return] literal[string] % identifier[link] . identifier[group] ( literal[int] ) identifier[msg_body] = identifier[re] . identifier[sub] ( identifier[RE_LINK] , identifier[link_wrapper] , identifier[msg_body] ) keyword[return] identifier[msg_body]
def _replace_link_brackets(msg_body): """ Normalize links i.e. replace '<', '>' wrapping the link with some symbols so that '>' closing the link couldn't be mistakenly taken for quotation marker. Converts msg_body into a unicode """ if isinstance(msg_body, bytes): msg_body = msg_body.decode('utf8') # depends on [control=['if'], data=[]] def link_wrapper(link): newline_index = msg_body[:link.start()].rfind('\n') if msg_body[newline_index + 1] == '>': return link.group() # depends on [control=['if'], data=[]] else: return '@@%s@@' % link.group(1) msg_body = re.sub(RE_LINK, link_wrapper, msg_body) return msg_body
def sym_gen(batch_size, sentences_size, num_embed, vocabulary_size, num_label=2, filter_list=None, num_filter=100, dropout=0.0, pre_trained_word2vec=False): """Generate network symbol Parameters ---------- batch_size: int sentences_size: int num_embed: int vocabulary_size: int num_label: int filter_list: list num_filter: int dropout: int pre_trained_word2vec: boolean identify the pre-trained layers or not Returns ---------- sm: symbol data: list of str data names softmax_label: list of str label names """ input_x = mx.sym.Variable('data') input_y = mx.sym.Variable('softmax_label') # embedding layer if not pre_trained_word2vec: embed_layer = mx.sym.Embedding(data=input_x, input_dim=vocabulary_size, output_dim=num_embed, name='vocab_embed') conv_input = mx.sym.Reshape(data=embed_layer, target_shape=(batch_size, 1, sentences_size, num_embed)) else: conv_input = input_x # create convolution + (max) pooling layer for each filter operation pooled_outputs = [] for i, filter_size in enumerate(filter_list): convi = mx.sym.Convolution(data=conv_input, kernel=(filter_size, num_embed), num_filter=num_filter) relui = mx.sym.Activation(data=convi, act_type='relu') pooli = mx.sym.Pooling(data=relui, pool_type='max', kernel=(sentences_size - filter_size + 1, 1), stride=(1, 1)) pooled_outputs.append(pooli) # combine all pooled outputs total_filters = num_filter * len(filter_list) concat = mx.sym.Concat(*pooled_outputs, dim=1) h_pool = mx.sym.Reshape(data=concat, target_shape=(batch_size, total_filters)) # dropout layer if dropout > 0.0: h_drop = mx.sym.Dropout(data=h_pool, p=dropout) else: h_drop = h_pool # fully connected cls_weight = mx.sym.Variable('cls_weight') cls_bias = mx.sym.Variable('cls_bias') fc = mx.sym.FullyConnected(data=h_drop, weight=cls_weight, bias=cls_bias, num_hidden=num_label) # softmax output sm = mx.sym.SoftmaxOutput(data=fc, label=input_y, name='softmax') return sm, ('data',), ('softmax_label',)
def function[sym_gen, parameter[batch_size, sentences_size, num_embed, vocabulary_size, num_label, filter_list, num_filter, dropout, pre_trained_word2vec]]: constant[Generate network symbol Parameters ---------- batch_size: int sentences_size: int num_embed: int vocabulary_size: int num_label: int filter_list: list num_filter: int dropout: int pre_trained_word2vec: boolean identify the pre-trained layers or not Returns ---------- sm: symbol data: list of str data names softmax_label: list of str label names ] variable[input_x] assign[=] call[name[mx].sym.Variable, parameter[constant[data]]] variable[input_y] assign[=] call[name[mx].sym.Variable, parameter[constant[softmax_label]]] if <ast.UnaryOp object at 0x7da1b2013010> begin[:] variable[embed_layer] assign[=] call[name[mx].sym.Embedding, parameter[]] variable[conv_input] assign[=] call[name[mx].sym.Reshape, parameter[]] variable[pooled_outputs] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b2013f40>, <ast.Name object at 0x7da1b2012e90>]]] in starred[call[name[enumerate], parameter[name[filter_list]]]] begin[:] variable[convi] assign[=] call[name[mx].sym.Convolution, parameter[]] variable[relui] assign[=] call[name[mx].sym.Activation, parameter[]] variable[pooli] assign[=] call[name[mx].sym.Pooling, parameter[]] call[name[pooled_outputs].append, parameter[name[pooli]]] variable[total_filters] assign[=] binary_operation[name[num_filter] * call[name[len], parameter[name[filter_list]]]] variable[concat] assign[=] call[name[mx].sym.Concat, parameter[<ast.Starred object at 0x7da1b20fa980>]] variable[h_pool] assign[=] call[name[mx].sym.Reshape, parameter[]] if compare[name[dropout] greater[>] constant[0.0]] begin[:] variable[h_drop] assign[=] call[name[mx].sym.Dropout, parameter[]] variable[cls_weight] assign[=] call[name[mx].sym.Variable, parameter[constant[cls_weight]]] variable[cls_bias] assign[=] call[name[mx].sym.Variable, parameter[constant[cls_bias]]] variable[fc] assign[=] call[name[mx].sym.FullyConnected, parameter[]] variable[sm] assign[=] call[name[mx].sym.SoftmaxOutput, parameter[]] return[tuple[[<ast.Name object at 0x7da1b20f93f0>, <ast.Tuple object at 0x7da1b20f99f0>, <ast.Tuple object at 0x7da1b20f9990>]]]
keyword[def] identifier[sym_gen] ( identifier[batch_size] , identifier[sentences_size] , identifier[num_embed] , identifier[vocabulary_size] , identifier[num_label] = literal[int] , identifier[filter_list] = keyword[None] , identifier[num_filter] = literal[int] , identifier[dropout] = literal[int] , identifier[pre_trained_word2vec] = keyword[False] ): literal[string] identifier[input_x] = identifier[mx] . identifier[sym] . identifier[Variable] ( literal[string] ) identifier[input_y] = identifier[mx] . identifier[sym] . identifier[Variable] ( literal[string] ) keyword[if] keyword[not] identifier[pre_trained_word2vec] : identifier[embed_layer] = identifier[mx] . identifier[sym] . identifier[Embedding] ( identifier[data] = identifier[input_x] , identifier[input_dim] = identifier[vocabulary_size] , identifier[output_dim] = identifier[num_embed] , identifier[name] = literal[string] ) identifier[conv_input] = identifier[mx] . identifier[sym] . identifier[Reshape] ( identifier[data] = identifier[embed_layer] , identifier[target_shape] =( identifier[batch_size] , literal[int] , identifier[sentences_size] , identifier[num_embed] )) keyword[else] : identifier[conv_input] = identifier[input_x] identifier[pooled_outputs] =[] keyword[for] identifier[i] , identifier[filter_size] keyword[in] identifier[enumerate] ( identifier[filter_list] ): identifier[convi] = identifier[mx] . identifier[sym] . identifier[Convolution] ( identifier[data] = identifier[conv_input] , identifier[kernel] =( identifier[filter_size] , identifier[num_embed] ), identifier[num_filter] = identifier[num_filter] ) identifier[relui] = identifier[mx] . identifier[sym] . identifier[Activation] ( identifier[data] = identifier[convi] , identifier[act_type] = literal[string] ) identifier[pooli] = identifier[mx] . identifier[sym] . identifier[Pooling] ( identifier[data] = identifier[relui] , identifier[pool_type] = literal[string] , identifier[kernel] =( identifier[sentences_size] - identifier[filter_size] + literal[int] , literal[int] ), identifier[stride] =( literal[int] , literal[int] )) identifier[pooled_outputs] . identifier[append] ( identifier[pooli] ) identifier[total_filters] = identifier[num_filter] * identifier[len] ( identifier[filter_list] ) identifier[concat] = identifier[mx] . identifier[sym] . identifier[Concat] (* identifier[pooled_outputs] , identifier[dim] = literal[int] ) identifier[h_pool] = identifier[mx] . identifier[sym] . identifier[Reshape] ( identifier[data] = identifier[concat] , identifier[target_shape] =( identifier[batch_size] , identifier[total_filters] )) keyword[if] identifier[dropout] > literal[int] : identifier[h_drop] = identifier[mx] . identifier[sym] . identifier[Dropout] ( identifier[data] = identifier[h_pool] , identifier[p] = identifier[dropout] ) keyword[else] : identifier[h_drop] = identifier[h_pool] identifier[cls_weight] = identifier[mx] . identifier[sym] . identifier[Variable] ( literal[string] ) identifier[cls_bias] = identifier[mx] . identifier[sym] . identifier[Variable] ( literal[string] ) identifier[fc] = identifier[mx] . identifier[sym] . identifier[FullyConnected] ( identifier[data] = identifier[h_drop] , identifier[weight] = identifier[cls_weight] , identifier[bias] = identifier[cls_bias] , identifier[num_hidden] = identifier[num_label] ) identifier[sm] = identifier[mx] . identifier[sym] . identifier[SoftmaxOutput] ( identifier[data] = identifier[fc] , identifier[label] = identifier[input_y] , identifier[name] = literal[string] ) keyword[return] identifier[sm] ,( literal[string] ,),( literal[string] ,)
def sym_gen(batch_size, sentences_size, num_embed, vocabulary_size, num_label=2, filter_list=None, num_filter=100, dropout=0.0, pre_trained_word2vec=False): """Generate network symbol Parameters ---------- batch_size: int sentences_size: int num_embed: int vocabulary_size: int num_label: int filter_list: list num_filter: int dropout: int pre_trained_word2vec: boolean identify the pre-trained layers or not Returns ---------- sm: symbol data: list of str data names softmax_label: list of str label names """ input_x = mx.sym.Variable('data') input_y = mx.sym.Variable('softmax_label') # embedding layer if not pre_trained_word2vec: embed_layer = mx.sym.Embedding(data=input_x, input_dim=vocabulary_size, output_dim=num_embed, name='vocab_embed') conv_input = mx.sym.Reshape(data=embed_layer, target_shape=(batch_size, 1, sentences_size, num_embed)) # depends on [control=['if'], data=[]] else: conv_input = input_x # create convolution + (max) pooling layer for each filter operation pooled_outputs = [] for (i, filter_size) in enumerate(filter_list): convi = mx.sym.Convolution(data=conv_input, kernel=(filter_size, num_embed), num_filter=num_filter) relui = mx.sym.Activation(data=convi, act_type='relu') pooli = mx.sym.Pooling(data=relui, pool_type='max', kernel=(sentences_size - filter_size + 1, 1), stride=(1, 1)) pooled_outputs.append(pooli) # depends on [control=['for'], data=[]] # combine all pooled outputs total_filters = num_filter * len(filter_list) concat = mx.sym.Concat(*pooled_outputs, dim=1) h_pool = mx.sym.Reshape(data=concat, target_shape=(batch_size, total_filters)) # dropout layer if dropout > 0.0: h_drop = mx.sym.Dropout(data=h_pool, p=dropout) # depends on [control=['if'], data=['dropout']] else: h_drop = h_pool # fully connected cls_weight = mx.sym.Variable('cls_weight') cls_bias = mx.sym.Variable('cls_bias') fc = mx.sym.FullyConnected(data=h_drop, weight=cls_weight, bias=cls_bias, num_hidden=num_label) # softmax output sm = mx.sym.SoftmaxOutput(data=fc, label=input_y, name='softmax') return (sm, ('data',), ('softmax_label',))
def oidc_to_user_data(payload): """ Map OIDC claims to Django user fields. """ payload = payload.copy() field_map = { 'given_name': 'first_name', 'family_name': 'last_name', 'email': 'email', } ret = {} for token_attr, user_attr in field_map.items(): if token_attr not in payload: continue ret[user_attr] = payload.pop(token_attr) ret.update(payload) return ret
def function[oidc_to_user_data, parameter[payload]]: constant[ Map OIDC claims to Django user fields. ] variable[payload] assign[=] call[name[payload].copy, parameter[]] variable[field_map] assign[=] dictionary[[<ast.Constant object at 0x7da1b0490d60>, <ast.Constant object at 0x7da1b0493e20>, <ast.Constant object at 0x7da1b04909d0>], [<ast.Constant object at 0x7da1b04903d0>, <ast.Constant object at 0x7da1b0492ce0>, <ast.Constant object at 0x7da1b0490910>]] variable[ret] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da1b0493310>, <ast.Name object at 0x7da1b0493a00>]]] in starred[call[name[field_map].items, parameter[]]] begin[:] if compare[name[token_attr] <ast.NotIn object at 0x7da2590d7190> name[payload]] begin[:] continue call[name[ret]][name[user_attr]] assign[=] call[name[payload].pop, parameter[name[token_attr]]] call[name[ret].update, parameter[name[payload]]] return[name[ret]]
keyword[def] identifier[oidc_to_user_data] ( identifier[payload] ): literal[string] identifier[payload] = identifier[payload] . identifier[copy] () identifier[field_map] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , } identifier[ret] ={} keyword[for] identifier[token_attr] , identifier[user_attr] keyword[in] identifier[field_map] . identifier[items] (): keyword[if] identifier[token_attr] keyword[not] keyword[in] identifier[payload] : keyword[continue] identifier[ret] [ identifier[user_attr] ]= identifier[payload] . identifier[pop] ( identifier[token_attr] ) identifier[ret] . identifier[update] ( identifier[payload] ) keyword[return] identifier[ret]
def oidc_to_user_data(payload): """ Map OIDC claims to Django user fields. """ payload = payload.copy() field_map = {'given_name': 'first_name', 'family_name': 'last_name', 'email': 'email'} ret = {} for (token_attr, user_attr) in field_map.items(): if token_attr not in payload: continue # depends on [control=['if'], data=[]] ret[user_attr] = payload.pop(token_attr) # depends on [control=['for'], data=[]] ret.update(payload) return ret
def process_sub_shrink(ref, alt_str): """Process substution where the string shrink""" if len(ref) == 0: raise exceptions.InvalidRecordException("Invalid VCF, empty REF") elif len(ref) == 1: if ref[0] == alt_str[0]: return record.Substitution(record.INS, alt_str) else: return record.Substitution(record.INDEL, alt_str) else: return record.Substitution(record.INDEL, alt_str)
def function[process_sub_shrink, parameter[ref, alt_str]]: constant[Process substution where the string shrink] if compare[call[name[len], parameter[name[ref]]] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da207f994b0>
keyword[def] identifier[process_sub_shrink] ( identifier[ref] , identifier[alt_str] ): literal[string] keyword[if] identifier[len] ( identifier[ref] )== literal[int] : keyword[raise] identifier[exceptions] . identifier[InvalidRecordException] ( literal[string] ) keyword[elif] identifier[len] ( identifier[ref] )== literal[int] : keyword[if] identifier[ref] [ literal[int] ]== identifier[alt_str] [ literal[int] ]: keyword[return] identifier[record] . identifier[Substitution] ( identifier[record] . identifier[INS] , identifier[alt_str] ) keyword[else] : keyword[return] identifier[record] . identifier[Substitution] ( identifier[record] . identifier[INDEL] , identifier[alt_str] ) keyword[else] : keyword[return] identifier[record] . identifier[Substitution] ( identifier[record] . identifier[INDEL] , identifier[alt_str] )
def process_sub_shrink(ref, alt_str): """Process substution where the string shrink""" if len(ref) == 0: raise exceptions.InvalidRecordException('Invalid VCF, empty REF') # depends on [control=['if'], data=[]] elif len(ref) == 1: if ref[0] == alt_str[0]: return record.Substitution(record.INS, alt_str) # depends on [control=['if'], data=[]] else: return record.Substitution(record.INDEL, alt_str) # depends on [control=['if'], data=[]] else: return record.Substitution(record.INDEL, alt_str)
def get_different_page(self, request, page): """ Returns a url that preserves the current querystring while changing the page requested to `page`. """ if page: qs = request.GET.copy() qs['page'] = page return "%s?%s" % (request.path_info, qs.urlencode()) return None
def function[get_different_page, parameter[self, request, page]]: constant[ Returns a url that preserves the current querystring while changing the page requested to `page`. ] if name[page] begin[:] variable[qs] assign[=] call[name[request].GET.copy, parameter[]] call[name[qs]][constant[page]] assign[=] name[page] return[binary_operation[constant[%s?%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18fe92650>, <ast.Call object at 0x7da18fe92c20>]]]] return[constant[None]]
keyword[def] identifier[get_different_page] ( identifier[self] , identifier[request] , identifier[page] ): literal[string] keyword[if] identifier[page] : identifier[qs] = identifier[request] . identifier[GET] . identifier[copy] () identifier[qs] [ literal[string] ]= identifier[page] keyword[return] literal[string] %( identifier[request] . identifier[path_info] , identifier[qs] . identifier[urlencode] ()) keyword[return] keyword[None]
def get_different_page(self, request, page): """ Returns a url that preserves the current querystring while changing the page requested to `page`. """ if page: qs = request.GET.copy() qs['page'] = page return '%s?%s' % (request.path_info, qs.urlencode()) # depends on [control=['if'], data=[]] return None
def find_connected_sites(bonds, am, flatten=True, logic='or'): r""" Given an adjacency matrix, finds which sites are connected to the input bonds. Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). flatten : boolean (default is ``True``) Indicates whether the returned result is a compressed array of all neighbors, or a list of lists with each sub-list containing the neighbors for each input site. Note that an *unflattened* list might be slow to generate since it is a Python ``list`` rather than a Numpy array. logic : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input bonds. This is also known as the 'union' in set theory or (sometimes) 'any' in boolean logic. Both keywords are accepted and treated as 'or'. **'xor'** : Only neighbors of one and only one input bond. This is useful for finding the sites that are not shared by any of the input bonds. 'exclusive_or' is also accepted. **'xnor'** : Neighbors that are shared by two or more input bonds. This is equivalent to finding all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. 'nxor' is also accepted. **'and'** : Only neighbors shared by all input bonds. This is also known as 'intersection' in set theory and (somtimes) as 'all' in boolean logic. Both keywords are accepted and treated as 'and'. Returns ------- An array containing the connected sites, filtered by the given logic. If ``flatten`` is ``False`` then the result is a list of lists containing the neighbors of each given input bond. In this latter case, sites that have been removed by the given logic are indicated by ``nans``, thus the array is of type ``float`` and is not suitable for indexing. See Also -------- find_complement """ if am.format != 'coo': raise Exception('Adjacency matrix must be in COO format') bonds = sp.array(bonds, ndmin=1) if len(bonds) == 0: return [] neighbors = sp.hstack((am.row[bonds], am.col[bonds])).astype(sp.int64) if neighbors.size: n_sites = sp.amax(neighbors) if logic in ['or', 'union', 'any']: neighbors = sp.unique(neighbors) elif logic in ['xor', 'exclusive_or']: neighbors = sp.unique(sp.where(sp.bincount(neighbors) == 1)[0]) elif logic in ['xnor']: neighbors = sp.unique(sp.where(sp.bincount(neighbors) > 1)[0]) elif logic in ['and', 'all', 'intersection']: temp = sp.vstack((am.row[bonds], am.col[bonds])).T.tolist() temp = [set(pair) for pair in temp] neighbors = temp[0] [neighbors.intersection_update(pair) for pair in temp[1:]] neighbors = sp.array(list(neighbors), dtype=sp.int64, ndmin=1) else: raise Exception('Specified logic is not implemented') if flatten is False: if neighbors.size: mask = sp.zeros(shape=n_sites+1, dtype=bool) mask[neighbors] = True temp = sp.hstack((am.row[bonds], am.col[bonds])).astype(sp.int64) temp[~mask[temp]] = -1 inds = sp.where(temp == -1)[0] if len(inds): temp = temp.astype(float) temp[inds] = sp.nan temp = sp.reshape(a=temp, newshape=[len(bonds), 2], order='F') neighbors = temp else: neighbors = [sp.array([], dtype=sp.int64) for i in range(len(bonds))] return neighbors
def function[find_connected_sites, parameter[bonds, am, flatten, logic]]: constant[ Given an adjacency matrix, finds which sites are connected to the input bonds. Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). flatten : boolean (default is ``True``) Indicates whether the returned result is a compressed array of all neighbors, or a list of lists with each sub-list containing the neighbors for each input site. Note that an *unflattened* list might be slow to generate since it is a Python ``list`` rather than a Numpy array. logic : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input bonds. This is also known as the 'union' in set theory or (sometimes) 'any' in boolean logic. Both keywords are accepted and treated as 'or'. **'xor'** : Only neighbors of one and only one input bond. This is useful for finding the sites that are not shared by any of the input bonds. 'exclusive_or' is also accepted. **'xnor'** : Neighbors that are shared by two or more input bonds. This is equivalent to finding all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. 'nxor' is also accepted. **'and'** : Only neighbors shared by all input bonds. This is also known as 'intersection' in set theory and (somtimes) as 'all' in boolean logic. Both keywords are accepted and treated as 'and'. Returns ------- An array containing the connected sites, filtered by the given logic. If ``flatten`` is ``False`` then the result is a list of lists containing the neighbors of each given input bond. In this latter case, sites that have been removed by the given logic are indicated by ``nans``, thus the array is of type ``float`` and is not suitable for indexing. See Also -------- find_complement ] if compare[name[am].format not_equal[!=] constant[coo]] begin[:] <ast.Raise object at 0x7da18fe91090> variable[bonds] assign[=] call[name[sp].array, parameter[name[bonds]]] if compare[call[name[len], parameter[name[bonds]]] equal[==] constant[0]] begin[:] return[list[[]]] variable[neighbors] assign[=] call[call[name[sp].hstack, parameter[tuple[[<ast.Subscript object at 0x7da18fe92c80>, <ast.Subscript object at 0x7da18eb54850>]]]].astype, parameter[name[sp].int64]] if name[neighbors].size begin[:] variable[n_sites] assign[=] call[name[sp].amax, parameter[name[neighbors]]] if compare[name[logic] in list[[<ast.Constant object at 0x7da18eb56950>, <ast.Constant object at 0x7da18eb56b00>, <ast.Constant object at 0x7da18eb57dc0>]]] begin[:] variable[neighbors] assign[=] call[name[sp].unique, parameter[name[neighbors]]] if compare[name[flatten] is constant[False]] begin[:] if name[neighbors].size begin[:] variable[mask] assign[=] call[name[sp].zeros, parameter[]] call[name[mask]][name[neighbors]] assign[=] constant[True] variable[temp] assign[=] call[call[name[sp].hstack, parameter[tuple[[<ast.Subscript object at 0x7da204962a40>, <ast.Subscript object at 0x7da2049617b0>]]]].astype, parameter[name[sp].int64]] call[name[temp]][<ast.UnaryOp object at 0x7da2049600d0>] assign[=] <ast.UnaryOp object at 0x7da204960490> variable[inds] assign[=] call[call[name[sp].where, parameter[compare[name[temp] equal[==] <ast.UnaryOp object at 0x7da18f58d810>]]]][constant[0]] if call[name[len], parameter[name[inds]]] begin[:] variable[temp] assign[=] call[name[temp].astype, parameter[name[float]]] call[name[temp]][name[inds]] assign[=] name[sp].nan variable[temp] assign[=] call[name[sp].reshape, parameter[]] variable[neighbors] assign[=] name[temp] return[name[neighbors]]
keyword[def] identifier[find_connected_sites] ( identifier[bonds] , identifier[am] , identifier[flatten] = keyword[True] , identifier[logic] = literal[string] ): literal[string] keyword[if] identifier[am] . identifier[format] != literal[string] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[bonds] = identifier[sp] . identifier[array] ( identifier[bonds] , identifier[ndmin] = literal[int] ) keyword[if] identifier[len] ( identifier[bonds] )== literal[int] : keyword[return] [] identifier[neighbors] = identifier[sp] . identifier[hstack] (( identifier[am] . identifier[row] [ identifier[bonds] ], identifier[am] . identifier[col] [ identifier[bonds] ])). identifier[astype] ( identifier[sp] . identifier[int64] ) keyword[if] identifier[neighbors] . identifier[size] : identifier[n_sites] = identifier[sp] . identifier[amax] ( identifier[neighbors] ) keyword[if] identifier[logic] keyword[in] [ literal[string] , literal[string] , literal[string] ]: identifier[neighbors] = identifier[sp] . identifier[unique] ( identifier[neighbors] ) keyword[elif] identifier[logic] keyword[in] [ literal[string] , literal[string] ]: identifier[neighbors] = identifier[sp] . identifier[unique] ( identifier[sp] . identifier[where] ( identifier[sp] . identifier[bincount] ( identifier[neighbors] )== literal[int] )[ literal[int] ]) keyword[elif] identifier[logic] keyword[in] [ literal[string] ]: identifier[neighbors] = identifier[sp] . identifier[unique] ( identifier[sp] . identifier[where] ( identifier[sp] . identifier[bincount] ( identifier[neighbors] )> literal[int] )[ literal[int] ]) keyword[elif] identifier[logic] keyword[in] [ literal[string] , literal[string] , literal[string] ]: identifier[temp] = identifier[sp] . identifier[vstack] (( identifier[am] . identifier[row] [ identifier[bonds] ], identifier[am] . identifier[col] [ identifier[bonds] ])). identifier[T] . identifier[tolist] () identifier[temp] =[ identifier[set] ( identifier[pair] ) keyword[for] identifier[pair] keyword[in] identifier[temp] ] identifier[neighbors] = identifier[temp] [ literal[int] ] [ identifier[neighbors] . identifier[intersection_update] ( identifier[pair] ) keyword[for] identifier[pair] keyword[in] identifier[temp] [ literal[int] :]] identifier[neighbors] = identifier[sp] . identifier[array] ( identifier[list] ( identifier[neighbors] ), identifier[dtype] = identifier[sp] . identifier[int64] , identifier[ndmin] = literal[int] ) keyword[else] : keyword[raise] identifier[Exception] ( literal[string] ) keyword[if] identifier[flatten] keyword[is] keyword[False] : keyword[if] identifier[neighbors] . identifier[size] : identifier[mask] = identifier[sp] . identifier[zeros] ( identifier[shape] = identifier[n_sites] + literal[int] , identifier[dtype] = identifier[bool] ) identifier[mask] [ identifier[neighbors] ]= keyword[True] identifier[temp] = identifier[sp] . identifier[hstack] (( identifier[am] . identifier[row] [ identifier[bonds] ], identifier[am] . identifier[col] [ identifier[bonds] ])). identifier[astype] ( identifier[sp] . identifier[int64] ) identifier[temp] [~ identifier[mask] [ identifier[temp] ]]=- literal[int] identifier[inds] = identifier[sp] . identifier[where] ( identifier[temp] ==- literal[int] )[ literal[int] ] keyword[if] identifier[len] ( identifier[inds] ): identifier[temp] = identifier[temp] . identifier[astype] ( identifier[float] ) identifier[temp] [ identifier[inds] ]= identifier[sp] . identifier[nan] identifier[temp] = identifier[sp] . identifier[reshape] ( identifier[a] = identifier[temp] , identifier[newshape] =[ identifier[len] ( identifier[bonds] ), literal[int] ], identifier[order] = literal[string] ) identifier[neighbors] = identifier[temp] keyword[else] : identifier[neighbors] =[ identifier[sp] . identifier[array] ([], identifier[dtype] = identifier[sp] . identifier[int64] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[bonds] ))] keyword[return] identifier[neighbors]
def find_connected_sites(bonds, am, flatten=True, logic='or'): """ Given an adjacency matrix, finds which sites are connected to the input bonds. Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). flatten : boolean (default is ``True``) Indicates whether the returned result is a compressed array of all neighbors, or a list of lists with each sub-list containing the neighbors for each input site. Note that an *unflattened* list might be slow to generate since it is a Python ``list`` rather than a Numpy array. logic : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input bonds. This is also known as the 'union' in set theory or (sometimes) 'any' in boolean logic. Both keywords are accepted and treated as 'or'. **'xor'** : Only neighbors of one and only one input bond. This is useful for finding the sites that are not shared by any of the input bonds. 'exclusive_or' is also accepted. **'xnor'** : Neighbors that are shared by two or more input bonds. This is equivalent to finding all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. 'nxor' is also accepted. **'and'** : Only neighbors shared by all input bonds. This is also known as 'intersection' in set theory and (somtimes) as 'all' in boolean logic. Both keywords are accepted and treated as 'and'. Returns ------- An array containing the connected sites, filtered by the given logic. If ``flatten`` is ``False`` then the result is a list of lists containing the neighbors of each given input bond. In this latter case, sites that have been removed by the given logic are indicated by ``nans``, thus the array is of type ``float`` and is not suitable for indexing. See Also -------- find_complement """ if am.format != 'coo': raise Exception('Adjacency matrix must be in COO format') # depends on [control=['if'], data=[]] bonds = sp.array(bonds, ndmin=1) if len(bonds) == 0: return [] # depends on [control=['if'], data=[]] neighbors = sp.hstack((am.row[bonds], am.col[bonds])).astype(sp.int64) if neighbors.size: n_sites = sp.amax(neighbors) # depends on [control=['if'], data=[]] if logic in ['or', 'union', 'any']: neighbors = sp.unique(neighbors) # depends on [control=['if'], data=[]] elif logic in ['xor', 'exclusive_or']: neighbors = sp.unique(sp.where(sp.bincount(neighbors) == 1)[0]) # depends on [control=['if'], data=[]] elif logic in ['xnor']: neighbors = sp.unique(sp.where(sp.bincount(neighbors) > 1)[0]) # depends on [control=['if'], data=[]] elif logic in ['and', 'all', 'intersection']: temp = sp.vstack((am.row[bonds], am.col[bonds])).T.tolist() temp = [set(pair) for pair in temp] neighbors = temp[0] [neighbors.intersection_update(pair) for pair in temp[1:]] neighbors = sp.array(list(neighbors), dtype=sp.int64, ndmin=1) # depends on [control=['if'], data=[]] else: raise Exception('Specified logic is not implemented') if flatten is False: if neighbors.size: mask = sp.zeros(shape=n_sites + 1, dtype=bool) mask[neighbors] = True temp = sp.hstack((am.row[bonds], am.col[bonds])).astype(sp.int64) temp[~mask[temp]] = -1 inds = sp.where(temp == -1)[0] if len(inds): temp = temp.astype(float) temp[inds] = sp.nan # depends on [control=['if'], data=[]] temp = sp.reshape(a=temp, newshape=[len(bonds), 2], order='F') neighbors = temp # depends on [control=['if'], data=[]] else: neighbors = [sp.array([], dtype=sp.int64) for i in range(len(bonds))] # depends on [control=['if'], data=[]] return neighbors
def bqsr_table(data): """Generate recalibration tables as inputs to BQSR. """ in_file = dd.get_align_bam(data) out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: assoc_files = dd.get_variation_resources(data) known = "-k %s" % (assoc_files.get("dbsnp")) if "dbsnp" in assoc_files else "" license = license_export(data) cores = dd.get_num_cores(data) ref_file = dd.get_ref_file(data) cmd = ("{license}sentieon driver -t {cores} -r {ref_file} " "-i {in_file} --algo QualCal {known} {tx_out_file}") do.run(cmd.format(**locals()), "Sentieon QualCal generate table") return out_file
def function[bqsr_table, parameter[data]]: constant[Generate recalibration tables as inputs to BQSR. ] variable[in_file] assign[=] call[name[dd].get_align_bam, parameter[name[data]]] variable[out_file] assign[=] binary_operation[constant[%s-recal-table.txt] <ast.Mod object at 0x7da2590d6920> call[call[name[utils].splitext_plus, parameter[name[in_file]]]][constant[0]]] if <ast.UnaryOp object at 0x7da1b17a50f0> begin[:] with call[name[file_transaction], parameter[name[data], name[out_file]]] begin[:] variable[assoc_files] assign[=] call[name[dd].get_variation_resources, parameter[name[data]]] variable[known] assign[=] <ast.IfExp object at 0x7da1b17a4fa0> variable[license] assign[=] call[name[license_export], parameter[name[data]]] variable[cores] assign[=] call[name[dd].get_num_cores, parameter[name[data]]] variable[ref_file] assign[=] call[name[dd].get_ref_file, parameter[name[data]]] variable[cmd] assign[=] constant[{license}sentieon driver -t {cores} -r {ref_file} -i {in_file} --algo QualCal {known} {tx_out_file}] call[name[do].run, parameter[call[name[cmd].format, parameter[]], constant[Sentieon QualCal generate table]]] return[name[out_file]]
keyword[def] identifier[bqsr_table] ( identifier[data] ): literal[string] identifier[in_file] = identifier[dd] . identifier[get_align_bam] ( identifier[data] ) identifier[out_file] = literal[string] % identifier[utils] . identifier[splitext_plus] ( identifier[in_file] )[ literal[int] ] keyword[if] keyword[not] identifier[utils] . identifier[file_uptodate] ( identifier[out_file] , identifier[in_file] ): keyword[with] identifier[file_transaction] ( identifier[data] , identifier[out_file] ) keyword[as] identifier[tx_out_file] : identifier[assoc_files] = identifier[dd] . identifier[get_variation_resources] ( identifier[data] ) identifier[known] = literal[string] %( identifier[assoc_files] . identifier[get] ( literal[string] )) keyword[if] literal[string] keyword[in] identifier[assoc_files] keyword[else] literal[string] identifier[license] = identifier[license_export] ( identifier[data] ) identifier[cores] = identifier[dd] . identifier[get_num_cores] ( identifier[data] ) identifier[ref_file] = identifier[dd] . identifier[get_ref_file] ( identifier[data] ) identifier[cmd] =( literal[string] literal[string] ) identifier[do] . identifier[run] ( identifier[cmd] . identifier[format] (** identifier[locals] ()), literal[string] ) keyword[return] identifier[out_file]
def bqsr_table(data): """Generate recalibration tables as inputs to BQSR. """ in_file = dd.get_align_bam(data) out_file = '%s-recal-table.txt' % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: assoc_files = dd.get_variation_resources(data) known = '-k %s' % assoc_files.get('dbsnp') if 'dbsnp' in assoc_files else '' license = license_export(data) cores = dd.get_num_cores(data) ref_file = dd.get_ref_file(data) cmd = '{license}sentieon driver -t {cores} -r {ref_file} -i {in_file} --algo QualCal {known} {tx_out_file}' do.run(cmd.format(**locals()), 'Sentieon QualCal generate table') # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]] return out_file
def epoch(self): ''' a method to report posix epoch timestamp from a labDT object :return: float with timestamp ''' # construct epoch timestamp from labDT epoch_dt = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc) delta_time = self - epoch_dt return delta_time.total_seconds()
def function[epoch, parameter[self]]: constant[ a method to report posix epoch timestamp from a labDT object :return: float with timestamp ] variable[epoch_dt] assign[=] call[call[name[datetime].utcfromtimestamp, parameter[constant[0]]].replace, parameter[]] variable[delta_time] assign[=] binary_operation[name[self] - name[epoch_dt]] return[call[name[delta_time].total_seconds, parameter[]]]
keyword[def] identifier[epoch] ( identifier[self] ): literal[string] identifier[epoch_dt] = identifier[datetime] . identifier[utcfromtimestamp] ( literal[int] ). identifier[replace] ( identifier[tzinfo] = identifier[pytz] . identifier[utc] ) identifier[delta_time] = identifier[self] - identifier[epoch_dt] keyword[return] identifier[delta_time] . identifier[total_seconds] ()
def epoch(self): """ a method to report posix epoch timestamp from a labDT object :return: float with timestamp """ # construct epoch timestamp from labDT epoch_dt = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc) delta_time = self - epoch_dt return delta_time.total_seconds()
def _update_shared_response(X, S, W, features): """Update the shared response `R`. Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data for alignment of one subject. S : list of array, element i has shape=[voxels_i, timepoints] The individual component :math:`S_i` for each subject. W : list of array, element i has shape=[voxels_i, features] The orthogonal transforms (mappings) :math:`W_i` for each subject. features : int The number of features in the model. Returns ------- R : array, shape=[features, timepoints] The updated shared response. """ subjs = len(X) TRs = X[0].shape[1] R = np.zeros((features, TRs)) # Project the subject data with the individual component removed into # the shared subspace and average over all subjects. for i in range(subjs): R += W[i].T.dot(X[i]-S[i]) R /= subjs return R
def function[_update_shared_response, parameter[X, S, W, features]]: constant[Update the shared response `R`. Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data for alignment of one subject. S : list of array, element i has shape=[voxels_i, timepoints] The individual component :math:`S_i` for each subject. W : list of array, element i has shape=[voxels_i, features] The orthogonal transforms (mappings) :math:`W_i` for each subject. features : int The number of features in the model. Returns ------- R : array, shape=[features, timepoints] The updated shared response. ] variable[subjs] assign[=] call[name[len], parameter[name[X]]] variable[TRs] assign[=] call[call[name[X]][constant[0]].shape][constant[1]] variable[R] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Name object at 0x7da1b07450f0>, <ast.Name object at 0x7da1b0745150>]]]] for taget[name[i]] in starred[call[name[range], parameter[name[subjs]]]] begin[:] <ast.AugAssign object at 0x7da1b0745270> <ast.AugAssign object at 0x7da1b0745960> return[name[R]]
keyword[def] identifier[_update_shared_response] ( identifier[X] , identifier[S] , identifier[W] , identifier[features] ): literal[string] identifier[subjs] = identifier[len] ( identifier[X] ) identifier[TRs] = identifier[X] [ literal[int] ]. identifier[shape] [ literal[int] ] identifier[R] = identifier[np] . identifier[zeros] (( identifier[features] , identifier[TRs] )) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[subjs] ): identifier[R] += identifier[W] [ identifier[i] ]. identifier[T] . identifier[dot] ( identifier[X] [ identifier[i] ]- identifier[S] [ identifier[i] ]) identifier[R] /= identifier[subjs] keyword[return] identifier[R]
def _update_shared_response(X, S, W, features): """Update the shared response `R`. Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data for alignment of one subject. S : list of array, element i has shape=[voxels_i, timepoints] The individual component :math:`S_i` for each subject. W : list of array, element i has shape=[voxels_i, features] The orthogonal transforms (mappings) :math:`W_i` for each subject. features : int The number of features in the model. Returns ------- R : array, shape=[features, timepoints] The updated shared response. """ subjs = len(X) TRs = X[0].shape[1] R = np.zeros((features, TRs)) # Project the subject data with the individual component removed into # the shared subspace and average over all subjects. for i in range(subjs): R += W[i].T.dot(X[i] - S[i]) # depends on [control=['for'], data=['i']] R /= subjs return R
def get_common_properties(root): """Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with common properties """ properties = {} for elem in root.iterfind('commonProperties/property'): name = elem.attrib['name'] if name == 'initial composition': properties['composition'] = {'species': [], 'kind': None} for child in elem.iter('component'): spec = {} spec['species-name'] = child.find('speciesLink').attrib['preferredKey'] units = child.find('amount').attrib['units'] # use InChI for unique species identifier (if present) try: spec['InChI'] = child.find('speciesLink').attrib['InChI'] except KeyError: # TODO: add InChI validator/search warn('Missing InChI for species ' + spec['species-name']) pass # If mole or mass fraction, just set value if units in ['mole fraction', 'mass fraction', 'mole percent']: spec['amount'] = [float(child.find('amount').text)] elif units == 'percent': # assume this means mole percent warn('Assuming percent in composition means mole percent') spec['amount'] = [float(child.find('amount').text)] units = 'mole percent' elif units == 'ppm': # assume molar ppm, convert to mole fraction warn('Assuming molar ppm in composition and converting to mole fraction') spec['amount'] = [float(child.find('amount').text) * 1.e-6] units = 'mole fraction' elif units == 'ppb': # assume molar ppb, convert to mole fraction warn('Assuming molar ppb in composition and converting to mole fraction') spec['amount'] = [float(child.find('amount').text) * 1.e-9] units = 'mole fraction' else: raise KeywordError('Composition units need to be one of: mole fraction, ' 'mass fraction, mole percent, percent, ppm, or ppb.' ) properties['composition']['species'].append(spec) # check consistency of composition type if properties['composition']['kind'] is None: properties['composition']['kind'] = units elif properties['composition']['kind'] != units: raise KeywordError('composition units ' + units + ' not consistent with ' + properties['composition']['kind'] ) elif name in datagroup_properties: field = name.replace(' ', '-') units = elem.attrib['units'] if units == 'Torr': units = 'torr' quantity = 1.0 * unit_registry(units) try: quantity.to(property_units[field]) except pint.DimensionalityError: raise KeywordError('units incompatible for property ' + name) properties[field] = [' '.join([elem.find('value').text, units])] else: raise KeywordError('Property ' + name + ' not supported as common property') return properties
def function[get_common_properties, parameter[root]]: constant[Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with common properties ] variable[properties] assign[=] dictionary[[], []] for taget[name[elem]] in starred[call[name[root].iterfind, parameter[constant[commonProperties/property]]]] begin[:] variable[name] assign[=] call[name[elem].attrib][constant[name]] if compare[name[name] equal[==] constant[initial composition]] begin[:] call[name[properties]][constant[composition]] assign[=] dictionary[[<ast.Constant object at 0x7da1b2558af0>, <ast.Constant object at 0x7da1b255a6e0>], [<ast.List object at 0x7da1b255ad40>, <ast.Constant object at 0x7da1b255ae90>]] for taget[name[child]] in starred[call[name[elem].iter, parameter[constant[component]]]] begin[:] variable[spec] assign[=] dictionary[[], []] call[name[spec]][constant[species-name]] assign[=] call[call[name[child].find, parameter[constant[speciesLink]]].attrib][constant[preferredKey]] variable[units] assign[=] call[call[name[child].find, parameter[constant[amount]]].attrib][constant[units]] <ast.Try object at 0x7da1b243a560> if compare[name[units] in list[[<ast.Constant object at 0x7da1b2439b70>, <ast.Constant object at 0x7da1b243ae60>, <ast.Constant object at 0x7da1b2439480>]]] begin[:] call[name[spec]][constant[amount]] assign[=] list[[<ast.Call object at 0x7da1b2438ac0>]] call[call[call[name[properties]][constant[composition]]][constant[species]].append, parameter[name[spec]]] if compare[call[call[name[properties]][constant[composition]]][constant[kind]] is constant[None]] begin[:] call[call[name[properties]][constant[composition]]][constant[kind]] assign[=] name[units] return[name[properties]]
keyword[def] identifier[get_common_properties] ( identifier[root] ): literal[string] identifier[properties] ={} keyword[for] identifier[elem] keyword[in] identifier[root] . identifier[iterfind] ( literal[string] ): identifier[name] = identifier[elem] . identifier[attrib] [ literal[string] ] keyword[if] identifier[name] == literal[string] : identifier[properties] [ literal[string] ]={ literal[string] :[], literal[string] : keyword[None] } keyword[for] identifier[child] keyword[in] identifier[elem] . identifier[iter] ( literal[string] ): identifier[spec] ={} identifier[spec] [ literal[string] ]= identifier[child] . identifier[find] ( literal[string] ). identifier[attrib] [ literal[string] ] identifier[units] = identifier[child] . identifier[find] ( literal[string] ). identifier[attrib] [ literal[string] ] keyword[try] : identifier[spec] [ literal[string] ]= identifier[child] . identifier[find] ( literal[string] ). identifier[attrib] [ literal[string] ] keyword[except] identifier[KeyError] : identifier[warn] ( literal[string] + identifier[spec] [ literal[string] ]) keyword[pass] keyword[if] identifier[units] keyword[in] [ literal[string] , literal[string] , literal[string] ]: identifier[spec] [ literal[string] ]=[ identifier[float] ( identifier[child] . identifier[find] ( literal[string] ). identifier[text] )] keyword[elif] identifier[units] == literal[string] : identifier[warn] ( literal[string] ) identifier[spec] [ literal[string] ]=[ identifier[float] ( identifier[child] . identifier[find] ( literal[string] ). identifier[text] )] identifier[units] = literal[string] keyword[elif] identifier[units] == literal[string] : identifier[warn] ( literal[string] ) identifier[spec] [ literal[string] ]=[ identifier[float] ( identifier[child] . identifier[find] ( literal[string] ). identifier[text] )* literal[int] ] identifier[units] = literal[string] keyword[elif] identifier[units] == literal[string] : identifier[warn] ( literal[string] ) identifier[spec] [ literal[string] ]=[ identifier[float] ( identifier[child] . identifier[find] ( literal[string] ). identifier[text] )* literal[int] ] identifier[units] = literal[string] keyword[else] : keyword[raise] identifier[KeywordError] ( literal[string] literal[string] ) identifier[properties] [ literal[string] ][ literal[string] ]. identifier[append] ( identifier[spec] ) keyword[if] identifier[properties] [ literal[string] ][ literal[string] ] keyword[is] keyword[None] : identifier[properties] [ literal[string] ][ literal[string] ]= identifier[units] keyword[elif] identifier[properties] [ literal[string] ][ literal[string] ]!= identifier[units] : keyword[raise] identifier[KeywordError] ( literal[string] + identifier[units] + literal[string] + identifier[properties] [ literal[string] ][ literal[string] ] ) keyword[elif] identifier[name] keyword[in] identifier[datagroup_properties] : identifier[field] = identifier[name] . identifier[replace] ( literal[string] , literal[string] ) identifier[units] = identifier[elem] . identifier[attrib] [ literal[string] ] keyword[if] identifier[units] == literal[string] : identifier[units] = literal[string] identifier[quantity] = literal[int] * identifier[unit_registry] ( identifier[units] ) keyword[try] : identifier[quantity] . identifier[to] ( identifier[property_units] [ identifier[field] ]) keyword[except] identifier[pint] . identifier[DimensionalityError] : keyword[raise] identifier[KeywordError] ( literal[string] + identifier[name] ) identifier[properties] [ identifier[field] ]=[ literal[string] . identifier[join] ([ identifier[elem] . identifier[find] ( literal[string] ). identifier[text] , identifier[units] ])] keyword[else] : keyword[raise] identifier[KeywordError] ( literal[string] + identifier[name] + literal[string] ) keyword[return] identifier[properties]
def get_common_properties(root): """Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with common properties """ properties = {} for elem in root.iterfind('commonProperties/property'): name = elem.attrib['name'] if name == 'initial composition': properties['composition'] = {'species': [], 'kind': None} for child in elem.iter('component'): spec = {} spec['species-name'] = child.find('speciesLink').attrib['preferredKey'] units = child.find('amount').attrib['units'] # use InChI for unique species identifier (if present) try: spec['InChI'] = child.find('speciesLink').attrib['InChI'] # depends on [control=['try'], data=[]] except KeyError: # TODO: add InChI validator/search warn('Missing InChI for species ' + spec['species-name']) pass # depends on [control=['except'], data=[]] # If mole or mass fraction, just set value if units in ['mole fraction', 'mass fraction', 'mole percent']: spec['amount'] = [float(child.find('amount').text)] # depends on [control=['if'], data=[]] elif units == 'percent': # assume this means mole percent warn('Assuming percent in composition means mole percent') spec['amount'] = [float(child.find('amount').text)] units = 'mole percent' # depends on [control=['if'], data=['units']] elif units == 'ppm': # assume molar ppm, convert to mole fraction warn('Assuming molar ppm in composition and converting to mole fraction') spec['amount'] = [float(child.find('amount').text) * 1e-06] units = 'mole fraction' # depends on [control=['if'], data=['units']] elif units == 'ppb': # assume molar ppb, convert to mole fraction warn('Assuming molar ppb in composition and converting to mole fraction') spec['amount'] = [float(child.find('amount').text) * 1e-09] units = 'mole fraction' # depends on [control=['if'], data=['units']] else: raise KeywordError('Composition units need to be one of: mole fraction, mass fraction, mole percent, percent, ppm, or ppb.') properties['composition']['species'].append(spec) # check consistency of composition type if properties['composition']['kind'] is None: properties['composition']['kind'] = units # depends on [control=['if'], data=[]] elif properties['composition']['kind'] != units: raise KeywordError('composition units ' + units + ' not consistent with ' + properties['composition']['kind']) # depends on [control=['if'], data=['units']] # depends on [control=['for'], data=['child']] # depends on [control=['if'], data=[]] elif name in datagroup_properties: field = name.replace(' ', '-') units = elem.attrib['units'] if units == 'Torr': units = 'torr' # depends on [control=['if'], data=['units']] quantity = 1.0 * unit_registry(units) try: quantity.to(property_units[field]) # depends on [control=['try'], data=[]] except pint.DimensionalityError: raise KeywordError('units incompatible for property ' + name) # depends on [control=['except'], data=[]] properties[field] = [' '.join([elem.find('value').text, units])] # depends on [control=['if'], data=['name']] else: raise KeywordError('Property ' + name + ' not supported as common property') # depends on [control=['for'], data=['elem']] return properties
def visit_page(self, page): """ Visit the specific page of the site, e.g. .. code-block:: gherkin When I visit site page "/users" """ url = urljoin(django_url(self), page) self.given('I visit "%s"' % url)
def function[visit_page, parameter[self, page]]: constant[ Visit the specific page of the site, e.g. .. code-block:: gherkin When I visit site page "/users" ] variable[url] assign[=] call[name[urljoin], parameter[call[name[django_url], parameter[name[self]]], name[page]]] call[name[self].given, parameter[binary_operation[constant[I visit "%s"] <ast.Mod object at 0x7da2590d6920> name[url]]]]
keyword[def] identifier[visit_page] ( identifier[self] , identifier[page] ): literal[string] identifier[url] = identifier[urljoin] ( identifier[django_url] ( identifier[self] ), identifier[page] ) identifier[self] . identifier[given] ( literal[string] % identifier[url] )
def visit_page(self, page): """ Visit the specific page of the site, e.g. .. code-block:: gherkin When I visit site page "/users" """ url = urljoin(django_url(self), page) self.given('I visit "%s"' % url)
def read_acceptance_fraction(self, temps=None, walkers=None): """Reads the acceptance fraction. Parameters ----------- temps : (list of) int, optional The temperature index (or a list of indices) to retrieve. If None, acfs from all temperatures and all walkers will be retrieved. walkers : (list of) int, optional The walker index (or a list of indices) to retrieve. If None, samples from all walkers will be obtained. Returns ------- array Array of acceptance fractions with shape (requested temps, requested walkers). """ group = self.sampler_group + '/acceptance_fraction' if walkers is None: wmask = numpy.ones(self.nwalkers, dtype=bool) else: wmask = numpy.zeros(self.nwalkers, dtype=bool) wmask[walkers] = True if temps is None: tmask = numpy.ones(self.ntemps, dtype=bool) else: tmask = numpy.zeros(self.ntemps, dtype=bool) tmask[temps] = True return self[group][:][numpy.ix_(tmask, wmask)]
def function[read_acceptance_fraction, parameter[self, temps, walkers]]: constant[Reads the acceptance fraction. Parameters ----------- temps : (list of) int, optional The temperature index (or a list of indices) to retrieve. If None, acfs from all temperatures and all walkers will be retrieved. walkers : (list of) int, optional The walker index (or a list of indices) to retrieve. If None, samples from all walkers will be obtained. Returns ------- array Array of acceptance fractions with shape (requested temps, requested walkers). ] variable[group] assign[=] binary_operation[name[self].sampler_group + constant[/acceptance_fraction]] if compare[name[walkers] is constant[None]] begin[:] variable[wmask] assign[=] call[name[numpy].ones, parameter[name[self].nwalkers]] if compare[name[temps] is constant[None]] begin[:] variable[tmask] assign[=] call[name[numpy].ones, parameter[name[self].ntemps]] return[call[call[call[name[self]][name[group]]][<ast.Slice object at 0x7da18bc728c0>]][call[name[numpy].ix_, parameter[name[tmask], name[wmask]]]]]
keyword[def] identifier[read_acceptance_fraction] ( identifier[self] , identifier[temps] = keyword[None] , identifier[walkers] = keyword[None] ): literal[string] identifier[group] = identifier[self] . identifier[sampler_group] + literal[string] keyword[if] identifier[walkers] keyword[is] keyword[None] : identifier[wmask] = identifier[numpy] . identifier[ones] ( identifier[self] . identifier[nwalkers] , identifier[dtype] = identifier[bool] ) keyword[else] : identifier[wmask] = identifier[numpy] . identifier[zeros] ( identifier[self] . identifier[nwalkers] , identifier[dtype] = identifier[bool] ) identifier[wmask] [ identifier[walkers] ]= keyword[True] keyword[if] identifier[temps] keyword[is] keyword[None] : identifier[tmask] = identifier[numpy] . identifier[ones] ( identifier[self] . identifier[ntemps] , identifier[dtype] = identifier[bool] ) keyword[else] : identifier[tmask] = identifier[numpy] . identifier[zeros] ( identifier[self] . identifier[ntemps] , identifier[dtype] = identifier[bool] ) identifier[tmask] [ identifier[temps] ]= keyword[True] keyword[return] identifier[self] [ identifier[group] ][:][ identifier[numpy] . identifier[ix_] ( identifier[tmask] , identifier[wmask] )]
def read_acceptance_fraction(self, temps=None, walkers=None): """Reads the acceptance fraction. Parameters ----------- temps : (list of) int, optional The temperature index (or a list of indices) to retrieve. If None, acfs from all temperatures and all walkers will be retrieved. walkers : (list of) int, optional The walker index (or a list of indices) to retrieve. If None, samples from all walkers will be obtained. Returns ------- array Array of acceptance fractions with shape (requested temps, requested walkers). """ group = self.sampler_group + '/acceptance_fraction' if walkers is None: wmask = numpy.ones(self.nwalkers, dtype=bool) # depends on [control=['if'], data=[]] else: wmask = numpy.zeros(self.nwalkers, dtype=bool) wmask[walkers] = True if temps is None: tmask = numpy.ones(self.ntemps, dtype=bool) # depends on [control=['if'], data=[]] else: tmask = numpy.zeros(self.ntemps, dtype=bool) tmask[temps] = True return self[group][:][numpy.ix_(tmask, wmask)]
def mutable_block(self, x: int, y: int) -> Block: """Returns the block at (x, y) so it can be edited.""" if x < 0 or y < 0: raise IndexError('x < 0 or y < 0') return self._blocks[(x, y)]
def function[mutable_block, parameter[self, x, y]]: constant[Returns the block at (x, y) so it can be edited.] if <ast.BoolOp object at 0x7da20c7c8580> begin[:] <ast.Raise object at 0x7da20c7cac20> return[call[name[self]._blocks][tuple[[<ast.Name object at 0x7da20c7c90f0>, <ast.Name object at 0x7da20c7cb730>]]]]
keyword[def] identifier[mutable_block] ( identifier[self] , identifier[x] : identifier[int] , identifier[y] : identifier[int] )-> identifier[Block] : literal[string] keyword[if] identifier[x] < literal[int] keyword[or] identifier[y] < literal[int] : keyword[raise] identifier[IndexError] ( literal[string] ) keyword[return] identifier[self] . identifier[_blocks] [( identifier[x] , identifier[y] )]
def mutable_block(self, x: int, y: int) -> Block: """Returns the block at (x, y) so it can be edited.""" if x < 0 or y < 0: raise IndexError('x < 0 or y < 0') # depends on [control=['if'], data=[]] return self._blocks[x, y]
def is_contradictory(self, other): """ Whether other and self can coexist """ other = self.coerce(other) to_i = self.to_i assert to_i(other.low) <= to_i(other.high), "Low must be <= high" if max(map(to_i, [other.low, self.low])) <= min(map(to_i, [other.high, self.high])): return False else: return True
def function[is_contradictory, parameter[self, other]]: constant[ Whether other and self can coexist ] variable[other] assign[=] call[name[self].coerce, parameter[name[other]]] variable[to_i] assign[=] name[self].to_i assert[compare[call[name[to_i], parameter[name[other].low]] less_or_equal[<=] call[name[to_i], parameter[name[other].high]]]] if compare[call[name[max], parameter[call[name[map], parameter[name[to_i], list[[<ast.Attribute object at 0x7da1b1461780>, <ast.Attribute object at 0x7da1b1463910>]]]]]] less_or_equal[<=] call[name[min], parameter[call[name[map], parameter[name[to_i], list[[<ast.Attribute object at 0x7da1b1461630>, <ast.Attribute object at 0x7da1b14620b0>]]]]]]] begin[:] return[constant[False]]
keyword[def] identifier[is_contradictory] ( identifier[self] , identifier[other] ): literal[string] identifier[other] = identifier[self] . identifier[coerce] ( identifier[other] ) identifier[to_i] = identifier[self] . identifier[to_i] keyword[assert] identifier[to_i] ( identifier[other] . identifier[low] )<= identifier[to_i] ( identifier[other] . identifier[high] ), literal[string] keyword[if] identifier[max] ( identifier[map] ( identifier[to_i] ,[ identifier[other] . identifier[low] , identifier[self] . identifier[low] ]))<= identifier[min] ( identifier[map] ( identifier[to_i] ,[ identifier[other] . identifier[high] , identifier[self] . identifier[high] ])): keyword[return] keyword[False] keyword[else] : keyword[return] keyword[True]
def is_contradictory(self, other): """ Whether other and self can coexist """ other = self.coerce(other) to_i = self.to_i assert to_i(other.low) <= to_i(other.high), 'Low must be <= high' if max(map(to_i, [other.low, self.low])) <= min(map(to_i, [other.high, self.high])): return False # depends on [control=['if'], data=[]] else: return True
def _assign_method(self, resource_class, method_type): """ Exactly the same code as the original except: - uid is now first parameter (after self). Therefore, no need to explicitly call 'uid=' - Ignored the other http methods besides GET (as they are not needed for the pokeapi.co API) - Added cache wrapping function - Added a way to list all get methods """ method_name = resource_class.get_method_name( resource_class, method_type) valid_status_codes = getattr( resource_class.Meta, 'valid_status_codes', DEFAULT_VALID_STATUS_CODES ) # uid is now the first argument (after self) @self._cache def get(self, uid=None, method_type=method_type, method_name=method_name, valid_status_codes=valid_status_codes, resource=resource_class, data=None, **kwargs): uid = uid.lower() if isinstance(uid, str) else uid return self.call_api( method_type, method_name, valid_status_codes, resource, data, uid=uid, **kwargs) # only GET method is used setattr( self, method_name, types.MethodType(get, self) ) # for easier listing of get methods self._all_get_methods_names.append(method_name)
def function[_assign_method, parameter[self, resource_class, method_type]]: constant[ Exactly the same code as the original except: - uid is now first parameter (after self). Therefore, no need to explicitly call 'uid=' - Ignored the other http methods besides GET (as they are not needed for the pokeapi.co API) - Added cache wrapping function - Added a way to list all get methods ] variable[method_name] assign[=] call[name[resource_class].get_method_name, parameter[name[resource_class], name[method_type]]] variable[valid_status_codes] assign[=] call[name[getattr], parameter[name[resource_class].Meta, constant[valid_status_codes], name[DEFAULT_VALID_STATUS_CODES]]] def function[get, parameter[self, uid, method_type, method_name, valid_status_codes, resource, data]]: variable[uid] assign[=] <ast.IfExp object at 0x7da20c76ecb0> return[call[name[self].call_api, parameter[name[method_type], name[method_name], name[valid_status_codes], name[resource], name[data]]]] call[name[setattr], parameter[name[self], name[method_name], call[name[types].MethodType, parameter[name[get], name[self]]]]] call[name[self]._all_get_methods_names.append, parameter[name[method_name]]]
keyword[def] identifier[_assign_method] ( identifier[self] , identifier[resource_class] , identifier[method_type] ): literal[string] identifier[method_name] = identifier[resource_class] . identifier[get_method_name] ( identifier[resource_class] , identifier[method_type] ) identifier[valid_status_codes] = identifier[getattr] ( identifier[resource_class] . identifier[Meta] , literal[string] , identifier[DEFAULT_VALID_STATUS_CODES] ) @ identifier[self] . identifier[_cache] keyword[def] identifier[get] ( identifier[self] , identifier[uid] = keyword[None] , identifier[method_type] = identifier[method_type] , identifier[method_name] = identifier[method_name] , identifier[valid_status_codes] = identifier[valid_status_codes] , identifier[resource] = identifier[resource_class] , identifier[data] = keyword[None] ,** identifier[kwargs] ): identifier[uid] = identifier[uid] . identifier[lower] () keyword[if] identifier[isinstance] ( identifier[uid] , identifier[str] ) keyword[else] identifier[uid] keyword[return] identifier[self] . identifier[call_api] ( identifier[method_type] , identifier[method_name] , identifier[valid_status_codes] , identifier[resource] , identifier[data] , identifier[uid] = identifier[uid] ,** identifier[kwargs] ) identifier[setattr] ( identifier[self] , identifier[method_name] , identifier[types] . identifier[MethodType] ( identifier[get] , identifier[self] ) ) identifier[self] . identifier[_all_get_methods_names] . identifier[append] ( identifier[method_name] )
def _assign_method(self, resource_class, method_type): """ Exactly the same code as the original except: - uid is now first parameter (after self). Therefore, no need to explicitly call 'uid=' - Ignored the other http methods besides GET (as they are not needed for the pokeapi.co API) - Added cache wrapping function - Added a way to list all get methods """ method_name = resource_class.get_method_name(resource_class, method_type) valid_status_codes = getattr(resource_class.Meta, 'valid_status_codes', DEFAULT_VALID_STATUS_CODES) # uid is now the first argument (after self) @self._cache def get(self, uid=None, method_type=method_type, method_name=method_name, valid_status_codes=valid_status_codes, resource=resource_class, data=None, **kwargs): uid = uid.lower() if isinstance(uid, str) else uid return self.call_api(method_type, method_name, valid_status_codes, resource, data, uid=uid, **kwargs) # only GET method is used setattr(self, method_name, types.MethodType(get, self)) # for easier listing of get methods self._all_get_methods_names.append(method_name)
def insert(self, index, object): """insert object before index""" self._check(object.id) list.insert(self, index, object) # all subsequent entries now have been shifted up by 1 _dict = self._dict for i, j in iteritems(_dict): if j >= index: _dict[i] = j + 1 _dict[object.id] = index
def function[insert, parameter[self, index, object]]: constant[insert object before index] call[name[self]._check, parameter[name[object].id]] call[name[list].insert, parameter[name[self], name[index], name[object]]] variable[_dict] assign[=] name[self]._dict for taget[tuple[[<ast.Name object at 0x7da1b0003fa0>, <ast.Name object at 0x7da1b0002020>]]] in starred[call[name[iteritems], parameter[name[_dict]]]] begin[:] if compare[name[j] greater_or_equal[>=] name[index]] begin[:] call[name[_dict]][name[i]] assign[=] binary_operation[name[j] + constant[1]] call[name[_dict]][name[object].id] assign[=] name[index]
keyword[def] identifier[insert] ( identifier[self] , identifier[index] , identifier[object] ): literal[string] identifier[self] . identifier[_check] ( identifier[object] . identifier[id] ) identifier[list] . identifier[insert] ( identifier[self] , identifier[index] , identifier[object] ) identifier[_dict] = identifier[self] . identifier[_dict] keyword[for] identifier[i] , identifier[j] keyword[in] identifier[iteritems] ( identifier[_dict] ): keyword[if] identifier[j] >= identifier[index] : identifier[_dict] [ identifier[i] ]= identifier[j] + literal[int] identifier[_dict] [ identifier[object] . identifier[id] ]= identifier[index]
def insert(self, index, object): """insert object before index""" self._check(object.id) list.insert(self, index, object) # all subsequent entries now have been shifted up by 1 _dict = self._dict for (i, j) in iteritems(_dict): if j >= index: _dict[i] = j + 1 # depends on [control=['if'], data=['j']] # depends on [control=['for'], data=[]] _dict[object.id] = index
def get_n_config_to_keep_for_iteration(self, iteration, bracket_iteration): """Return the number of configs to keep for an iteration and iteration bracket. This is just util function around `get_n_config_to_keep` """ bracket = self.get_bracket(iteration=iteration) if bracket_iteration == bracket + 1: # End of loop `for bracket_iteration in range(bracket + 1):` return 0 n_configs = self.get_n_configs(bracket=bracket) return self.get_n_config_to_keep( n_suggestions=n_configs, bracket_iteration=bracket_iteration)
def function[get_n_config_to_keep_for_iteration, parameter[self, iteration, bracket_iteration]]: constant[Return the number of configs to keep for an iteration and iteration bracket. This is just util function around `get_n_config_to_keep` ] variable[bracket] assign[=] call[name[self].get_bracket, parameter[]] if compare[name[bracket_iteration] equal[==] binary_operation[name[bracket] + constant[1]]] begin[:] return[constant[0]] variable[n_configs] assign[=] call[name[self].get_n_configs, parameter[]] return[call[name[self].get_n_config_to_keep, parameter[]]]
keyword[def] identifier[get_n_config_to_keep_for_iteration] ( identifier[self] , identifier[iteration] , identifier[bracket_iteration] ): literal[string] identifier[bracket] = identifier[self] . identifier[get_bracket] ( identifier[iteration] = identifier[iteration] ) keyword[if] identifier[bracket_iteration] == identifier[bracket] + literal[int] : keyword[return] literal[int] identifier[n_configs] = identifier[self] . identifier[get_n_configs] ( identifier[bracket] = identifier[bracket] ) keyword[return] identifier[self] . identifier[get_n_config_to_keep] ( identifier[n_suggestions] = identifier[n_configs] , identifier[bracket_iteration] = identifier[bracket_iteration] )
def get_n_config_to_keep_for_iteration(self, iteration, bracket_iteration): """Return the number of configs to keep for an iteration and iteration bracket. This is just util function around `get_n_config_to_keep` """ bracket = self.get_bracket(iteration=iteration) if bracket_iteration == bracket + 1: # End of loop `for bracket_iteration in range(bracket + 1):` return 0 # depends on [control=['if'], data=[]] n_configs = self.get_n_configs(bracket=bracket) return self.get_n_config_to_keep(n_suggestions=n_configs, bracket_iteration=bracket_iteration)
def jaccard_sim(features1, features2): """Compute similarity between two sets using Jaccard similarity. Args: features1: list of PE Symbols. features2: list of PE Symbols. Returns: Returns an int. """ set1 = set(features1) set2 = set(features2) try: return len(set1.intersection(set2))/float(max(len(set1), len(set2))) except ZeroDivisionError: return 0
def function[jaccard_sim, parameter[features1, features2]]: constant[Compute similarity between two sets using Jaccard similarity. Args: features1: list of PE Symbols. features2: list of PE Symbols. Returns: Returns an int. ] variable[set1] assign[=] call[name[set], parameter[name[features1]]] variable[set2] assign[=] call[name[set], parameter[name[features2]]] <ast.Try object at 0x7da20c6c5480>
keyword[def] identifier[jaccard_sim] ( identifier[features1] , identifier[features2] ): literal[string] identifier[set1] = identifier[set] ( identifier[features1] ) identifier[set2] = identifier[set] ( identifier[features2] ) keyword[try] : keyword[return] identifier[len] ( identifier[set1] . identifier[intersection] ( identifier[set2] ))/ identifier[float] ( identifier[max] ( identifier[len] ( identifier[set1] ), identifier[len] ( identifier[set2] ))) keyword[except] identifier[ZeroDivisionError] : keyword[return] literal[int]
def jaccard_sim(features1, features2): """Compute similarity between two sets using Jaccard similarity. Args: features1: list of PE Symbols. features2: list of PE Symbols. Returns: Returns an int. """ set1 = set(features1) set2 = set(features2) try: return len(set1.intersection(set2)) / float(max(len(set1), len(set2))) # depends on [control=['try'], data=[]] except ZeroDivisionError: return 0 # depends on [control=['except'], data=[]]
def _tf_squared_euclidean(X, Y): """Squared Euclidean distance between the rows of `X` and `Y`. """ return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)
def function[_tf_squared_euclidean, parameter[X, Y]]: constant[Squared Euclidean distance between the rows of `X` and `Y`. ] return[call[name[tf].reduce_sum, parameter[call[name[tf].pow, parameter[call[name[tf].subtract, parameter[name[X], name[Y]]], constant[2]]]]]]
keyword[def] identifier[_tf_squared_euclidean] ( identifier[X] , identifier[Y] ): literal[string] keyword[return] identifier[tf] . identifier[reduce_sum] ( identifier[tf] . identifier[pow] ( identifier[tf] . identifier[subtract] ( identifier[X] , identifier[Y] ), literal[int] ), identifier[axis] = literal[int] )
def _tf_squared_euclidean(X, Y): """Squared Euclidean distance between the rows of `X` and `Y`. """ return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)
def _get_temp_file_location(): ''' Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) ''' from .._connect import main as _glconnect unity = _glconnect.get_unity() cache_dir = _convert_slashes(unity.get_current_cache_file_location()) if not _os.path.exists(cache_dir): _os.makedirs(cache_dir) return cache_dir
def function[_get_temp_file_location, parameter[]]: constant[ Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) ] from relative_module[_connect] import module[main] variable[unity] assign[=] call[name[_glconnect].get_unity, parameter[]] variable[cache_dir] assign[=] call[name[_convert_slashes], parameter[call[name[unity].get_current_cache_file_location, parameter[]]]] if <ast.UnaryOp object at 0x7da1b20eeb00> begin[:] call[name[_os].makedirs, parameter[name[cache_dir]]] return[name[cache_dir]]
keyword[def] identifier[_get_temp_file_location] (): literal[string] keyword[from] .. identifier[_connect] keyword[import] identifier[main] keyword[as] identifier[_glconnect] identifier[unity] = identifier[_glconnect] . identifier[get_unity] () identifier[cache_dir] = identifier[_convert_slashes] ( identifier[unity] . identifier[get_current_cache_file_location] ()) keyword[if] keyword[not] identifier[_os] . identifier[path] . identifier[exists] ( identifier[cache_dir] ): identifier[_os] . identifier[makedirs] ( identifier[cache_dir] ) keyword[return] identifier[cache_dir]
def _get_temp_file_location(): """ Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) """ from .._connect import main as _glconnect unity = _glconnect.get_unity() cache_dir = _convert_slashes(unity.get_current_cache_file_location()) if not _os.path.exists(cache_dir): _os.makedirs(cache_dir) # depends on [control=['if'], data=[]] return cache_dir
def extend(network, pore_coords=[], throat_conns=[], labels=[]): r''' Add individual pores and/or throats to the network from a list of coords or conns. Parameters ---------- network : OpenPNM Network Object The Network to which pores or throats should be added pore_coords : array_like The coordinates of the pores to add throat_conns : array_like The throat connections to add labels : string, or list of strings, optional A list of labels to apply to the new pores and throats Notes ----- This needs to be enhanced so that it increases the size of all pore and throat props and labels on ALL associated Phase objects. At the moment it throws an error is there are any associated Phases. This is an in-place operation, meaning the received Network object will be altered directly. ''' if len(network.project.phases()) > 0: raise Exception('Project has active Phases, copy network to a new ' + 'project and try again') Np_old = network.num_pores() Nt_old = network.num_throats() Np = Np_old + int(sp.size(pore_coords)/3) Nt = Nt_old + int(sp.size(throat_conns)/2) # Adjust 'all' labels del network['pore.all'], network['throat.all'] network['pore.all'] = sp.ones((Np,), dtype=bool) network['throat.all'] = sp.ones((Nt,), dtype=bool) # Add coords and conns if sp.size(pore_coords) > 0: coords = sp.vstack((network['pore.coords'], pore_coords)) network['pore.coords'] = coords if sp.size(throat_conns) > 0: conns = sp.vstack((network['throat.conns'], throat_conns)) network['throat.conns'] = conns # Increase size of any prop or label arrays aready on Network for item in list(network.keys()): if item.split('.')[1] not in ['coords', 'conns', 'all', '_id']: N = network._count(element=item.split('.')[0]) arr = network.pop(item) s = arr.shape network[item] = sp.zeros(shape=(N, *s[1:]), dtype=arr.dtype) # This is a temporary work-around until I learn to handle 2+ dims network[item][:arr.shape[0]] = arr # Apply labels, if supplied if labels != []: # Convert labels to list if necessary if type(labels) is str: labels = [labels] for label in labels: # Remove pore or throat from label, if present label = label.split('.')[-1] if sp.size(pore_coords) > 0: Ps = sp.r_[Np_old:Np] if 'pore.'+label not in network.labels(): network['pore.'+label] = False network['pore.'+label][Ps] = True if sp.size(throat_conns) > 0: Ts = sp.r_[Nt_old:Nt] if 'throat.'+label not in network.labels(): network['throat.'+label] = False network['throat.'+label][Ts] = True # Clear adjacency and incidence matrices which will be out of date now network._am.clear() network._im.clear()
def function[extend, parameter[network, pore_coords, throat_conns, labels]]: constant[ Add individual pores and/or throats to the network from a list of coords or conns. Parameters ---------- network : OpenPNM Network Object The Network to which pores or throats should be added pore_coords : array_like The coordinates of the pores to add throat_conns : array_like The throat connections to add labels : string, or list of strings, optional A list of labels to apply to the new pores and throats Notes ----- This needs to be enhanced so that it increases the size of all pore and throat props and labels on ALL associated Phase objects. At the moment it throws an error is there are any associated Phases. This is an in-place operation, meaning the received Network object will be altered directly. ] if compare[call[name[len], parameter[call[name[network].project.phases, parameter[]]]] greater[>] constant[0]] begin[:] <ast.Raise object at 0x7da204960490> variable[Np_old] assign[=] call[name[network].num_pores, parameter[]] variable[Nt_old] assign[=] call[name[network].num_throats, parameter[]] variable[Np] assign[=] binary_operation[name[Np_old] + call[name[int], parameter[binary_operation[call[name[sp].size, parameter[name[pore_coords]]] / constant[3]]]]] variable[Nt] assign[=] binary_operation[name[Nt_old] + call[name[int], parameter[binary_operation[call[name[sp].size, parameter[name[throat_conns]]] / constant[2]]]]] <ast.Delete object at 0x7da2049616c0> call[name[network]][constant[pore.all]] assign[=] call[name[sp].ones, parameter[tuple[[<ast.Name object at 0x7da204960cd0>]]]] call[name[network]][constant[throat.all]] assign[=] call[name[sp].ones, parameter[tuple[[<ast.Name object at 0x7da204962710>]]]] if compare[call[name[sp].size, parameter[name[pore_coords]]] greater[>] constant[0]] begin[:] variable[coords] assign[=] call[name[sp].vstack, parameter[tuple[[<ast.Subscript object at 0x7da204963be0>, <ast.Name object at 0x7da18f58f670>]]]] call[name[network]][constant[pore.coords]] assign[=] name[coords] if compare[call[name[sp].size, parameter[name[throat_conns]]] greater[>] constant[0]] begin[:] variable[conns] assign[=] call[name[sp].vstack, parameter[tuple[[<ast.Subscript object at 0x7da18f58c7f0>, <ast.Name object at 0x7da18f58dc00>]]]] call[name[network]][constant[throat.conns]] assign[=] name[conns] for taget[name[item]] in starred[call[name[list], parameter[call[name[network].keys, parameter[]]]]] begin[:] if compare[call[call[name[item].split, parameter[constant[.]]]][constant[1]] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7da18f58da20>, <ast.Constant object at 0x7da18f58d120>, <ast.Constant object at 0x7da18f58d630>, <ast.Constant object at 0x7da18f58caf0>]]] begin[:] variable[N] assign[=] call[name[network]._count, parameter[]] variable[arr] assign[=] call[name[network].pop, parameter[name[item]]] variable[s] assign[=] name[arr].shape call[name[network]][name[item]] assign[=] call[name[sp].zeros, parameter[]] call[call[name[network]][name[item]]][<ast.Slice object at 0x7da18dc04eb0>] assign[=] name[arr] if compare[name[labels] not_equal[!=] list[[]]] begin[:] if compare[call[name[type], parameter[name[labels]]] is name[str]] begin[:] variable[labels] assign[=] list[[<ast.Name object at 0x7da18dc04430>]] for taget[name[label]] in starred[name[labels]] begin[:] variable[label] assign[=] call[call[name[label].split, parameter[constant[.]]]][<ast.UnaryOp object at 0x7da18dc06d40>] if compare[call[name[sp].size, parameter[name[pore_coords]]] greater[>] constant[0]] begin[:] variable[Ps] assign[=] call[name[sp].r_][<ast.Slice object at 0x7da18dc078b0>] if compare[binary_operation[constant[pore.] + name[label]] <ast.NotIn object at 0x7da2590d7190> call[name[network].labels, parameter[]]] begin[:] call[name[network]][binary_operation[constant[pore.] + name[label]]] assign[=] constant[False] call[call[name[network]][binary_operation[constant[pore.] + name[label]]]][name[Ps]] assign[=] constant[True] if compare[call[name[sp].size, parameter[name[throat_conns]]] greater[>] constant[0]] begin[:] variable[Ts] assign[=] call[name[sp].r_][<ast.Slice object at 0x7da18dc07b80>] if compare[binary_operation[constant[throat.] + name[label]] <ast.NotIn object at 0x7da2590d7190> call[name[network].labels, parameter[]]] begin[:] call[name[network]][binary_operation[constant[throat.] + name[label]]] assign[=] constant[False] call[call[name[network]][binary_operation[constant[throat.] + name[label]]]][name[Ts]] assign[=] constant[True] call[name[network]._am.clear, parameter[]] call[name[network]._im.clear, parameter[]]
keyword[def] identifier[extend] ( identifier[network] , identifier[pore_coords] =[], identifier[throat_conns] =[], identifier[labels] =[]): literal[string] keyword[if] identifier[len] ( identifier[network] . identifier[project] . identifier[phases] ())> literal[int] : keyword[raise] identifier[Exception] ( literal[string] + literal[string] ) identifier[Np_old] = identifier[network] . identifier[num_pores] () identifier[Nt_old] = identifier[network] . identifier[num_throats] () identifier[Np] = identifier[Np_old] + identifier[int] ( identifier[sp] . identifier[size] ( identifier[pore_coords] )/ literal[int] ) identifier[Nt] = identifier[Nt_old] + identifier[int] ( identifier[sp] . identifier[size] ( identifier[throat_conns] )/ literal[int] ) keyword[del] identifier[network] [ literal[string] ], identifier[network] [ literal[string] ] identifier[network] [ literal[string] ]= identifier[sp] . identifier[ones] (( identifier[Np] ,), identifier[dtype] = identifier[bool] ) identifier[network] [ literal[string] ]= identifier[sp] . identifier[ones] (( identifier[Nt] ,), identifier[dtype] = identifier[bool] ) keyword[if] identifier[sp] . identifier[size] ( identifier[pore_coords] )> literal[int] : identifier[coords] = identifier[sp] . identifier[vstack] (( identifier[network] [ literal[string] ], identifier[pore_coords] )) identifier[network] [ literal[string] ]= identifier[coords] keyword[if] identifier[sp] . identifier[size] ( identifier[throat_conns] )> literal[int] : identifier[conns] = identifier[sp] . identifier[vstack] (( identifier[network] [ literal[string] ], identifier[throat_conns] )) identifier[network] [ literal[string] ]= identifier[conns] keyword[for] identifier[item] keyword[in] identifier[list] ( identifier[network] . identifier[keys] ()): keyword[if] identifier[item] . identifier[split] ( literal[string] )[ literal[int] ] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ]: identifier[N] = identifier[network] . identifier[_count] ( identifier[element] = identifier[item] . identifier[split] ( literal[string] )[ literal[int] ]) identifier[arr] = identifier[network] . identifier[pop] ( identifier[item] ) identifier[s] = identifier[arr] . identifier[shape] identifier[network] [ identifier[item] ]= identifier[sp] . identifier[zeros] ( identifier[shape] =( identifier[N] ,* identifier[s] [ literal[int] :]), identifier[dtype] = identifier[arr] . identifier[dtype] ) identifier[network] [ identifier[item] ][: identifier[arr] . identifier[shape] [ literal[int] ]]= identifier[arr] keyword[if] identifier[labels] !=[]: keyword[if] identifier[type] ( identifier[labels] ) keyword[is] identifier[str] : identifier[labels] =[ identifier[labels] ] keyword[for] identifier[label] keyword[in] identifier[labels] : identifier[label] = identifier[label] . identifier[split] ( literal[string] )[- literal[int] ] keyword[if] identifier[sp] . identifier[size] ( identifier[pore_coords] )> literal[int] : identifier[Ps] = identifier[sp] . identifier[r_] [ identifier[Np_old] : identifier[Np] ] keyword[if] literal[string] + identifier[label] keyword[not] keyword[in] identifier[network] . identifier[labels] (): identifier[network] [ literal[string] + identifier[label] ]= keyword[False] identifier[network] [ literal[string] + identifier[label] ][ identifier[Ps] ]= keyword[True] keyword[if] identifier[sp] . identifier[size] ( identifier[throat_conns] )> literal[int] : identifier[Ts] = identifier[sp] . identifier[r_] [ identifier[Nt_old] : identifier[Nt] ] keyword[if] literal[string] + identifier[label] keyword[not] keyword[in] identifier[network] . identifier[labels] (): identifier[network] [ literal[string] + identifier[label] ]= keyword[False] identifier[network] [ literal[string] + identifier[label] ][ identifier[Ts] ]= keyword[True] identifier[network] . identifier[_am] . identifier[clear] () identifier[network] . identifier[_im] . identifier[clear] ()
def extend(network, pore_coords=[], throat_conns=[], labels=[]): """ Add individual pores and/or throats to the network from a list of coords or conns. Parameters ---------- network : OpenPNM Network Object The Network to which pores or throats should be added pore_coords : array_like The coordinates of the pores to add throat_conns : array_like The throat connections to add labels : string, or list of strings, optional A list of labels to apply to the new pores and throats Notes ----- This needs to be enhanced so that it increases the size of all pore and throat props and labels on ALL associated Phase objects. At the moment it throws an error is there are any associated Phases. This is an in-place operation, meaning the received Network object will be altered directly. """ if len(network.project.phases()) > 0: raise Exception('Project has active Phases, copy network to a new ' + 'project and try again') # depends on [control=['if'], data=[]] Np_old = network.num_pores() Nt_old = network.num_throats() Np = Np_old + int(sp.size(pore_coords) / 3) Nt = Nt_old + int(sp.size(throat_conns) / 2) # Adjust 'all' labels del network['pore.all'], network['throat.all'] network['pore.all'] = sp.ones((Np,), dtype=bool) network['throat.all'] = sp.ones((Nt,), dtype=bool) # Add coords and conns if sp.size(pore_coords) > 0: coords = sp.vstack((network['pore.coords'], pore_coords)) network['pore.coords'] = coords # depends on [control=['if'], data=[]] if sp.size(throat_conns) > 0: conns = sp.vstack((network['throat.conns'], throat_conns)) network['throat.conns'] = conns # depends on [control=['if'], data=[]] # Increase size of any prop or label arrays aready on Network for item in list(network.keys()): if item.split('.')[1] not in ['coords', 'conns', 'all', '_id']: N = network._count(element=item.split('.')[0]) arr = network.pop(item) s = arr.shape network[item] = sp.zeros(shape=(N, *s[1:]), dtype=arr.dtype) # This is a temporary work-around until I learn to handle 2+ dims network[item][:arr.shape[0]] = arr # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['item']] # Apply labels, if supplied if labels != []: # Convert labels to list if necessary if type(labels) is str: labels = [labels] # depends on [control=['if'], data=[]] for label in labels: # Remove pore or throat from label, if present label = label.split('.')[-1] if sp.size(pore_coords) > 0: Ps = sp.r_[Np_old:Np] if 'pore.' + label not in network.labels(): network['pore.' + label] = False # depends on [control=['if'], data=[]] network['pore.' + label][Ps] = True # depends on [control=['if'], data=[]] if sp.size(throat_conns) > 0: Ts = sp.r_[Nt_old:Nt] if 'throat.' + label not in network.labels(): network['throat.' + label] = False # depends on [control=['if'], data=[]] network['throat.' + label][Ts] = True # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['label']] # depends on [control=['if'], data=['labels']] # Clear adjacency and incidence matrices which will be out of date now network._am.clear() network._im.clear()
def get_experiments(base, load=False): ''' get_experiments will return loaded json for all valid experiments from an experiment folder :param base: full path to the base folder with experiments inside :param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to the experiments ''' experiments = find_directories(base) valid_experiments = [e for e in experiments if validate(e,cleanup=False)] bot.info("Found %s valid experiments" %(len(valid_experiments))) if load is True: valid_experiments = load_experiments(valid_experiments) #TODO at some point in this workflow we would want to grab instructions from help # and variables from labels, environment, etc. return valid_experiments
def function[get_experiments, parameter[base, load]]: constant[ get_experiments will return loaded json for all valid experiments from an experiment folder :param base: full path to the base folder with experiments inside :param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to the experiments ] variable[experiments] assign[=] call[name[find_directories], parameter[name[base]]] variable[valid_experiments] assign[=] <ast.ListComp object at 0x7da1b0fa69e0> call[name[bot].info, parameter[binary_operation[constant[Found %s valid experiments] <ast.Mod object at 0x7da2590d6920> call[name[len], parameter[name[valid_experiments]]]]]] if compare[name[load] is constant[True]] begin[:] variable[valid_experiments] assign[=] call[name[load_experiments], parameter[name[valid_experiments]]] return[name[valid_experiments]]
keyword[def] identifier[get_experiments] ( identifier[base] , identifier[load] = keyword[False] ): literal[string] identifier[experiments] = identifier[find_directories] ( identifier[base] ) identifier[valid_experiments] =[ identifier[e] keyword[for] identifier[e] keyword[in] identifier[experiments] keyword[if] identifier[validate] ( identifier[e] , identifier[cleanup] = keyword[False] )] identifier[bot] . identifier[info] ( literal[string] %( identifier[len] ( identifier[valid_experiments] ))) keyword[if] identifier[load] keyword[is] keyword[True] : identifier[valid_experiments] = identifier[load_experiments] ( identifier[valid_experiments] ) keyword[return] identifier[valid_experiments]
def get_experiments(base, load=False): """ get_experiments will return loaded json for all valid experiments from an experiment folder :param base: full path to the base folder with experiments inside :param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to the experiments """ experiments = find_directories(base) valid_experiments = [e for e in experiments if validate(e, cleanup=False)] bot.info('Found %s valid experiments' % len(valid_experiments)) if load is True: valid_experiments = load_experiments(valid_experiments) # depends on [control=['if'], data=[]] #TODO at some point in this workflow we would want to grab instructions from help # and variables from labels, environment, etc. return valid_experiments
def _stream_helper(self, response, decode=False): """Generator for data coming from a chunked-encoded HTTP response.""" if response.raw._fp.chunked: if decode: for chunk in json_stream(self._stream_helper(response, False)): yield chunk else: reader = response.raw while not reader.closed: # this read call will block until we get a chunk data = reader.read(1) if not data: break if reader._fp.chunk_left: data += reader.read(reader._fp.chunk_left) yield data else: # Response isn't chunked, meaning we probably # encountered an error immediately yield self._result(response, json=decode)
def function[_stream_helper, parameter[self, response, decode]]: constant[Generator for data coming from a chunked-encoded HTTP response.] if name[response].raw._fp.chunked begin[:] if name[decode] begin[:] for taget[name[chunk]] in starred[call[name[json_stream], parameter[call[name[self]._stream_helper, parameter[name[response], constant[False]]]]]] begin[:] <ast.Yield object at 0x7da207f010c0>
keyword[def] identifier[_stream_helper] ( identifier[self] , identifier[response] , identifier[decode] = keyword[False] ): literal[string] keyword[if] identifier[response] . identifier[raw] . identifier[_fp] . identifier[chunked] : keyword[if] identifier[decode] : keyword[for] identifier[chunk] keyword[in] identifier[json_stream] ( identifier[self] . identifier[_stream_helper] ( identifier[response] , keyword[False] )): keyword[yield] identifier[chunk] keyword[else] : identifier[reader] = identifier[response] . identifier[raw] keyword[while] keyword[not] identifier[reader] . identifier[closed] : identifier[data] = identifier[reader] . identifier[read] ( literal[int] ) keyword[if] keyword[not] identifier[data] : keyword[break] keyword[if] identifier[reader] . identifier[_fp] . identifier[chunk_left] : identifier[data] += identifier[reader] . identifier[read] ( identifier[reader] . identifier[_fp] . identifier[chunk_left] ) keyword[yield] identifier[data] keyword[else] : keyword[yield] identifier[self] . identifier[_result] ( identifier[response] , identifier[json] = identifier[decode] )
def _stream_helper(self, response, decode=False): """Generator for data coming from a chunked-encoded HTTP response.""" if response.raw._fp.chunked: if decode: for chunk in json_stream(self._stream_helper(response, False)): yield chunk # depends on [control=['for'], data=['chunk']] # depends on [control=['if'], data=[]] else: reader = response.raw while not reader.closed: # this read call will block until we get a chunk data = reader.read(1) if not data: break # depends on [control=['if'], data=[]] if reader._fp.chunk_left: data += reader.read(reader._fp.chunk_left) # depends on [control=['if'], data=[]] yield data # depends on [control=['while'], data=[]] # depends on [control=['if'], data=[]] else: # Response isn't chunked, meaning we probably # encountered an error immediately yield self._result(response, json=decode)
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. """ if semitone > 0 and semitone < 128: self.pianoroll[:, semitone:] = self.pianoroll[:, :(128 - semitone)] self.pianoroll[:, :semitone] = 0 elif semitone < 0 and semitone > -128: self.pianoroll[:, :(128 + semitone)] = self.pianoroll[:, -semitone:] self.pianoroll[:, (128 + semitone):] = 0
def function[transpose, parameter[self, semitone]]: constant[ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. ] if <ast.BoolOp object at 0x7da2043453f0> begin[:] call[name[self].pianoroll][tuple[[<ast.Slice object at 0x7da204346290>, <ast.Slice object at 0x7da2043464a0>]]] assign[=] call[name[self].pianoroll][tuple[[<ast.Slice object at 0x7da2043450c0>, <ast.Slice object at 0x7da204344340>]]] call[name[self].pianoroll][tuple[[<ast.Slice object at 0x7da2047e8cd0>, <ast.Slice object at 0x7da2047e9ae0>]]] assign[=] constant[0]
keyword[def] identifier[transpose] ( identifier[self] , identifier[semitone] ): literal[string] keyword[if] identifier[semitone] > literal[int] keyword[and] identifier[semitone] < literal[int] : identifier[self] . identifier[pianoroll] [:, identifier[semitone] :]= identifier[self] . identifier[pianoroll] [:,:( literal[int] - identifier[semitone] )] identifier[self] . identifier[pianoroll] [:,: identifier[semitone] ]= literal[int] keyword[elif] identifier[semitone] < literal[int] keyword[and] identifier[semitone] >- literal[int] : identifier[self] . identifier[pianoroll] [:,:( literal[int] + identifier[semitone] )]= identifier[self] . identifier[pianoroll] [:,- identifier[semitone] :] identifier[self] . identifier[pianoroll] [:,( literal[int] + identifier[semitone] ):]= literal[int]
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. """ if semitone > 0 and semitone < 128: self.pianoroll[:, semitone:] = self.pianoroll[:, :128 - semitone] self.pianoroll[:, :semitone] = 0 # depends on [control=['if'], data=[]] elif semitone < 0 and semitone > -128: self.pianoroll[:, :128 + semitone] = self.pianoroll[:, -semitone:] self.pianoroll[:, 128 + semitone:] = 0 # depends on [control=['if'], data=[]]
def getNextSample(self, V): """ Given a ranking over the candidates, generate a new ranking by assigning each candidate at position i a Plakett-Luce weight of phi^i and draw a new ranking. :ivar list<int> V: Contains integer representations of each candidate in order of their ranking in a vote, from first to last. """ W, WProb = self.drawRankingPlakettLuce(V) VProb = self.calcProbOfVFromW(V, W) acceptanceRatio = self.calcAcceptanceRatio(V, W) prob = min(1.0, acceptanceRatio * (VProb/WProb)) if random.random() <= prob: V = W return V
def function[getNextSample, parameter[self, V]]: constant[ Given a ranking over the candidates, generate a new ranking by assigning each candidate at position i a Plakett-Luce weight of phi^i and draw a new ranking. :ivar list<int> V: Contains integer representations of each candidate in order of their ranking in a vote, from first to last. ] <ast.Tuple object at 0x7da18ede7be0> assign[=] call[name[self].drawRankingPlakettLuce, parameter[name[V]]] variable[VProb] assign[=] call[name[self].calcProbOfVFromW, parameter[name[V], name[W]]] variable[acceptanceRatio] assign[=] call[name[self].calcAcceptanceRatio, parameter[name[V], name[W]]] variable[prob] assign[=] call[name[min], parameter[constant[1.0], binary_operation[name[acceptanceRatio] * binary_operation[name[VProb] / name[WProb]]]]] if compare[call[name[random].random, parameter[]] less_or_equal[<=] name[prob]] begin[:] variable[V] assign[=] name[W] return[name[V]]
keyword[def] identifier[getNextSample] ( identifier[self] , identifier[V] ): literal[string] identifier[W] , identifier[WProb] = identifier[self] . identifier[drawRankingPlakettLuce] ( identifier[V] ) identifier[VProb] = identifier[self] . identifier[calcProbOfVFromW] ( identifier[V] , identifier[W] ) identifier[acceptanceRatio] = identifier[self] . identifier[calcAcceptanceRatio] ( identifier[V] , identifier[W] ) identifier[prob] = identifier[min] ( literal[int] , identifier[acceptanceRatio] *( identifier[VProb] / identifier[WProb] )) keyword[if] identifier[random] . identifier[random] ()<= identifier[prob] : identifier[V] = identifier[W] keyword[return] identifier[V]
def getNextSample(self, V): """ Given a ranking over the candidates, generate a new ranking by assigning each candidate at position i a Plakett-Luce weight of phi^i and draw a new ranking. :ivar list<int> V: Contains integer representations of each candidate in order of their ranking in a vote, from first to last. """ (W, WProb) = self.drawRankingPlakettLuce(V) VProb = self.calcProbOfVFromW(V, W) acceptanceRatio = self.calcAcceptanceRatio(V, W) prob = min(1.0, acceptanceRatio * (VProb / WProb)) if random.random() <= prob: V = W # depends on [control=['if'], data=[]] return V
def create_2D_grid_simple(self, longitude, latitude, year, magnitude, completeness_table, t_f=1., mag_inc=0.1): ''' Generates the grid from the limits using an approach closer to that of Frankel (1995) :param numpy.ndarray longitude: Vector of earthquake longitudes :param numpy.ndarray latitude: Vector of earthquake latitudes :param numpy.ndarray year: Vector of earthquake years :param numpy.ndarray magnitude: Vector of earthquake magnitudes :param numpy.ndarray completeness_table: Completeness table :param float t_f: Weichert adjustment factor :returns: Two-dimensional spatial grid of observed rates ''' assert mag_inc > 0. xlim = np.ceil( (self.grid_limits['xmax'] - self.grid_limits['xmin']) / self.grid_limits['xspc']) ylim = np.ceil( (self.grid_limits['ymax'] - self.grid_limits['ymin']) / self.grid_limits['yspc']) ncolx = int(xlim) ncoly = int(ylim) grid_count = np.zeros(ncolx * ncoly, dtype=float) for iloc in range(0, len(longitude)): dlon = (longitude[iloc] - self.grid_limits['xmin']) /\ self.grid_limits['xspc'] if (dlon < 0.) or (dlon > xlim): # Earthquake outside longitude limits continue xcol = int(dlon) if xcol == ncolx: # If longitude is directly on upper grid line then retain xcol = ncolx - 1 dlat = fabs(self.grid_limits['ymax'] - latitude[iloc]) /\ self.grid_limits['yspc'] if (dlat < 0.) or (dlat > ylim): # Earthquake outside latitude limits continue ycol = int(dlat) # Correct for floating precision if ycol == ncoly: # If latitude is directly on upper grid line then retain ycol = ncoly - 1 kmarker = (ycol * int(xlim)) + xcol adjust = _get_adjustment(magnitude[iloc], year[iloc], completeness_table[0, 1], completeness_table[:, 0], t_f, mag_inc) if adjust: grid_count[kmarker] = grid_count[kmarker] + adjust return grid_count
def function[create_2D_grid_simple, parameter[self, longitude, latitude, year, magnitude, completeness_table, t_f, mag_inc]]: constant[ Generates the grid from the limits using an approach closer to that of Frankel (1995) :param numpy.ndarray longitude: Vector of earthquake longitudes :param numpy.ndarray latitude: Vector of earthquake latitudes :param numpy.ndarray year: Vector of earthquake years :param numpy.ndarray magnitude: Vector of earthquake magnitudes :param numpy.ndarray completeness_table: Completeness table :param float t_f: Weichert adjustment factor :returns: Two-dimensional spatial grid of observed rates ] assert[compare[name[mag_inc] greater[>] constant[0.0]]] variable[xlim] assign[=] call[name[np].ceil, parameter[binary_operation[binary_operation[call[name[self].grid_limits][constant[xmax]] - call[name[self].grid_limits][constant[xmin]]] / call[name[self].grid_limits][constant[xspc]]]]] variable[ylim] assign[=] call[name[np].ceil, parameter[binary_operation[binary_operation[call[name[self].grid_limits][constant[ymax]] - call[name[self].grid_limits][constant[ymin]]] / call[name[self].grid_limits][constant[yspc]]]]] variable[ncolx] assign[=] call[name[int], parameter[name[xlim]]] variable[ncoly] assign[=] call[name[int], parameter[name[ylim]]] variable[grid_count] assign[=] call[name[np].zeros, parameter[binary_operation[name[ncolx] * name[ncoly]]]] for taget[name[iloc]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[longitude]]]]]] begin[:] variable[dlon] assign[=] binary_operation[binary_operation[call[name[longitude]][name[iloc]] - call[name[self].grid_limits][constant[xmin]]] / call[name[self].grid_limits][constant[xspc]]] if <ast.BoolOp object at 0x7da18bcc8b80> begin[:] continue variable[xcol] assign[=] call[name[int], parameter[name[dlon]]] if compare[name[xcol] equal[==] name[ncolx]] begin[:] variable[xcol] assign[=] binary_operation[name[ncolx] - constant[1]] variable[dlat] assign[=] binary_operation[call[name[fabs], parameter[binary_operation[call[name[self].grid_limits][constant[ymax]] - call[name[latitude]][name[iloc]]]]] / call[name[self].grid_limits][constant[yspc]]] if <ast.BoolOp object at 0x7da18ede6aa0> begin[:] continue variable[ycol] assign[=] call[name[int], parameter[name[dlat]]] if compare[name[ycol] equal[==] name[ncoly]] begin[:] variable[ycol] assign[=] binary_operation[name[ncoly] - constant[1]] variable[kmarker] assign[=] binary_operation[binary_operation[name[ycol] * call[name[int], parameter[name[xlim]]]] + name[xcol]] variable[adjust] assign[=] call[name[_get_adjustment], parameter[call[name[magnitude]][name[iloc]], call[name[year]][name[iloc]], call[name[completeness_table]][tuple[[<ast.Constant object at 0x7da20e957040>, <ast.Constant object at 0x7da20e9577c0>]]], call[name[completeness_table]][tuple[[<ast.Slice object at 0x7da20e954430>, <ast.Constant object at 0x7da20e9553f0>]]], name[t_f], name[mag_inc]]] if name[adjust] begin[:] call[name[grid_count]][name[kmarker]] assign[=] binary_operation[call[name[grid_count]][name[kmarker]] + name[adjust]] return[name[grid_count]]
keyword[def] identifier[create_2D_grid_simple] ( identifier[self] , identifier[longitude] , identifier[latitude] , identifier[year] , identifier[magnitude] , identifier[completeness_table] , identifier[t_f] = literal[int] , identifier[mag_inc] = literal[int] ): literal[string] keyword[assert] identifier[mag_inc] > literal[int] identifier[xlim] = identifier[np] . identifier[ceil] ( ( identifier[self] . identifier[grid_limits] [ literal[string] ]- identifier[self] . identifier[grid_limits] [ literal[string] ])/ identifier[self] . identifier[grid_limits] [ literal[string] ]) identifier[ylim] = identifier[np] . identifier[ceil] ( ( identifier[self] . identifier[grid_limits] [ literal[string] ]- identifier[self] . identifier[grid_limits] [ literal[string] ])/ identifier[self] . identifier[grid_limits] [ literal[string] ]) identifier[ncolx] = identifier[int] ( identifier[xlim] ) identifier[ncoly] = identifier[int] ( identifier[ylim] ) identifier[grid_count] = identifier[np] . identifier[zeros] ( identifier[ncolx] * identifier[ncoly] , identifier[dtype] = identifier[float] ) keyword[for] identifier[iloc] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[longitude] )): identifier[dlon] =( identifier[longitude] [ identifier[iloc] ]- identifier[self] . identifier[grid_limits] [ literal[string] ])/ identifier[self] . identifier[grid_limits] [ literal[string] ] keyword[if] ( identifier[dlon] < literal[int] ) keyword[or] ( identifier[dlon] > identifier[xlim] ): keyword[continue] identifier[xcol] = identifier[int] ( identifier[dlon] ) keyword[if] identifier[xcol] == identifier[ncolx] : identifier[xcol] = identifier[ncolx] - literal[int] identifier[dlat] = identifier[fabs] ( identifier[self] . identifier[grid_limits] [ literal[string] ]- identifier[latitude] [ identifier[iloc] ])/ identifier[self] . identifier[grid_limits] [ literal[string] ] keyword[if] ( identifier[dlat] < literal[int] ) keyword[or] ( identifier[dlat] > identifier[ylim] ): keyword[continue] identifier[ycol] = identifier[int] ( identifier[dlat] ) keyword[if] identifier[ycol] == identifier[ncoly] : identifier[ycol] = identifier[ncoly] - literal[int] identifier[kmarker] =( identifier[ycol] * identifier[int] ( identifier[xlim] ))+ identifier[xcol] identifier[adjust] = identifier[_get_adjustment] ( identifier[magnitude] [ identifier[iloc] ], identifier[year] [ identifier[iloc] ], identifier[completeness_table] [ literal[int] , literal[int] ], identifier[completeness_table] [:, literal[int] ], identifier[t_f] , identifier[mag_inc] ) keyword[if] identifier[adjust] : identifier[grid_count] [ identifier[kmarker] ]= identifier[grid_count] [ identifier[kmarker] ]+ identifier[adjust] keyword[return] identifier[grid_count]
def create_2D_grid_simple(self, longitude, latitude, year, magnitude, completeness_table, t_f=1.0, mag_inc=0.1): """ Generates the grid from the limits using an approach closer to that of Frankel (1995) :param numpy.ndarray longitude: Vector of earthquake longitudes :param numpy.ndarray latitude: Vector of earthquake latitudes :param numpy.ndarray year: Vector of earthquake years :param numpy.ndarray magnitude: Vector of earthquake magnitudes :param numpy.ndarray completeness_table: Completeness table :param float t_f: Weichert adjustment factor :returns: Two-dimensional spatial grid of observed rates """ assert mag_inc > 0.0 xlim = np.ceil((self.grid_limits['xmax'] - self.grid_limits['xmin']) / self.grid_limits['xspc']) ylim = np.ceil((self.grid_limits['ymax'] - self.grid_limits['ymin']) / self.grid_limits['yspc']) ncolx = int(xlim) ncoly = int(ylim) grid_count = np.zeros(ncolx * ncoly, dtype=float) for iloc in range(0, len(longitude)): dlon = (longitude[iloc] - self.grid_limits['xmin']) / self.grid_limits['xspc'] if dlon < 0.0 or dlon > xlim: # Earthquake outside longitude limits continue # depends on [control=['if'], data=[]] xcol = int(dlon) if xcol == ncolx: # If longitude is directly on upper grid line then retain xcol = ncolx - 1 # depends on [control=['if'], data=['xcol', 'ncolx']] dlat = fabs(self.grid_limits['ymax'] - latitude[iloc]) / self.grid_limits['yspc'] if dlat < 0.0 or dlat > ylim: # Earthquake outside latitude limits continue # depends on [control=['if'], data=[]] ycol = int(dlat) # Correct for floating precision if ycol == ncoly: # If latitude is directly on upper grid line then retain ycol = ncoly - 1 # depends on [control=['if'], data=['ycol', 'ncoly']] kmarker = ycol * int(xlim) + xcol adjust = _get_adjustment(magnitude[iloc], year[iloc], completeness_table[0, 1], completeness_table[:, 0], t_f, mag_inc) if adjust: grid_count[kmarker] = grid_count[kmarker] + adjust # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['iloc']] return grid_count
def annotatethreads(self): """ Use prokka to annotate each strain """ # Move the files to subfolders and create objects self.runmetadata = createobject.ObjectCreation(self) # Fix headers self.headers() printtime('Performing prokka analyses', self.start) # Create and start threads for i in range(self.cpus): # Send the threads to the appropriate destination function threads = Thread(target=self.annotate, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() for sample in self.metadata.samples: # Create the prokka attribute in the metadata object setattr(sample, 'prokka', GenObject()) sample.prokka.outputdir = os.path.join(sample.general.outputdirectory, 'prokka') if not os.path.isdir(sample.prokka.outputdir): os.makedirs(sample.prokka.outputdir) # TODO Incorporate MASH/rMLST/user inputted genus, species results in the system call # Create the system call # prokka 2014-SEQ-0275.fasta --force --genus Escherichia --species coli --usegenus --addgenes # --prefix 2014-SEQ-0275 --locustag EC0275 --outputdir /path/to/sequences/2014-SEQ-0275/prokka sample.prokka.command = 'prokka {} ' \ '--force ' \ '--genus {} ' \ '--species {} ' \ '--usegenus ' \ '--addgenes ' \ '--prefix {} ' \ '--locustag {} ' \ '--outdir {}' \ .format(sample.general.fixedheaders, self.genus, self.species, sample.name, sample.name, sample.prokka.outputdir) self.queue.put(sample) self.queue.join()
def function[annotatethreads, parameter[self]]: constant[ Use prokka to annotate each strain ] name[self].runmetadata assign[=] call[name[createobject].ObjectCreation, parameter[name[self]]] call[name[self].headers, parameter[]] call[name[printtime], parameter[constant[Performing prokka analyses], name[self].start]] for taget[name[i]] in starred[call[name[range], parameter[name[self].cpus]]] begin[:] variable[threads] assign[=] call[name[Thread], parameter[]] call[name[threads].setDaemon, parameter[constant[True]]] call[name[threads].start, parameter[]] for taget[name[sample]] in starred[name[self].metadata.samples] begin[:] call[name[setattr], parameter[name[sample], constant[prokka], call[name[GenObject], parameter[]]]] name[sample].prokka.outputdir assign[=] call[name[os].path.join, parameter[name[sample].general.outputdirectory, constant[prokka]]] if <ast.UnaryOp object at 0x7da18bccae00> begin[:] call[name[os].makedirs, parameter[name[sample].prokka.outputdir]] name[sample].prokka.command assign[=] call[constant[prokka {} --force --genus {} --species {} --usegenus --addgenes --prefix {} --locustag {} --outdir {}].format, parameter[name[sample].general.fixedheaders, name[self].genus, name[self].species, name[sample].name, name[sample].name, name[sample].prokka.outputdir]] call[name[self].queue.put, parameter[name[sample]]] call[name[self].queue.join, parameter[]]
keyword[def] identifier[annotatethreads] ( identifier[self] ): literal[string] identifier[self] . identifier[runmetadata] = identifier[createobject] . identifier[ObjectCreation] ( identifier[self] ) identifier[self] . identifier[headers] () identifier[printtime] ( literal[string] , identifier[self] . identifier[start] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[cpus] ): identifier[threads] = identifier[Thread] ( identifier[target] = identifier[self] . identifier[annotate] , identifier[args] =()) identifier[threads] . identifier[setDaemon] ( keyword[True] ) identifier[threads] . identifier[start] () keyword[for] identifier[sample] keyword[in] identifier[self] . identifier[metadata] . identifier[samples] : identifier[setattr] ( identifier[sample] , literal[string] , identifier[GenObject] ()) identifier[sample] . identifier[prokka] . identifier[outputdir] = identifier[os] . identifier[path] . identifier[join] ( identifier[sample] . identifier[general] . identifier[outputdirectory] , literal[string] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[sample] . identifier[prokka] . identifier[outputdir] ): identifier[os] . identifier[makedirs] ( identifier[sample] . identifier[prokka] . identifier[outputdir] ) identifier[sample] . identifier[prokka] . identifier[command] = literal[string] literal[string] literal[string] literal[string] literal[string] literal[string] literal[string] literal[string] literal[string] . identifier[format] ( identifier[sample] . identifier[general] . identifier[fixedheaders] , identifier[self] . identifier[genus] , identifier[self] . identifier[species] , identifier[sample] . identifier[name] , identifier[sample] . identifier[name] , identifier[sample] . identifier[prokka] . identifier[outputdir] ) identifier[self] . identifier[queue] . identifier[put] ( identifier[sample] ) identifier[self] . identifier[queue] . identifier[join] ()
def annotatethreads(self): """ Use prokka to annotate each strain """ # Move the files to subfolders and create objects self.runmetadata = createobject.ObjectCreation(self) # Fix headers self.headers() printtime('Performing prokka analyses', self.start) # Create and start threads for i in range(self.cpus): # Send the threads to the appropriate destination function threads = Thread(target=self.annotate, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() # depends on [control=['for'], data=[]] for sample in self.metadata.samples: # Create the prokka attribute in the metadata object setattr(sample, 'prokka', GenObject()) sample.prokka.outputdir = os.path.join(sample.general.outputdirectory, 'prokka') if not os.path.isdir(sample.prokka.outputdir): os.makedirs(sample.prokka.outputdir) # depends on [control=['if'], data=[]] # TODO Incorporate MASH/rMLST/user inputted genus, species results in the system call # Create the system call # prokka 2014-SEQ-0275.fasta --force --genus Escherichia --species coli --usegenus --addgenes # --prefix 2014-SEQ-0275 --locustag EC0275 --outputdir /path/to/sequences/2014-SEQ-0275/prokka sample.prokka.command = 'prokka {} --force --genus {} --species {} --usegenus --addgenes --prefix {} --locustag {} --outdir {}'.format(sample.general.fixedheaders, self.genus, self.species, sample.name, sample.name, sample.prokka.outputdir) self.queue.put(sample) # depends on [control=['for'], data=['sample']] self.queue.join()