code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def _queue_declare_ok(self, args): """Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ return queue_declare_ok_t( args.read_shortstr(), args.read_long(), args.read_long(), )
def function[_queue_declare_ok, parameter[self, args]]: constant[Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. ] return[call[name[queue_declare_ok_t], parameter[call[name[args].read_shortstr, parameter[]], call[name[args].read_long, parameter[]], call[name[args].read_long, parameter[]]]]]
keyword[def] identifier[_queue_declare_ok] ( identifier[self] , identifier[args] ): literal[string] keyword[return] identifier[queue_declare_ok_t] ( identifier[args] . identifier[read_shortstr] (), identifier[args] . identifier[read_long] (), identifier[args] . identifier[read_long] (), )
def _queue_declare_ok(self, args): """Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ return queue_declare_ok_t(args.read_shortstr(), args.read_long(), args.read_long())
def user_ban(channel, user): """ Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to ban Returns: ui (ui_embed.UI): The embed UI object """ username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick # Create embed UI object gui = ui_embed.UI( channel, "Banned {}".format(username), "{} has been banned from this server".format(username), modulename=modulename ) return gui
def function[user_ban, parameter[channel, user]]: constant[ Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to ban Returns: ui (ui_embed.UI): The embed UI object ] variable[username] assign[=] name[user].name if call[name[isinstance], parameter[name[user], name[discord].Member]] begin[:] if compare[name[user].nick is_not constant[None]] begin[:] variable[username] assign[=] name[user].nick variable[gui] assign[=] call[name[ui_embed].UI, parameter[name[channel], call[constant[Banned {}].format, parameter[name[username]]], call[constant[{} has been banned from this server].format, parameter[name[username]]]]] return[name[gui]]
keyword[def] identifier[user_ban] ( identifier[channel] , identifier[user] ): literal[string] identifier[username] = identifier[user] . identifier[name] keyword[if] identifier[isinstance] ( identifier[user] , identifier[discord] . identifier[Member] ): keyword[if] identifier[user] . identifier[nick] keyword[is] keyword[not] keyword[None] : identifier[username] = identifier[user] . identifier[nick] identifier[gui] = identifier[ui_embed] . identifier[UI] ( identifier[channel] , literal[string] . identifier[format] ( identifier[username] ), literal[string] . identifier[format] ( identifier[username] ), identifier[modulename] = identifier[modulename] ) keyword[return] identifier[gui]
def user_ban(channel, user): """ Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to ban Returns: ui (ui_embed.UI): The embed UI object """ username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Create embed UI object gui = ui_embed.UI(channel, 'Banned {}'.format(username), '{} has been banned from this server'.format(username), modulename=modulename) return gui
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidSeekBar, self).init_widget() w = self.widget #: Setup listener w.setOnSeekBarChangeListener(w.getId()) w.onProgressChanged.connect(self.on_progress_changed)
def function[init_widget, parameter[self]]: constant[ Initialize the underlying widget. ] call[call[name[super], parameter[name[AndroidSeekBar], name[self]]].init_widget, parameter[]] variable[w] assign[=] name[self].widget call[name[w].setOnSeekBarChangeListener, parameter[call[name[w].getId, parameter[]]]] call[name[w].onProgressChanged.connect, parameter[name[self].on_progress_changed]]
keyword[def] identifier[init_widget] ( identifier[self] ): literal[string] identifier[super] ( identifier[AndroidSeekBar] , identifier[self] ). identifier[init_widget] () identifier[w] = identifier[self] . identifier[widget] identifier[w] . identifier[setOnSeekBarChangeListener] ( identifier[w] . identifier[getId] ()) identifier[w] . identifier[onProgressChanged] . identifier[connect] ( identifier[self] . identifier[on_progress_changed] )
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidSeekBar, self).init_widget() w = self.widget #: Setup listener w.setOnSeekBarChangeListener(w.getId()) w.onProgressChanged.connect(self.on_progress_changed)
def list_autoscaling_group(region, filter_by_kwargs): """List all Auto Scaling Groups.""" conn = boto.ec2.autoscale.connect_to_region(region) groups = conn.get_all_groups() return lookup(groups, filter_by=filter_by_kwargs)
def function[list_autoscaling_group, parameter[region, filter_by_kwargs]]: constant[List all Auto Scaling Groups.] variable[conn] assign[=] call[name[boto].ec2.autoscale.connect_to_region, parameter[name[region]]] variable[groups] assign[=] call[name[conn].get_all_groups, parameter[]] return[call[name[lookup], parameter[name[groups]]]]
keyword[def] identifier[list_autoscaling_group] ( identifier[region] , identifier[filter_by_kwargs] ): literal[string] identifier[conn] = identifier[boto] . identifier[ec2] . identifier[autoscale] . identifier[connect_to_region] ( identifier[region] ) identifier[groups] = identifier[conn] . identifier[get_all_groups] () keyword[return] identifier[lookup] ( identifier[groups] , identifier[filter_by] = identifier[filter_by_kwargs] )
def list_autoscaling_group(region, filter_by_kwargs): """List all Auto Scaling Groups.""" conn = boto.ec2.autoscale.connect_to_region(region) groups = conn.get_all_groups() return lookup(groups, filter_by=filter_by_kwargs)
def copy(self, *, continuations: List[memoryview] = None, expected: Sequence[Type['Parseable']] = None, list_expected: Sequence[Type['Parseable']] = None, command_name: bytes = None, uid: bool = None, charset: str = None, tag: bytes = None, max_append_len: int = None, allow_continuations: bool = None) -> 'Params': """Copy the parameters, possibly replacing a subset.""" kwargs: Dict[str, Any] = {} self._set_if_none(kwargs, 'continuations', continuations) self._set_if_none(kwargs, 'expected', expected) self._set_if_none(kwargs, 'list_expected', list_expected) self._set_if_none(kwargs, 'command_name', command_name) self._set_if_none(kwargs, 'uid', uid) self._set_if_none(kwargs, 'charset', charset) self._set_if_none(kwargs, 'tag', tag) self._set_if_none(kwargs, 'max_append_len', max_append_len) self._set_if_none(kwargs, 'allow_continuations', allow_continuations) return Params(**kwargs)
def function[copy, parameter[self]]: constant[Copy the parameters, possibly replacing a subset.] <ast.AnnAssign object at 0x7da18fe90d60> call[name[self]._set_if_none, parameter[name[kwargs], constant[continuations], name[continuations]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[expected], name[expected]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[list_expected], name[list_expected]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[command_name], name[command_name]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[uid], name[uid]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[charset], name[charset]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[tag], name[tag]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[max_append_len], name[max_append_len]]] call[name[self]._set_if_none, parameter[name[kwargs], constant[allow_continuations], name[allow_continuations]]] return[call[name[Params], parameter[]]]
keyword[def] identifier[copy] ( identifier[self] ,*, identifier[continuations] : identifier[List] [ identifier[memoryview] ]= keyword[None] , identifier[expected] : identifier[Sequence] [ identifier[Type] [ literal[string] ]]= keyword[None] , identifier[list_expected] : identifier[Sequence] [ identifier[Type] [ literal[string] ]]= keyword[None] , identifier[command_name] : identifier[bytes] = keyword[None] , identifier[uid] : identifier[bool] = keyword[None] , identifier[charset] : identifier[str] = keyword[None] , identifier[tag] : identifier[bytes] = keyword[None] , identifier[max_append_len] : identifier[int] = keyword[None] , identifier[allow_continuations] : identifier[bool] = keyword[None] )-> literal[string] : literal[string] identifier[kwargs] : identifier[Dict] [ identifier[str] , identifier[Any] ]={} identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[continuations] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[expected] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[list_expected] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[command_name] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[uid] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[charset] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[tag] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[max_append_len] ) identifier[self] . identifier[_set_if_none] ( identifier[kwargs] , literal[string] , identifier[allow_continuations] ) keyword[return] identifier[Params] (** identifier[kwargs] )
def copy(self, *, continuations: List[memoryview]=None, expected: Sequence[Type['Parseable']]=None, list_expected: Sequence[Type['Parseable']]=None, command_name: bytes=None, uid: bool=None, charset: str=None, tag: bytes=None, max_append_len: int=None, allow_continuations: bool=None) -> 'Params': """Copy the parameters, possibly replacing a subset.""" kwargs: Dict[str, Any] = {} self._set_if_none(kwargs, 'continuations', continuations) self._set_if_none(kwargs, 'expected', expected) self._set_if_none(kwargs, 'list_expected', list_expected) self._set_if_none(kwargs, 'command_name', command_name) self._set_if_none(kwargs, 'uid', uid) self._set_if_none(kwargs, 'charset', charset) self._set_if_none(kwargs, 'tag', tag) self._set_if_none(kwargs, 'max_append_len', max_append_len) self._set_if_none(kwargs, 'allow_continuations', allow_continuations) return Params(**kwargs)
def pca(adata, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return plot_scatter(adata, 'pca', **kwargs)
def function[pca, parameter[adata]]: constant[ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. ] return[call[name[plot_scatter], parameter[name[adata], constant[pca]]]]
keyword[def] identifier[pca] ( identifier[adata] ,** identifier[kwargs] )-> identifier[Union] [ identifier[Axes] , identifier[List] [ identifier[Axes] ], keyword[None] ]: literal[string] keyword[return] identifier[plot_scatter] ( identifier[adata] , literal[string] ,** identifier[kwargs] )
def pca(adata, **kwargs) -> Union[Axes, List[Axes], None]: """ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return plot_scatter(adata, 'pca', **kwargs)
def apply(self, doc, split, train, **kwargs): """Extract candidates from the given Context. :param doc: A document to process. :param split: Which split to use. :param train: Whether or not to insert new FeatureKeys. """ logger.debug(f"Document: {doc}") # Get all the candidates in this doc that will be featurized cands_list = get_cands_list_from_split( self.session, self.candidate_classes, doc, split ) feature_map = dict() # Make a flat list of all candidates from the list of list of # candidates. This helps reduce the number of queries needed to update. all_cands = itertools.chain.from_iterable(cands_list) records = list( get_mapping(self.session, Feature, all_cands, get_all_feats, feature_map) ) batch_upsert_records(self.session, Feature, records) # Insert all Feature Keys if train: upsert_keys(self.session, FeatureKey, feature_map) # This return + yield makes a completely empty generator return yield
def function[apply, parameter[self, doc, split, train]]: constant[Extract candidates from the given Context. :param doc: A document to process. :param split: Which split to use. :param train: Whether or not to insert new FeatureKeys. ] call[name[logger].debug, parameter[<ast.JoinedStr object at 0x7da20cabfd00>]] variable[cands_list] assign[=] call[name[get_cands_list_from_split], parameter[name[self].session, name[self].candidate_classes, name[doc], name[split]]] variable[feature_map] assign[=] call[name[dict], parameter[]] variable[all_cands] assign[=] call[name[itertools].chain.from_iterable, parameter[name[cands_list]]] variable[records] assign[=] call[name[list], parameter[call[name[get_mapping], parameter[name[self].session, name[Feature], name[all_cands], name[get_all_feats], name[feature_map]]]]] call[name[batch_upsert_records], parameter[name[self].session, name[Feature], name[records]]] if name[train] begin[:] call[name[upsert_keys], parameter[name[self].session, name[FeatureKey], name[feature_map]]] return[None] <ast.Yield object at 0x7da1b26ac430>
keyword[def] identifier[apply] ( identifier[self] , identifier[doc] , identifier[split] , identifier[train] ,** identifier[kwargs] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] ) identifier[cands_list] = identifier[get_cands_list_from_split] ( identifier[self] . identifier[session] , identifier[self] . identifier[candidate_classes] , identifier[doc] , identifier[split] ) identifier[feature_map] = identifier[dict] () identifier[all_cands] = identifier[itertools] . identifier[chain] . identifier[from_iterable] ( identifier[cands_list] ) identifier[records] = identifier[list] ( identifier[get_mapping] ( identifier[self] . identifier[session] , identifier[Feature] , identifier[all_cands] , identifier[get_all_feats] , identifier[feature_map] ) ) identifier[batch_upsert_records] ( identifier[self] . identifier[session] , identifier[Feature] , identifier[records] ) keyword[if] identifier[train] : identifier[upsert_keys] ( identifier[self] . identifier[session] , identifier[FeatureKey] , identifier[feature_map] ) keyword[return] keyword[yield]
def apply(self, doc, split, train, **kwargs): """Extract candidates from the given Context. :param doc: A document to process. :param split: Which split to use. :param train: Whether or not to insert new FeatureKeys. """ logger.debug(f'Document: {doc}') # Get all the candidates in this doc that will be featurized cands_list = get_cands_list_from_split(self.session, self.candidate_classes, doc, split) feature_map = dict() # Make a flat list of all candidates from the list of list of # candidates. This helps reduce the number of queries needed to update. all_cands = itertools.chain.from_iterable(cands_list) records = list(get_mapping(self.session, Feature, all_cands, get_all_feats, feature_map)) batch_upsert_records(self.session, Feature, records) # Insert all Feature Keys if train: upsert_keys(self.session, FeatureKey, feature_map) # depends on [control=['if'], data=[]] # This return + yield makes a completely empty generator return yield
def presence_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_presence_callback( type_, from_, cb, ) try: yield finally: stream.unregister_presence_callback( type_, from_, )
def function[presence_handler, parameter[stream, type_, from_, cb]]: constant[ Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 ] call[name[stream].register_presence_callback, parameter[name[type_], name[from_], name[cb]]] <ast.Try object at 0x7da20c6aace0>
keyword[def] identifier[presence_handler] ( identifier[stream] , identifier[type_] , identifier[from_] , identifier[cb] ): literal[string] identifier[stream] . identifier[register_presence_callback] ( identifier[type_] , identifier[from_] , identifier[cb] , ) keyword[try] : keyword[yield] keyword[finally] : identifier[stream] . identifier[unregister_presence_callback] ( identifier[type_] , identifier[from_] , )
def presence_handler(stream, type_, from_, cb): """ Context manager to temporarily register a callback to handle presence stanzas on a :class:`StanzaStream`. :param stream: Stanza stream to register the coroutine at :type stream: :class:`StanzaStream` :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or :data:`None`. :param cb: Callback to register The callback is registered when the context is entered and unregistered when the context is exited. .. versionadded:: 0.8 """ stream.register_presence_callback(type_, from_, cb) try: yield # depends on [control=['try'], data=[]] finally: stream.unregister_presence_callback(type_, from_)
def run_cmd(command, verbose=True, shell='/bin/bash'): """internal helper function to run shell commands and get output""" process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full output including empty lines return output return [line for line in output if line.strip()]
def function[run_cmd, parameter[command, verbose, shell]]: constant[internal helper function to run shell commands and get output] variable[process] assign[=] call[name[Popen], parameter[name[command]]] variable[output] assign[=] call[call[call[call[name[process].stdout.read, parameter[]].decode, parameter[]].strip, parameter[]].split, parameter[constant[ ]]] if name[verbose] begin[:] return[name[output]] return[<ast.ListComp object at 0x7da1b26aef50>]
keyword[def] identifier[run_cmd] ( identifier[command] , identifier[verbose] = keyword[True] , identifier[shell] = literal[string] ): literal[string] identifier[process] = identifier[Popen] ( identifier[command] , identifier[shell] = keyword[True] , identifier[stdout] = identifier[PIPE] , identifier[stderr] = identifier[STDOUT] , identifier[executable] = identifier[shell] ) identifier[output] = identifier[process] . identifier[stdout] . identifier[read] (). identifier[decode] (). identifier[strip] (). identifier[split] ( literal[string] ) keyword[if] identifier[verbose] : keyword[return] identifier[output] keyword[return] [ identifier[line] keyword[for] identifier[line] keyword[in] identifier[output] keyword[if] identifier[line] . identifier[strip] ()]
def run_cmd(command, verbose=True, shell='/bin/bash'): """internal helper function to run shell commands and get output""" process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full output including empty lines return output # depends on [control=['if'], data=[]] return [line for line in output if line.strip()]
def interrupt_kernel(self, kernel_id): """Interrupt a kernel.""" self._check_kernel_id(kernel_id) super(MappingKernelManager, self).interrupt_kernel(kernel_id) self.log.info("Kernel interrupted: %s" % kernel_id)
def function[interrupt_kernel, parameter[self, kernel_id]]: constant[Interrupt a kernel.] call[name[self]._check_kernel_id, parameter[name[kernel_id]]] call[call[name[super], parameter[name[MappingKernelManager], name[self]]].interrupt_kernel, parameter[name[kernel_id]]] call[name[self].log.info, parameter[binary_operation[constant[Kernel interrupted: %s] <ast.Mod object at 0x7da2590d6920> name[kernel_id]]]]
keyword[def] identifier[interrupt_kernel] ( identifier[self] , identifier[kernel_id] ): literal[string] identifier[self] . identifier[_check_kernel_id] ( identifier[kernel_id] ) identifier[super] ( identifier[MappingKernelManager] , identifier[self] ). identifier[interrupt_kernel] ( identifier[kernel_id] ) identifier[self] . identifier[log] . identifier[info] ( literal[string] % identifier[kernel_id] )
def interrupt_kernel(self, kernel_id): """Interrupt a kernel.""" self._check_kernel_id(kernel_id) super(MappingKernelManager, self).interrupt_kernel(kernel_id) self.log.info('Kernel interrupted: %s' % kernel_id)
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x}{self._suffix}', delete=delete)
def function[load_state, parameter[self, state_id, delete]]: constant[ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State ] return[call[name[self]._store.load_state, parameter[<ast.JoinedStr object at 0x7da20c76eec0>]]]
keyword[def] identifier[load_state] ( identifier[self] , identifier[state_id] , identifier[delete] = keyword[True] ): literal[string] keyword[return] identifier[self] . identifier[_store] . identifier[load_state] ( literal[string] , identifier[delete] = identifier[delete] )
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x}{self._suffix}', delete=delete)
def transform(self, X, y=None): """Transform documents to document ids. Uses the vocabulary learned by fit. Args: X : iterable an iterable which yields either str, unicode or file objects. y : iterabl, label strings. Returns: features: document id matrix. y: label id matrix. """ word_ids = [self._word_vocab.doc2id(doc) for doc in X] word_ids = pad_sequences(word_ids, padding='post') if self._use_char: char_ids = [[self._char_vocab.doc2id(w) for w in doc] for doc in X] char_ids = pad_nested_sequences(char_ids) features = [word_ids, char_ids] else: features = word_ids if y is not None: y = [self._label_vocab.doc2id(doc) for doc in y] y = pad_sequences(y, padding='post') y = to_categorical(y, self.label_size).astype(int) # In 2018/06/01, to_categorical is a bit strange. # >>> to_categorical([[1,3]], num_classes=4).shape # (1, 2, 4) # >>> to_categorical([[1]], num_classes=4).shape # (1, 4) # So, I expand dimensions when len(y.shape) == 2. y = y if len(y.shape) == 3 else np.expand_dims(y, axis=0) return features, y else: return features
def function[transform, parameter[self, X, y]]: constant[Transform documents to document ids. Uses the vocabulary learned by fit. Args: X : iterable an iterable which yields either str, unicode or file objects. y : iterabl, label strings. Returns: features: document id matrix. y: label id matrix. ] variable[word_ids] assign[=] <ast.ListComp object at 0x7da1b1bcbac0> variable[word_ids] assign[=] call[name[pad_sequences], parameter[name[word_ids]]] if name[self]._use_char begin[:] variable[char_ids] assign[=] <ast.ListComp object at 0x7da1b1bcb970> variable[char_ids] assign[=] call[name[pad_nested_sequences], parameter[name[char_ids]]] variable[features] assign[=] list[[<ast.Name object at 0x7da1b1bc9270>, <ast.Name object at 0x7da1b1bca650>]] if compare[name[y] is_not constant[None]] begin[:] variable[y] assign[=] <ast.ListComp object at 0x7da1b1bab910> variable[y] assign[=] call[name[pad_sequences], parameter[name[y]]] variable[y] assign[=] call[call[name[to_categorical], parameter[name[y], name[self].label_size]].astype, parameter[name[int]]] variable[y] assign[=] <ast.IfExp object at 0x7da1b1bab460> return[tuple[[<ast.Name object at 0x7da1b1bab130>, <ast.Name object at 0x7da1b1babdc0>]]]
keyword[def] identifier[transform] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] ): literal[string] identifier[word_ids] =[ identifier[self] . identifier[_word_vocab] . identifier[doc2id] ( identifier[doc] ) keyword[for] identifier[doc] keyword[in] identifier[X] ] identifier[word_ids] = identifier[pad_sequences] ( identifier[word_ids] , identifier[padding] = literal[string] ) keyword[if] identifier[self] . identifier[_use_char] : identifier[char_ids] =[[ identifier[self] . identifier[_char_vocab] . identifier[doc2id] ( identifier[w] ) keyword[for] identifier[w] keyword[in] identifier[doc] ] keyword[for] identifier[doc] keyword[in] identifier[X] ] identifier[char_ids] = identifier[pad_nested_sequences] ( identifier[char_ids] ) identifier[features] =[ identifier[word_ids] , identifier[char_ids] ] keyword[else] : identifier[features] = identifier[word_ids] keyword[if] identifier[y] keyword[is] keyword[not] keyword[None] : identifier[y] =[ identifier[self] . identifier[_label_vocab] . identifier[doc2id] ( identifier[doc] ) keyword[for] identifier[doc] keyword[in] identifier[y] ] identifier[y] = identifier[pad_sequences] ( identifier[y] , identifier[padding] = literal[string] ) identifier[y] = identifier[to_categorical] ( identifier[y] , identifier[self] . identifier[label_size] ). identifier[astype] ( identifier[int] ) identifier[y] = identifier[y] keyword[if] identifier[len] ( identifier[y] . identifier[shape] )== literal[int] keyword[else] identifier[np] . identifier[expand_dims] ( identifier[y] , identifier[axis] = literal[int] ) keyword[return] identifier[features] , identifier[y] keyword[else] : keyword[return] identifier[features]
def transform(self, X, y=None): """Transform documents to document ids. Uses the vocabulary learned by fit. Args: X : iterable an iterable which yields either str, unicode or file objects. y : iterabl, label strings. Returns: features: document id matrix. y: label id matrix. """ word_ids = [self._word_vocab.doc2id(doc) for doc in X] word_ids = pad_sequences(word_ids, padding='post') if self._use_char: char_ids = [[self._char_vocab.doc2id(w) for w in doc] for doc in X] char_ids = pad_nested_sequences(char_ids) features = [word_ids, char_ids] # depends on [control=['if'], data=[]] else: features = word_ids if y is not None: y = [self._label_vocab.doc2id(doc) for doc in y] y = pad_sequences(y, padding='post') y = to_categorical(y, self.label_size).astype(int) # In 2018/06/01, to_categorical is a bit strange. # >>> to_categorical([[1,3]], num_classes=4).shape # (1, 2, 4) # >>> to_categorical([[1]], num_classes=4).shape # (1, 4) # So, I expand dimensions when len(y.shape) == 2. y = y if len(y.shape) == 3 else np.expand_dims(y, axis=0) return (features, y) # depends on [control=['if'], data=['y']] else: return features
def get_queue(queue, flags=FLAGS.ALL, **conn): """ Orchestrates all the calls required to fully fetch details about an SQS Queue: { "Arn": ..., "Region": ..., "Name": ..., "Url": ..., "Attributes": ..., "Tags": ..., "DeadLetterSourceQueues": ..., "_version": 1 } :param queue: Either the queue name OR the queue url :param flags: By default, set to ALL fields. :param conn: dict containing enough information to make a connection to the desired account. Must at least have 'assume_role' key. :return: dict containing a fully built out SQS queue. """ # Check if this is a Queue URL or a queue name: if queue.startswith("https://") or queue.startswith("http://"): queue_name = queue else: queue_name = get_queue_url(QueueName=queue, **conn) sqs_queue = {"QueueUrl": queue_name} return registry.build_out(flags, sqs_queue, **conn)
def function[get_queue, parameter[queue, flags]]: constant[ Orchestrates all the calls required to fully fetch details about an SQS Queue: { "Arn": ..., "Region": ..., "Name": ..., "Url": ..., "Attributes": ..., "Tags": ..., "DeadLetterSourceQueues": ..., "_version": 1 } :param queue: Either the queue name OR the queue url :param flags: By default, set to ALL fields. :param conn: dict containing enough information to make a connection to the desired account. Must at least have 'assume_role' key. :return: dict containing a fully built out SQS queue. ] if <ast.BoolOp object at 0x7da1b01c3ca0> begin[:] variable[queue_name] assign[=] name[queue] variable[sqs_queue] assign[=] dictionary[[<ast.Constant object at 0x7da1b01c0fa0>], [<ast.Name object at 0x7da1b01c0700>]] return[call[name[registry].build_out, parameter[name[flags], name[sqs_queue]]]]
keyword[def] identifier[get_queue] ( identifier[queue] , identifier[flags] = identifier[FLAGS] . identifier[ALL] ,** identifier[conn] ): literal[string] keyword[if] identifier[queue] . identifier[startswith] ( literal[string] ) keyword[or] identifier[queue] . identifier[startswith] ( literal[string] ): identifier[queue_name] = identifier[queue] keyword[else] : identifier[queue_name] = identifier[get_queue_url] ( identifier[QueueName] = identifier[queue] ,** identifier[conn] ) identifier[sqs_queue] ={ literal[string] : identifier[queue_name] } keyword[return] identifier[registry] . identifier[build_out] ( identifier[flags] , identifier[sqs_queue] ,** identifier[conn] )
def get_queue(queue, flags=FLAGS.ALL, **conn): """ Orchestrates all the calls required to fully fetch details about an SQS Queue: { "Arn": ..., "Region": ..., "Name": ..., "Url": ..., "Attributes": ..., "Tags": ..., "DeadLetterSourceQueues": ..., "_version": 1 } :param queue: Either the queue name OR the queue url :param flags: By default, set to ALL fields. :param conn: dict containing enough information to make a connection to the desired account. Must at least have 'assume_role' key. :return: dict containing a fully built out SQS queue. """ # Check if this is a Queue URL or a queue name: if queue.startswith('https://') or queue.startswith('http://'): queue_name = queue # depends on [control=['if'], data=[]] else: queue_name = get_queue_url(QueueName=queue, **conn) sqs_queue = {'QueueUrl': queue_name} return registry.build_out(flags, sqs_queue, **conn)
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(self.backend, mount_point=self.path, description=self.description, config=a_obj) elif self.description: m_fun(self.backend, mount_point=self.path, description=self.description) elif a_obj: m_fun(self.backend, mount_point=self.path, config=a_obj) else: m_fun(self.backend, mount_point=self.path) except hvac.exceptions.InvalidRequest as exception: match = re.match('existing mount at (?P<path>.+)', str(exception)) if match: e_msg = "%s has a mountpoint conflict with %s" % \ (self.path, match.group('path')) raise aomi_excep.VaultConstraint(e_msg) else: raise
def function[actually_mount, parameter[self, client]]: constant[Actually mount something in Vault] variable[a_obj] assign[=] call[name[self].config.copy, parameter[]] if compare[constant[description] in name[a_obj]] begin[:] <ast.Delete object at 0x7da18c4ced70> <ast.Try object at 0x7da18c4cf190>
keyword[def] identifier[actually_mount] ( identifier[self] , identifier[client] ): literal[string] identifier[a_obj] = identifier[self] . identifier[config] . identifier[copy] () keyword[if] literal[string] keyword[in] identifier[a_obj] : keyword[del] identifier[a_obj] [ literal[string] ] keyword[try] : identifier[m_fun] = identifier[getattr] ( identifier[client] , identifier[self] . identifier[mount_fun] ) keyword[if] identifier[self] . identifier[description] keyword[and] identifier[a_obj] : identifier[m_fun] ( identifier[self] . identifier[backend] , identifier[mount_point] = identifier[self] . identifier[path] , identifier[description] = identifier[self] . identifier[description] , identifier[config] = identifier[a_obj] ) keyword[elif] identifier[self] . identifier[description] : identifier[m_fun] ( identifier[self] . identifier[backend] , identifier[mount_point] = identifier[self] . identifier[path] , identifier[description] = identifier[self] . identifier[description] ) keyword[elif] identifier[a_obj] : identifier[m_fun] ( identifier[self] . identifier[backend] , identifier[mount_point] = identifier[self] . identifier[path] , identifier[config] = identifier[a_obj] ) keyword[else] : identifier[m_fun] ( identifier[self] . identifier[backend] , identifier[mount_point] = identifier[self] . identifier[path] ) keyword[except] identifier[hvac] . identifier[exceptions] . identifier[InvalidRequest] keyword[as] identifier[exception] : identifier[match] = identifier[re] . identifier[match] ( literal[string] , identifier[str] ( identifier[exception] )) keyword[if] identifier[match] : identifier[e_msg] = literal[string] %( identifier[self] . identifier[path] , identifier[match] . identifier[group] ( literal[string] )) keyword[raise] identifier[aomi_excep] . identifier[VaultConstraint] ( identifier[e_msg] ) keyword[else] : keyword[raise]
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] # depends on [control=['if'], data=['a_obj']] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(self.backend, mount_point=self.path, description=self.description, config=a_obj) # depends on [control=['if'], data=[]] elif self.description: m_fun(self.backend, mount_point=self.path, description=self.description) # depends on [control=['if'], data=[]] elif a_obj: m_fun(self.backend, mount_point=self.path, config=a_obj) # depends on [control=['if'], data=[]] else: m_fun(self.backend, mount_point=self.path) # depends on [control=['try'], data=[]] except hvac.exceptions.InvalidRequest as exception: match = re.match('existing mount at (?P<path>.+)', str(exception)) if match: e_msg = '%s has a mountpoint conflict with %s' % (self.path, match.group('path')) raise aomi_excep.VaultConstraint(e_msg) # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['exception']]
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) it, = itertools.tee(obj, 1) s = set() too_big = False for i, v in enumerate(it): if i <= max_iterable_length: s.add(type(v)) else: too_big = True break return {"types": s, "too_big": too_big}
def function[get_types, parameter[obj]]: constant[Get the types of an iterable.] variable[max_iterable_length] assign[=] call[name[kwargs].get, parameter[constant[max_iterable_length], constant[100000]]] <ast.Tuple object at 0x7da20c991630> assign[=] call[name[itertools].tee, parameter[name[obj], constant[1]]] variable[s] assign[=] call[name[set], parameter[]] variable[too_big] assign[=] constant[False] for taget[tuple[[<ast.Name object at 0x7da20c993e80>, <ast.Name object at 0x7da20c9919c0>]]] in starred[call[name[enumerate], parameter[name[it]]]] begin[:] if compare[name[i] less_or_equal[<=] name[max_iterable_length]] begin[:] call[name[s].add, parameter[call[name[type], parameter[name[v]]]]] return[dictionary[[<ast.Constant object at 0x7da20c990a00>, <ast.Constant object at 0x7da20c9932b0>], [<ast.Name object at 0x7da20c992aa0>, <ast.Name object at 0x7da20c993550>]]]
keyword[def] identifier[get_types] ( identifier[obj] ,** identifier[kwargs] ): literal[string] identifier[max_iterable_length] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] ) identifier[it] ,= identifier[itertools] . identifier[tee] ( identifier[obj] , literal[int] ) identifier[s] = identifier[set] () identifier[too_big] = keyword[False] keyword[for] identifier[i] , identifier[v] keyword[in] identifier[enumerate] ( identifier[it] ): keyword[if] identifier[i] <= identifier[max_iterable_length] : identifier[s] . identifier[add] ( identifier[type] ( identifier[v] )) keyword[else] : identifier[too_big] = keyword[True] keyword[break] keyword[return] { literal[string] : identifier[s] , literal[string] : identifier[too_big] }
def get_types(obj, **kwargs): """Get the types of an iterable.""" max_iterable_length = kwargs.get('max_iterable_length', 100000) (it,) = itertools.tee(obj, 1) s = set() too_big = False for (i, v) in enumerate(it): if i <= max_iterable_length: s.add(type(v)) # depends on [control=['if'], data=[]] else: too_big = True break # depends on [control=['for'], data=[]] return {'types': s, 'too_big': too_big}
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr): """One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple).""" # kws_plt -> go2color go2bordercolor kws_plt, kws_dag = self._get_kws_plt(self.grprobj.usrgos, **kws_usr) pltgosusr = self.grprobj.usrgos if exclude_hdrs is not None: pltgosusr = pltgosusr.difference(self.grprobj.get_usrgos_g_hdrgos(exclude_hdrs)) if fout_img is None: fout_img = "{GRP_NAME}.png".format(GRP_NAME=self.grprobj.grpname) # Split one plot into potentially three (BP, MF, CC) if png filename contains '{NS}' if '{NS}' in fout_img: go2nt = self.grprobj.gosubdag.get_go2nt(pltgosusr) for namespace in ['BP', 'MF', 'CC']: pltgos_ns = [go for go in pltgosusr if go2nt[go].NS == namespace] if pltgos_ns: png = fout_img.format(NS=namespace) self._plot_grouped_gos(png, pltgos_ns, kws_plt, kws_dag) # Plot all user GO IDs into a single plot, regardless of their namespace else: self._plot_grouped_gos(fout_img, pltgosusr, kws_plt, kws_dag)
def function[plot_grouped_gos, parameter[self, fout_img, exclude_hdrs]]: constant[One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple).] <ast.Tuple object at 0x7da1b26ac250> assign[=] call[name[self]._get_kws_plt, parameter[name[self].grprobj.usrgos]] variable[pltgosusr] assign[=] name[self].grprobj.usrgos if compare[name[exclude_hdrs] is_not constant[None]] begin[:] variable[pltgosusr] assign[=] call[name[pltgosusr].difference, parameter[call[name[self].grprobj.get_usrgos_g_hdrgos, parameter[name[exclude_hdrs]]]]] if compare[name[fout_img] is constant[None]] begin[:] variable[fout_img] assign[=] call[constant[{GRP_NAME}.png].format, parameter[]] if compare[constant[{NS}] in name[fout_img]] begin[:] variable[go2nt] assign[=] call[name[self].grprobj.gosubdag.get_go2nt, parameter[name[pltgosusr]]] for taget[name[namespace]] in starred[list[[<ast.Constant object at 0x7da1b26ae860>, <ast.Constant object at 0x7da1b26acee0>, <ast.Constant object at 0x7da1b26ad300>]]] begin[:] variable[pltgos_ns] assign[=] <ast.ListComp object at 0x7da1b26ac610> if name[pltgos_ns] begin[:] variable[png] assign[=] call[name[fout_img].format, parameter[]] call[name[self]._plot_grouped_gos, parameter[name[png], name[pltgos_ns], name[kws_plt], name[kws_dag]]]
keyword[def] identifier[plot_grouped_gos] ( identifier[self] , identifier[fout_img] = keyword[None] , identifier[exclude_hdrs] = keyword[None] ,** identifier[kws_usr] ): literal[string] identifier[kws_plt] , identifier[kws_dag] = identifier[self] . identifier[_get_kws_plt] ( identifier[self] . identifier[grprobj] . identifier[usrgos] ,** identifier[kws_usr] ) identifier[pltgosusr] = identifier[self] . identifier[grprobj] . identifier[usrgos] keyword[if] identifier[exclude_hdrs] keyword[is] keyword[not] keyword[None] : identifier[pltgosusr] = identifier[pltgosusr] . identifier[difference] ( identifier[self] . identifier[grprobj] . identifier[get_usrgos_g_hdrgos] ( identifier[exclude_hdrs] )) keyword[if] identifier[fout_img] keyword[is] keyword[None] : identifier[fout_img] = literal[string] . identifier[format] ( identifier[GRP_NAME] = identifier[self] . identifier[grprobj] . identifier[grpname] ) keyword[if] literal[string] keyword[in] identifier[fout_img] : identifier[go2nt] = identifier[self] . identifier[grprobj] . identifier[gosubdag] . identifier[get_go2nt] ( identifier[pltgosusr] ) keyword[for] identifier[namespace] keyword[in] [ literal[string] , literal[string] , literal[string] ]: identifier[pltgos_ns] =[ identifier[go] keyword[for] identifier[go] keyword[in] identifier[pltgosusr] keyword[if] identifier[go2nt] [ identifier[go] ]. identifier[NS] == identifier[namespace] ] keyword[if] identifier[pltgos_ns] : identifier[png] = identifier[fout_img] . identifier[format] ( identifier[NS] = identifier[namespace] ) identifier[self] . identifier[_plot_grouped_gos] ( identifier[png] , identifier[pltgos_ns] , identifier[kws_plt] , identifier[kws_dag] ) keyword[else] : identifier[self] . identifier[_plot_grouped_gos] ( identifier[fout_img] , identifier[pltgosusr] , identifier[kws_plt] , identifier[kws_dag] )
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr): """One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple).""" # kws_plt -> go2color go2bordercolor (kws_plt, kws_dag) = self._get_kws_plt(self.grprobj.usrgos, **kws_usr) pltgosusr = self.grprobj.usrgos if exclude_hdrs is not None: pltgosusr = pltgosusr.difference(self.grprobj.get_usrgos_g_hdrgos(exclude_hdrs)) # depends on [control=['if'], data=['exclude_hdrs']] if fout_img is None: fout_img = '{GRP_NAME}.png'.format(GRP_NAME=self.grprobj.grpname) # depends on [control=['if'], data=['fout_img']] # Split one plot into potentially three (BP, MF, CC) if png filename contains '{NS}' if '{NS}' in fout_img: go2nt = self.grprobj.gosubdag.get_go2nt(pltgosusr) for namespace in ['BP', 'MF', 'CC']: pltgos_ns = [go for go in pltgosusr if go2nt[go].NS == namespace] if pltgos_ns: png = fout_img.format(NS=namespace) self._plot_grouped_gos(png, pltgos_ns, kws_plt, kws_dag) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['namespace']] # depends on [control=['if'], data=['fout_img']] else: # Plot all user GO IDs into a single plot, regardless of their namespace self._plot_grouped_gos(fout_img, pltgosusr, kws_plt, kws_dag)
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval_max_num_noops, hparams.rl_env_max_episode_steps, env_name=hparams.rl_env_name) env.start_new_epoch(0) return rl.make_real_env_fn(env)
def function[initialize_env_specs, parameter[hparams, env_problem_name]]: constant[Initializes env_specs using the appropriate env.] if name[env_problem_name] begin[:] variable[env] assign[=] call[name[registry].env_problem, parameter[name[env_problem_name]]] return[call[name[rl].make_real_env_fn, parameter[name[env]]]]
keyword[def] identifier[initialize_env_specs] ( identifier[hparams] , identifier[env_problem_name] ): literal[string] keyword[if] identifier[env_problem_name] : identifier[env] = identifier[registry] . identifier[env_problem] ( identifier[env_problem_name] , identifier[batch_size] = identifier[hparams] . identifier[batch_size] ) keyword[else] : identifier[env] = identifier[rl_utils] . identifier[setup_env] ( identifier[hparams] , identifier[hparams] . identifier[batch_size] , identifier[hparams] . identifier[eval_max_num_noops] , identifier[hparams] . identifier[rl_env_max_episode_steps] , identifier[env_name] = identifier[hparams] . identifier[rl_env_name] ) identifier[env] . identifier[start_new_epoch] ( literal[int] ) keyword[return] identifier[rl] . identifier[make_real_env_fn] ( identifier[env] )
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) # depends on [control=['if'], data=[]] else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval_max_num_noops, hparams.rl_env_max_episode_steps, env_name=hparams.rl_env_name) env.start_new_epoch(0) return rl.make_real_env_fn(env)
def make_pre_authed_request(self, env, method=None, path=None, body=None, headers=None): """Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swift_source as a kwarg, but we do it this way so we don't have to have a newer Swift. Since we're doing this anyway, we may as well set the user agent too since we always do that. """ if self.default_storage_policy: sp = self.default_storage_policy if headers: headers.update({'X-Storage-Policy': sp}) else: headers = {'X-Storage-Policy': sp} subreq = swift.common.wsgi.make_pre_authed_request( env, method=method, path=path, body=body, headers=headers, agent=self.agent) subreq.environ['swift.source'] = self.swift_source return subreq
def function[make_pre_authed_request, parameter[self, env, method, path, body, headers]]: constant[Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swift_source as a kwarg, but we do it this way so we don't have to have a newer Swift. Since we're doing this anyway, we may as well set the user agent too since we always do that. ] if name[self].default_storage_policy begin[:] variable[sp] assign[=] name[self].default_storage_policy if name[headers] begin[:] call[name[headers].update, parameter[dictionary[[<ast.Constant object at 0x7da20c6a9fc0>], [<ast.Name object at 0x7da20c6a9090>]]]] variable[subreq] assign[=] call[name[swift].common.wsgi.make_pre_authed_request, parameter[name[env]]] call[name[subreq].environ][constant[swift.source]] assign[=] name[self].swift_source return[name[subreq]]
keyword[def] identifier[make_pre_authed_request] ( identifier[self] , identifier[env] , identifier[method] = keyword[None] , identifier[path] = keyword[None] , identifier[body] = keyword[None] , identifier[headers] = keyword[None] ): literal[string] keyword[if] identifier[self] . identifier[default_storage_policy] : identifier[sp] = identifier[self] . identifier[default_storage_policy] keyword[if] identifier[headers] : identifier[headers] . identifier[update] ({ literal[string] : identifier[sp] }) keyword[else] : identifier[headers] ={ literal[string] : identifier[sp] } identifier[subreq] = identifier[swift] . identifier[common] . identifier[wsgi] . identifier[make_pre_authed_request] ( identifier[env] , identifier[method] = identifier[method] , identifier[path] = identifier[path] , identifier[body] = identifier[body] , identifier[headers] = identifier[headers] , identifier[agent] = identifier[self] . identifier[agent] ) identifier[subreq] . identifier[environ] [ literal[string] ]= identifier[self] . identifier[swift_source] keyword[return] identifier[subreq]
def make_pre_authed_request(self, env, method=None, path=None, body=None, headers=None): """Nearly the same as swift.common.wsgi.make_pre_authed_request except that this also always sets the 'swift.source' and user agent. Newer Swift code will support swift_source as a kwarg, but we do it this way so we don't have to have a newer Swift. Since we're doing this anyway, we may as well set the user agent too since we always do that. """ if self.default_storage_policy: sp = self.default_storage_policy if headers: headers.update({'X-Storage-Policy': sp}) # depends on [control=['if'], data=[]] else: headers = {'X-Storage-Policy': sp} # depends on [control=['if'], data=[]] subreq = swift.common.wsgi.make_pre_authed_request(env, method=method, path=path, body=body, headers=headers, agent=self.agent) subreq.environ['swift.source'] = self.swift_source return subreq
def start(cls, ev=None): """ Start the query to aleph by ISSN. """ ViewController.log_view.add("Beginning AlephReader request..") ViewController.issnbox_error.reset() issn = ViewController.issn.strip() # make sure, that `issn` was filled if not issn: ViewController.issnbox_error.show("ISSN nebylo vyplněno!") ViewController.log_view.add("No ISSN! Aborting.") return ViewController.issnbox_error.hide() ViewController.issn_progressbar.reset() ViewController.issn_progressbar.show(50) ViewController.log_view.add("For ISSN `%s`." % issn) make_request( url=join(settings.API_PATH, "aleph/records_by_issn"), data={'issn': issn}, on_complete=cls.on_complete )
def function[start, parameter[cls, ev]]: constant[ Start the query to aleph by ISSN. ] call[name[ViewController].log_view.add, parameter[constant[Beginning AlephReader request..]]] call[name[ViewController].issnbox_error.reset, parameter[]] variable[issn] assign[=] call[name[ViewController].issn.strip, parameter[]] if <ast.UnaryOp object at 0x7da18bcc9300> begin[:] call[name[ViewController].issnbox_error.show, parameter[constant[ISSN nebylo vyplněno!]]] call[name[ViewController].log_view.add, parameter[constant[No ISSN! Aborting.]]] return[None] call[name[ViewController].issnbox_error.hide, parameter[]] call[name[ViewController].issn_progressbar.reset, parameter[]] call[name[ViewController].issn_progressbar.show, parameter[constant[50]]] call[name[ViewController].log_view.add, parameter[binary_operation[constant[For ISSN `%s`.] <ast.Mod object at 0x7da2590d6920> name[issn]]]] call[name[make_request], parameter[]]
keyword[def] identifier[start] ( identifier[cls] , identifier[ev] = keyword[None] ): literal[string] identifier[ViewController] . identifier[log_view] . identifier[add] ( literal[string] ) identifier[ViewController] . identifier[issnbox_error] . identifier[reset] () identifier[issn] = identifier[ViewController] . identifier[issn] . identifier[strip] () keyword[if] keyword[not] identifier[issn] : identifier[ViewController] . identifier[issnbox_error] . identifier[show] ( literal[string] ) identifier[ViewController] . identifier[log_view] . identifier[add] ( literal[string] ) keyword[return] identifier[ViewController] . identifier[issnbox_error] . identifier[hide] () identifier[ViewController] . identifier[issn_progressbar] . identifier[reset] () identifier[ViewController] . identifier[issn_progressbar] . identifier[show] ( literal[int] ) identifier[ViewController] . identifier[log_view] . identifier[add] ( literal[string] % identifier[issn] ) identifier[make_request] ( identifier[url] = identifier[join] ( identifier[settings] . identifier[API_PATH] , literal[string] ), identifier[data] ={ literal[string] : identifier[issn] }, identifier[on_complete] = identifier[cls] . identifier[on_complete] )
def start(cls, ev=None): """ Start the query to aleph by ISSN. """ ViewController.log_view.add('Beginning AlephReader request..') ViewController.issnbox_error.reset() issn = ViewController.issn.strip() # make sure, that `issn` was filled if not issn: ViewController.issnbox_error.show('ISSN nebylo vyplněno!') ViewController.log_view.add('No ISSN! Aborting.') return # depends on [control=['if'], data=[]] ViewController.issnbox_error.hide() ViewController.issn_progressbar.reset() ViewController.issn_progressbar.show(50) ViewController.log_view.add('For ISSN `%s`.' % issn) make_request(url=join(settings.API_PATH, 'aleph/records_by_issn'), data={'issn': issn}, on_complete=cls.on_complete)
def to_dict(self): """Convert the cells to a dictionary. This is intended to be used with HappyBase, so the column family and column qualiers are combined (with ``:``). :rtype: dict :returns: Dictionary containing all the data in the cells of this row. """ result = {} for column_family_id, columns in six.iteritems(self._cells): for column_qual, cells in six.iteritems(columns): key = _to_bytes(column_family_id) + b":" + _to_bytes(column_qual) result[key] = cells return result
def function[to_dict, parameter[self]]: constant[Convert the cells to a dictionary. This is intended to be used with HappyBase, so the column family and column qualiers are combined (with ``:``). :rtype: dict :returns: Dictionary containing all the data in the cells of this row. ] variable[result] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da18bcc9c60>, <ast.Name object at 0x7da18bcc8340>]]] in starred[call[name[six].iteritems, parameter[name[self]._cells]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da18bcca020>, <ast.Name object at 0x7da18bccb910>]]] in starred[call[name[six].iteritems, parameter[name[columns]]]] begin[:] variable[key] assign[=] binary_operation[binary_operation[call[name[_to_bytes], parameter[name[column_family_id]]] + constant[b':']] + call[name[_to_bytes], parameter[name[column_qual]]]] call[name[result]][name[key]] assign[=] name[cells] return[name[result]]
keyword[def] identifier[to_dict] ( identifier[self] ): literal[string] identifier[result] ={} keyword[for] identifier[column_family_id] , identifier[columns] keyword[in] identifier[six] . identifier[iteritems] ( identifier[self] . identifier[_cells] ): keyword[for] identifier[column_qual] , identifier[cells] keyword[in] identifier[six] . identifier[iteritems] ( identifier[columns] ): identifier[key] = identifier[_to_bytes] ( identifier[column_family_id] )+ literal[string] + identifier[_to_bytes] ( identifier[column_qual] ) identifier[result] [ identifier[key] ]= identifier[cells] keyword[return] identifier[result]
def to_dict(self): """Convert the cells to a dictionary. This is intended to be used with HappyBase, so the column family and column qualiers are combined (with ``:``). :rtype: dict :returns: Dictionary containing all the data in the cells of this row. """ result = {} for (column_family_id, columns) in six.iteritems(self._cells): for (column_qual, cells) in six.iteritems(columns): key = _to_bytes(column_family_id) + b':' + _to_bytes(column_qual) result[key] = cells # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] return result
def get_interface_detail_output_interface_line_protocol_state(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") interface = ET.SubElement(output, "interface") interface_type_key = ET.SubElement(interface, "interface-type") interface_type_key.text = kwargs.pop('interface_type') interface_name_key = ET.SubElement(interface, "interface-name") interface_name_key.text = kwargs.pop('interface_name') line_protocol_state = ET.SubElement(interface, "line-protocol-state") line_protocol_state.text = kwargs.pop('line_protocol_state') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[get_interface_detail_output_interface_line_protocol_state, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[get_interface_detail] assign[=] call[name[ET].Element, parameter[constant[get_interface_detail]]] variable[config] assign[=] name[get_interface_detail] variable[output] assign[=] call[name[ET].SubElement, parameter[name[get_interface_detail], constant[output]]] variable[interface] assign[=] call[name[ET].SubElement, parameter[name[output], constant[interface]]] variable[interface_type_key] assign[=] call[name[ET].SubElement, parameter[name[interface], constant[interface-type]]] name[interface_type_key].text assign[=] call[name[kwargs].pop, parameter[constant[interface_type]]] variable[interface_name_key] assign[=] call[name[ET].SubElement, parameter[name[interface], constant[interface-name]]] name[interface_name_key].text assign[=] call[name[kwargs].pop, parameter[constant[interface_name]]] variable[line_protocol_state] assign[=] call[name[ET].SubElement, parameter[name[interface], constant[line-protocol-state]]] name[line_protocol_state].text assign[=] call[name[kwargs].pop, parameter[constant[line_protocol_state]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[get_interface_detail_output_interface_line_protocol_state] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[get_interface_detail] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[config] = identifier[get_interface_detail] identifier[output] = identifier[ET] . identifier[SubElement] ( identifier[get_interface_detail] , literal[string] ) identifier[interface] = identifier[ET] . identifier[SubElement] ( identifier[output] , literal[string] ) identifier[interface_type_key] = identifier[ET] . identifier[SubElement] ( identifier[interface] , literal[string] ) identifier[interface_type_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[interface_name_key] = identifier[ET] . identifier[SubElement] ( identifier[interface] , literal[string] ) identifier[interface_name_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[line_protocol_state] = identifier[ET] . identifier[SubElement] ( identifier[interface] , literal[string] ) identifier[line_protocol_state] . 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_interface_detail_output_interface_line_protocol_state(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') get_interface_detail = ET.Element('get_interface_detail') config = get_interface_detail output = ET.SubElement(get_interface_detail, 'output') interface = ET.SubElement(output, 'interface') interface_type_key = ET.SubElement(interface, 'interface-type') interface_type_key.text = kwargs.pop('interface_type') interface_name_key = ET.SubElement(interface, 'interface-name') interface_name_key.text = kwargs.pop('interface_name') line_protocol_state = ET.SubElement(interface, 'line-protocol-state') line_protocol_state.text = kwargs.pop('line_protocol_state') callback = kwargs.pop('callback', self._callback) return callback(config)
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
def function[_api_key_patch_replace, parameter[conn, apiKey, path, value]]: constant[ the replace patch operation on an ApiKey resource ] variable[response] assign[=] call[name[conn].update_api_key, parameter[]] return[name[response]]
keyword[def] identifier[_api_key_patch_replace] ( identifier[conn] , identifier[apiKey] , identifier[path] , identifier[value] ): literal[string] identifier[response] = identifier[conn] . identifier[update_api_key] ( identifier[apiKey] = identifier[apiKey] , identifier[patchOperations] =[{ literal[string] : literal[string] , literal[string] : identifier[path] , literal[string] : identifier[value] }]) keyword[return] identifier[response]
def _api_key_patch_replace(conn, apiKey, path, value): """ the replace patch operation on an ApiKey resource """ response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
def edgepaths(self): """ Returns the fixed EdgePaths or computes direct connections between supplied nodes. """ edgepaths = super(TriMesh, self).edgepaths edgepaths.crs = self.crs return edgepaths
def function[edgepaths, parameter[self]]: constant[ Returns the fixed EdgePaths or computes direct connections between supplied nodes. ] variable[edgepaths] assign[=] call[name[super], parameter[name[TriMesh], name[self]]].edgepaths name[edgepaths].crs assign[=] name[self].crs return[name[edgepaths]]
keyword[def] identifier[edgepaths] ( identifier[self] ): literal[string] identifier[edgepaths] = identifier[super] ( identifier[TriMesh] , identifier[self] ). identifier[edgepaths] identifier[edgepaths] . identifier[crs] = identifier[self] . identifier[crs] keyword[return] identifier[edgepaths]
def edgepaths(self): """ Returns the fixed EdgePaths or computes direct connections between supplied nodes. """ edgepaths = super(TriMesh, self).edgepaths edgepaths.crs = self.crs return edgepaths
def initialize( self, region="us-west-1", host=None, port=8000, config_dir=None, session=None ): """ Set up the repl for execution. """ try: import readline import rlcompleter except ImportError: # Windows doesn't have readline, so gracefully ignore. pass else: # Mac OS X readline compatibility from http://stackoverflow.com/a/7116997 if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") # Tab-complete names with a '-' in them delims = set(readline.get_completer_delims()) if "-" in delims: delims.remove("-") readline.set_completer_delims("".join(delims)) self._conf_dir = config_dir or os.path.join( os.environ.get("HOME", "."), ".config" ) self.session = session or botocore.session.get_session() self.engine = FragmentEngine() self.engine.caution_callback = self.caution_callback if host is not None: self._local_endpoint = (host, port) self.engine.connect( region, session=self.session, host=host, port=port, is_secure=(host is None) ) self.conf = self.load_config() for key, value in iteritems(DEFAULT_CONFIG): self.conf.setdefault(key, value) self.display = DISPLAYS[self.conf["display"]] self.throttle = TableLimits() self.throttle.load(self.conf["_throttle"])
def function[initialize, parameter[self, region, host, port, config_dir, session]]: constant[ Set up the repl for execution. ] <ast.Try object at 0x7da1b0e2d720> name[self]._conf_dir assign[=] <ast.BoolOp object at 0x7da204623a00> name[self].session assign[=] <ast.BoolOp object at 0x7da1b0c32c50> name[self].engine assign[=] call[name[FragmentEngine], parameter[]] name[self].engine.caution_callback assign[=] name[self].caution_callback if compare[name[host] is_not constant[None]] begin[:] name[self]._local_endpoint assign[=] tuple[[<ast.Name object at 0x7da1b0e2cc70>, <ast.Name object at 0x7da1b0e2e320>]] call[name[self].engine.connect, parameter[name[region]]] name[self].conf assign[=] call[name[self].load_config, parameter[]] for taget[tuple[[<ast.Name object at 0x7da1b0c65d50>, <ast.Name object at 0x7da1b0c658d0>]]] in starred[call[name[iteritems], parameter[name[DEFAULT_CONFIG]]]] begin[:] call[name[self].conf.setdefault, parameter[name[key], name[value]]] name[self].display assign[=] call[name[DISPLAYS]][call[name[self].conf][constant[display]]] name[self].throttle assign[=] call[name[TableLimits], parameter[]] call[name[self].throttle.load, parameter[call[name[self].conf][constant[_throttle]]]]
keyword[def] identifier[initialize] ( identifier[self] , identifier[region] = literal[string] , identifier[host] = keyword[None] , identifier[port] = literal[int] , identifier[config_dir] = keyword[None] , identifier[session] = keyword[None] ): literal[string] keyword[try] : keyword[import] identifier[readline] keyword[import] identifier[rlcompleter] keyword[except] identifier[ImportError] : keyword[pass] keyword[else] : keyword[if] literal[string] keyword[in] identifier[readline] . identifier[__doc__] : identifier[readline] . identifier[parse_and_bind] ( literal[string] ) keyword[else] : identifier[readline] . identifier[parse_and_bind] ( literal[string] ) identifier[delims] = identifier[set] ( identifier[readline] . identifier[get_completer_delims] ()) keyword[if] literal[string] keyword[in] identifier[delims] : identifier[delims] . identifier[remove] ( literal[string] ) identifier[readline] . identifier[set_completer_delims] ( literal[string] . identifier[join] ( identifier[delims] )) identifier[self] . identifier[_conf_dir] = identifier[config_dir] keyword[or] identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ), literal[string] ) identifier[self] . identifier[session] = identifier[session] keyword[or] identifier[botocore] . identifier[session] . identifier[get_session] () identifier[self] . identifier[engine] = identifier[FragmentEngine] () identifier[self] . identifier[engine] . identifier[caution_callback] = identifier[self] . identifier[caution_callback] keyword[if] identifier[host] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[_local_endpoint] =( identifier[host] , identifier[port] ) identifier[self] . identifier[engine] . identifier[connect] ( identifier[region] , identifier[session] = identifier[self] . identifier[session] , identifier[host] = identifier[host] , identifier[port] = identifier[port] , identifier[is_secure] =( identifier[host] keyword[is] keyword[None] ) ) identifier[self] . identifier[conf] = identifier[self] . identifier[load_config] () keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iteritems] ( identifier[DEFAULT_CONFIG] ): identifier[self] . identifier[conf] . identifier[setdefault] ( identifier[key] , identifier[value] ) identifier[self] . identifier[display] = identifier[DISPLAYS] [ identifier[self] . identifier[conf] [ literal[string] ]] identifier[self] . identifier[throttle] = identifier[TableLimits] () identifier[self] . identifier[throttle] . identifier[load] ( identifier[self] . identifier[conf] [ literal[string] ])
def initialize(self, region='us-west-1', host=None, port=8000, config_dir=None, session=None): """ Set up the repl for execution. """ try: import readline import rlcompleter # depends on [control=['try'], data=[]] except ImportError: # Windows doesn't have readline, so gracefully ignore. pass # depends on [control=['except'], data=[]] else: # Mac OS X readline compatibility from http://stackoverflow.com/a/7116997 if 'libedit' in readline.__doc__: readline.parse_and_bind('bind ^I rl_complete') # depends on [control=['if'], data=[]] else: readline.parse_and_bind('tab: complete') # Tab-complete names with a '-' in them delims = set(readline.get_completer_delims()) if '-' in delims: delims.remove('-') readline.set_completer_delims(''.join(delims)) # depends on [control=['if'], data=['delims']] self._conf_dir = config_dir or os.path.join(os.environ.get('HOME', '.'), '.config') self.session = session or botocore.session.get_session() self.engine = FragmentEngine() self.engine.caution_callback = self.caution_callback if host is not None: self._local_endpoint = (host, port) # depends on [control=['if'], data=['host']] self.engine.connect(region, session=self.session, host=host, port=port, is_secure=host is None) self.conf = self.load_config() for (key, value) in iteritems(DEFAULT_CONFIG): self.conf.setdefault(key, value) # depends on [control=['for'], data=[]] self.display = DISPLAYS[self.conf['display']] self.throttle = TableLimits() self.throttle.load(self.conf['_throttle'])
def macaroons_expiry_time(ns, ms): ''' Returns the minimum time of any time-before caveats found in the given macaroons or None if no such caveats were found. :param ns: a Namespace, used to resolve caveats. :param ms: a list of pymacaroons.Macaroon :return: datetime.DateTime or None. ''' t = None for m in ms: et = expiry_time(ns, m.caveats) if et is not None and (t is None or et < t): t = et return t
def function[macaroons_expiry_time, parameter[ns, ms]]: constant[ Returns the minimum time of any time-before caveats found in the given macaroons or None if no such caveats were found. :param ns: a Namespace, used to resolve caveats. :param ms: a list of pymacaroons.Macaroon :return: datetime.DateTime or None. ] variable[t] assign[=] constant[None] for taget[name[m]] in starred[name[ms]] begin[:] variable[et] assign[=] call[name[expiry_time], parameter[name[ns], name[m].caveats]] if <ast.BoolOp object at 0x7da1b2436320> begin[:] variable[t] assign[=] name[et] return[name[t]]
keyword[def] identifier[macaroons_expiry_time] ( identifier[ns] , identifier[ms] ): literal[string] identifier[t] = keyword[None] keyword[for] identifier[m] keyword[in] identifier[ms] : identifier[et] = identifier[expiry_time] ( identifier[ns] , identifier[m] . identifier[caveats] ) keyword[if] identifier[et] keyword[is] keyword[not] keyword[None] keyword[and] ( identifier[t] keyword[is] keyword[None] keyword[or] identifier[et] < identifier[t] ): identifier[t] = identifier[et] keyword[return] identifier[t]
def macaroons_expiry_time(ns, ms): """ Returns the minimum time of any time-before caveats found in the given macaroons or None if no such caveats were found. :param ns: a Namespace, used to resolve caveats. :param ms: a list of pymacaroons.Macaroon :return: datetime.DateTime or None. """ t = None for m in ms: et = expiry_time(ns, m.caveats) if et is not None and (t is None or et < t): t = et # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['m']] return t
def oauth2_dance(consumer_key, consumer_secret, loop=None): """ oauth2 dance Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret loop : event loop, optional event loop to use Returns ------- str Bearer token """ loop = asyncio.get_event_loop() if loop is None else loop client = BasePeonyClient(consumer_key=consumer_key, consumer_secret=consumer_secret, auth=oauth.OAuth2Headers) loop.run_until_complete(client.headers.sign()) return client.headers.token
def function[oauth2_dance, parameter[consumer_key, consumer_secret, loop]]: constant[ oauth2 dance Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret loop : event loop, optional event loop to use Returns ------- str Bearer token ] variable[loop] assign[=] <ast.IfExp object at 0x7da1b0143310> variable[client] assign[=] call[name[BasePeonyClient], parameter[]] call[name[loop].run_until_complete, parameter[call[name[client].headers.sign, parameter[]]]] return[name[client].headers.token]
keyword[def] identifier[oauth2_dance] ( identifier[consumer_key] , identifier[consumer_secret] , identifier[loop] = keyword[None] ): literal[string] identifier[loop] = identifier[asyncio] . identifier[get_event_loop] () keyword[if] identifier[loop] keyword[is] keyword[None] keyword[else] identifier[loop] identifier[client] = identifier[BasePeonyClient] ( identifier[consumer_key] = identifier[consumer_key] , identifier[consumer_secret] = identifier[consumer_secret] , identifier[auth] = identifier[oauth] . identifier[OAuth2Headers] ) identifier[loop] . identifier[run_until_complete] ( identifier[client] . identifier[headers] . identifier[sign] ()) keyword[return] identifier[client] . identifier[headers] . identifier[token]
def oauth2_dance(consumer_key, consumer_secret, loop=None): """ oauth2 dance Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret loop : event loop, optional event loop to use Returns ------- str Bearer token """ loop = asyncio.get_event_loop() if loop is None else loop client = BasePeonyClient(consumer_key=consumer_key, consumer_secret=consumer_secret, auth=oauth.OAuth2Headers) loop.run_until_complete(client.headers.sign()) return client.headers.token
def update_ff(self, ff, mol2=False, force_ff_assign=False): """Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style labels will also be used. force_ff_assign: bool, optional If true, the force field will be completely reassigned, ignoring the cached parameters. """ aff = False if force_ff_assign: aff = True elif 'assigned_ff' not in self.tags: aff = True elif not self.tags['assigned_ff']: aff = True if aff: self.assign_force_field(ff, mol2=mol2) return
def function[update_ff, parameter[self, ff, mol2, force_ff_assign]]: constant[Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style labels will also be used. force_ff_assign: bool, optional If true, the force field will be completely reassigned, ignoring the cached parameters. ] variable[aff] assign[=] constant[False] if name[force_ff_assign] begin[:] variable[aff] assign[=] constant[True] if name[aff] begin[:] call[name[self].assign_force_field, parameter[name[ff]]] return[None]
keyword[def] identifier[update_ff] ( identifier[self] , identifier[ff] , identifier[mol2] = keyword[False] , identifier[force_ff_assign] = keyword[False] ): literal[string] identifier[aff] = keyword[False] keyword[if] identifier[force_ff_assign] : identifier[aff] = keyword[True] keyword[elif] literal[string] keyword[not] keyword[in] identifier[self] . identifier[tags] : identifier[aff] = keyword[True] keyword[elif] keyword[not] identifier[self] . identifier[tags] [ literal[string] ]: identifier[aff] = keyword[True] keyword[if] identifier[aff] : identifier[self] . identifier[assign_force_field] ( identifier[ff] , identifier[mol2] = identifier[mol2] ) keyword[return]
def update_ff(self, ff, mol2=False, force_ff_assign=False): """Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assignment of the force field. Parameters ---------- ff: BuffForceField The force field to be used for scoring. mol2: bool, optional If true, mol2 style labels will also be used. force_ff_assign: bool, optional If true, the force field will be completely reassigned, ignoring the cached parameters. """ aff = False if force_ff_assign: aff = True # depends on [control=['if'], data=[]] elif 'assigned_ff' not in self.tags: aff = True # depends on [control=['if'], data=[]] elif not self.tags['assigned_ff']: aff = True # depends on [control=['if'], data=[]] if aff: self.assign_force_field(ff, mol2=mol2) # depends on [control=['if'], data=[]] return
def queue(self, *args, **kwargs): """ A function to queue a RQ job, e.g.:: @rq.job(timeout=60) def add(x, y): return x + y add.queue(1, 2, timeout=30) :param \\*args: The positional arguments to pass to the queued job. :param \\*\\*kwargs: The keyword arguments to pass to the queued job. :param queue: Name of the queue to queue in, defaults to queue of of job or :attr:`~flask_rq2.RQ.default_queue`. :type queue: str :param timeout: The job timeout in seconds. If not provided uses the job's timeout or :attr:`~flask_rq2.RQ.default_timeout`. :type timeout: int :param description: Description of the job. :type description: str :param result_ttl: The result TTL in seconds. If not provided uses the job's result TTL or :attr:`~flask_rq2.RQ.default_result_ttl`. :type result_ttl: int :param ttl: The job TTL in seconds. If not provided uses the job's TTL or no TTL at all. :type ttl: int :param depends_on: A job instance or id that the new job depends on. :type depends_on: ~flask_rq2.job.FlaskJob or str :param job_id: A custom ID for the new job. Defaults to an :mod:`UUID <uuid>`. :type job_id: str :param at_front: Whether or not the job is queued in front of all other enqueued jobs. :type at_front: bool :param meta: Additional meta data about the job. :type meta: dict :return: An RQ job instance. :rtype: ~flask_rq2.job.FlaskJob """ queue_name = kwargs.pop('queue', self.queue_name) timeout = kwargs.pop('timeout', self.timeout) result_ttl = kwargs.pop('result_ttl', self.result_ttl) ttl = kwargs.pop('ttl', self.ttl) depends_on = kwargs.pop('depends_on', self._depends_on) job_id = kwargs.pop('job_id', None) at_front = kwargs.pop('at_front', self._at_front) meta = kwargs.pop('meta', self._meta) description = kwargs.pop('description', self._description) return self.rq.get_queue(queue_name).enqueue_call( self.wrapped, args=args, kwargs=kwargs, timeout=timeout, result_ttl=result_ttl, ttl=ttl, depends_on=depends_on, job_id=job_id, at_front=at_front, meta=meta, description=description, )
def function[queue, parameter[self]]: constant[ A function to queue a RQ job, e.g.:: @rq.job(timeout=60) def add(x, y): return x + y add.queue(1, 2, timeout=30) :param \*args: The positional arguments to pass to the queued job. :param \*\*kwargs: The keyword arguments to pass to the queued job. :param queue: Name of the queue to queue in, defaults to queue of of job or :attr:`~flask_rq2.RQ.default_queue`. :type queue: str :param timeout: The job timeout in seconds. If not provided uses the job's timeout or :attr:`~flask_rq2.RQ.default_timeout`. :type timeout: int :param description: Description of the job. :type description: str :param result_ttl: The result TTL in seconds. If not provided uses the job's result TTL or :attr:`~flask_rq2.RQ.default_result_ttl`. :type result_ttl: int :param ttl: The job TTL in seconds. If not provided uses the job's TTL or no TTL at all. :type ttl: int :param depends_on: A job instance or id that the new job depends on. :type depends_on: ~flask_rq2.job.FlaskJob or str :param job_id: A custom ID for the new job. Defaults to an :mod:`UUID <uuid>`. :type job_id: str :param at_front: Whether or not the job is queued in front of all other enqueued jobs. :type at_front: bool :param meta: Additional meta data about the job. :type meta: dict :return: An RQ job instance. :rtype: ~flask_rq2.job.FlaskJob ] variable[queue_name] assign[=] call[name[kwargs].pop, parameter[constant[queue], name[self].queue_name]] variable[timeout] assign[=] call[name[kwargs].pop, parameter[constant[timeout], name[self].timeout]] variable[result_ttl] assign[=] call[name[kwargs].pop, parameter[constant[result_ttl], name[self].result_ttl]] variable[ttl] assign[=] call[name[kwargs].pop, parameter[constant[ttl], name[self].ttl]] variable[depends_on] assign[=] call[name[kwargs].pop, parameter[constant[depends_on], name[self]._depends_on]] variable[job_id] assign[=] call[name[kwargs].pop, parameter[constant[job_id], constant[None]]] variable[at_front] assign[=] call[name[kwargs].pop, parameter[constant[at_front], name[self]._at_front]] variable[meta] assign[=] call[name[kwargs].pop, parameter[constant[meta], name[self]._meta]] variable[description] assign[=] call[name[kwargs].pop, parameter[constant[description], name[self]._description]] return[call[call[name[self].rq.get_queue, parameter[name[queue_name]]].enqueue_call, parameter[name[self].wrapped]]]
keyword[def] identifier[queue] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[queue_name] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[queue_name] ) identifier[timeout] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[timeout] ) identifier[result_ttl] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[result_ttl] ) identifier[ttl] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[ttl] ) identifier[depends_on] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_depends_on] ) identifier[job_id] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) identifier[at_front] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_at_front] ) identifier[meta] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_meta] ) identifier[description] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_description] ) keyword[return] identifier[self] . identifier[rq] . identifier[get_queue] ( identifier[queue_name] ). identifier[enqueue_call] ( identifier[self] . identifier[wrapped] , identifier[args] = identifier[args] , identifier[kwargs] = identifier[kwargs] , identifier[timeout] = identifier[timeout] , identifier[result_ttl] = identifier[result_ttl] , identifier[ttl] = identifier[ttl] , identifier[depends_on] = identifier[depends_on] , identifier[job_id] = identifier[job_id] , identifier[at_front] = identifier[at_front] , identifier[meta] = identifier[meta] , identifier[description] = identifier[description] , )
def queue(self, *args, **kwargs): """ A function to queue a RQ job, e.g.:: @rq.job(timeout=60) def add(x, y): return x + y add.queue(1, 2, timeout=30) :param \\*args: The positional arguments to pass to the queued job. :param \\*\\*kwargs: The keyword arguments to pass to the queued job. :param queue: Name of the queue to queue in, defaults to queue of of job or :attr:`~flask_rq2.RQ.default_queue`. :type queue: str :param timeout: The job timeout in seconds. If not provided uses the job's timeout or :attr:`~flask_rq2.RQ.default_timeout`. :type timeout: int :param description: Description of the job. :type description: str :param result_ttl: The result TTL in seconds. If not provided uses the job's result TTL or :attr:`~flask_rq2.RQ.default_result_ttl`. :type result_ttl: int :param ttl: The job TTL in seconds. If not provided uses the job's TTL or no TTL at all. :type ttl: int :param depends_on: A job instance or id that the new job depends on. :type depends_on: ~flask_rq2.job.FlaskJob or str :param job_id: A custom ID for the new job. Defaults to an :mod:`UUID <uuid>`. :type job_id: str :param at_front: Whether or not the job is queued in front of all other enqueued jobs. :type at_front: bool :param meta: Additional meta data about the job. :type meta: dict :return: An RQ job instance. :rtype: ~flask_rq2.job.FlaskJob """ queue_name = kwargs.pop('queue', self.queue_name) timeout = kwargs.pop('timeout', self.timeout) result_ttl = kwargs.pop('result_ttl', self.result_ttl) ttl = kwargs.pop('ttl', self.ttl) depends_on = kwargs.pop('depends_on', self._depends_on) job_id = kwargs.pop('job_id', None) at_front = kwargs.pop('at_front', self._at_front) meta = kwargs.pop('meta', self._meta) description = kwargs.pop('description', self._description) return self.rq.get_queue(queue_name).enqueue_call(self.wrapped, args=args, kwargs=kwargs, timeout=timeout, result_ttl=result_ttl, ttl=ttl, depends_on=depends_on, job_id=job_id, at_front=at_front, meta=meta, description=description)
def show_raslog_output_show_all_raslog_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_raslog = ET.Element("show_raslog") config = show_raslog output = ET.SubElement(show_raslog, "output") show_all_raslog = ET.SubElement(output, "show-all-raslog") rbridge_id = ET.SubElement(show_all_raslog, "rbridge-id") rbridge_id.text = kwargs.pop('rbridge_id') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[show_raslog_output_show_all_raslog_rbridge_id, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[show_raslog] assign[=] call[name[ET].Element, parameter[constant[show_raslog]]] variable[config] assign[=] name[show_raslog] variable[output] assign[=] call[name[ET].SubElement, parameter[name[show_raslog], constant[output]]] variable[show_all_raslog] assign[=] call[name[ET].SubElement, parameter[name[output], constant[show-all-raslog]]] variable[rbridge_id] assign[=] call[name[ET].SubElement, parameter[name[show_all_raslog], constant[rbridge-id]]] name[rbridge_id].text assign[=] call[name[kwargs].pop, parameter[constant[rbridge_id]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[show_raslog_output_show_all_raslog_rbridge_id] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[show_raslog] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[config] = identifier[show_raslog] identifier[output] = identifier[ET] . identifier[SubElement] ( identifier[show_raslog] , literal[string] ) identifier[show_all_raslog] = identifier[ET] . identifier[SubElement] ( identifier[output] , literal[string] ) identifier[rbridge_id] = identifier[ET] . identifier[SubElement] ( identifier[show_all_raslog] , literal[string] ) identifier[rbridge_id] . 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 show_raslog_output_show_all_raslog_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') show_raslog = ET.Element('show_raslog') config = show_raslog output = ET.SubElement(show_raslog, 'output') show_all_raslog = ET.SubElement(output, 'show-all-raslog') rbridge_id = ET.SubElement(show_all_raslog, 'rbridge-id') rbridge_id.text = kwargs.pop('rbridge_id') callback = kwargs.pop('callback', self._callback) return callback(config)
def resize_image(buf, width, height, num_channels, new_width, new_height): """Resize an image Args: buf (Buffer): Buffer coming from `load_image` width (int): Width of `buf` height (int): Height of `buf` num_channels (int): Number of channels in `buf` (RGBA=4) new_width (int): Desired width new_height (int): Desired height Returns: Buffer: Resized image Raises: ResizeError: If an error occurs during resize """ new_size = new_width * new_height * num_channels input_pixels = ffi.from_buffer(buf) output_pixels = ffi.new('unsigned char[]', new_size) result = lib.stbir_resize_uint8( ffi.cast('unsigned char*', input_pixels), width, height, 0, output_pixels, new_width, new_height, 0, num_channels ) if not result: raise ResizeError() return ffi.buffer(output_pixels, new_size)
def function[resize_image, parameter[buf, width, height, num_channels, new_width, new_height]]: constant[Resize an image Args: buf (Buffer): Buffer coming from `load_image` width (int): Width of `buf` height (int): Height of `buf` num_channels (int): Number of channels in `buf` (RGBA=4) new_width (int): Desired width new_height (int): Desired height Returns: Buffer: Resized image Raises: ResizeError: If an error occurs during resize ] variable[new_size] assign[=] binary_operation[binary_operation[name[new_width] * name[new_height]] * name[num_channels]] variable[input_pixels] assign[=] call[name[ffi].from_buffer, parameter[name[buf]]] variable[output_pixels] assign[=] call[name[ffi].new, parameter[constant[unsigned char[]], name[new_size]]] variable[result] assign[=] call[name[lib].stbir_resize_uint8, parameter[call[name[ffi].cast, parameter[constant[unsigned char*], name[input_pixels]]], name[width], name[height], constant[0], name[output_pixels], name[new_width], name[new_height], constant[0], name[num_channels]]] if <ast.UnaryOp object at 0x7da1b0862590> begin[:] <ast.Raise object at 0x7da1b0863820> return[call[name[ffi].buffer, parameter[name[output_pixels], name[new_size]]]]
keyword[def] identifier[resize_image] ( identifier[buf] , identifier[width] , identifier[height] , identifier[num_channels] , identifier[new_width] , identifier[new_height] ): literal[string] identifier[new_size] = identifier[new_width] * identifier[new_height] * identifier[num_channels] identifier[input_pixels] = identifier[ffi] . identifier[from_buffer] ( identifier[buf] ) identifier[output_pixels] = identifier[ffi] . identifier[new] ( literal[string] , identifier[new_size] ) identifier[result] = identifier[lib] . identifier[stbir_resize_uint8] ( identifier[ffi] . identifier[cast] ( literal[string] , identifier[input_pixels] ), identifier[width] , identifier[height] , literal[int] , identifier[output_pixels] , identifier[new_width] , identifier[new_height] , literal[int] , identifier[num_channels] ) keyword[if] keyword[not] identifier[result] : keyword[raise] identifier[ResizeError] () keyword[return] identifier[ffi] . identifier[buffer] ( identifier[output_pixels] , identifier[new_size] )
def resize_image(buf, width, height, num_channels, new_width, new_height): """Resize an image Args: buf (Buffer): Buffer coming from `load_image` width (int): Width of `buf` height (int): Height of `buf` num_channels (int): Number of channels in `buf` (RGBA=4) new_width (int): Desired width new_height (int): Desired height Returns: Buffer: Resized image Raises: ResizeError: If an error occurs during resize """ new_size = new_width * new_height * num_channels input_pixels = ffi.from_buffer(buf) output_pixels = ffi.new('unsigned char[]', new_size) result = lib.stbir_resize_uint8(ffi.cast('unsigned char*', input_pixels), width, height, 0, output_pixels, new_width, new_height, 0, num_channels) if not result: raise ResizeError() # depends on [control=['if'], data=[]] return ffi.buffer(output_pixels, new_size)
def save(self): """ Save the UFO.""" # handle glyphs that were muted for name in self.mutedGlyphsNames: if name not in self.font: continue if self.logger: self.logger.info("removing muted glyph %s", name) del self.font[name] # XXX housekeeping: # remove glyph from groups / kerning as well? # remove components referencing this glyph? # fontTools.ufoLib no longer calls os.makedirs for us if the # parent directories of the Font we are saving do not exist. # We want to keep backward compatibility with the previous # MutatorMath behavior, so we create the instance' parent # directories if they do not exist. We assume that the users # knows what they are doing... directory = os.path.dirname(os.path.normpath(self.path)) if directory and not os.path.exists(directory): os.makedirs(directory) try: self.font.save(os.path.abspath(self.path), self.ufoVersion) except defcon.DefconError as error: if self.logger: self.logger.exception("Error generating.") return False, error.report return True, None
def function[save, parameter[self]]: constant[ Save the UFO.] for taget[name[name]] in starred[name[self].mutedGlyphsNames] begin[:] if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self].font] begin[:] continue if name[self].logger begin[:] call[name[self].logger.info, parameter[constant[removing muted glyph %s], name[name]]] <ast.Delete object at 0x7da2041d97b0> variable[directory] assign[=] call[name[os].path.dirname, parameter[call[name[os].path.normpath, parameter[name[self].path]]]] if <ast.BoolOp object at 0x7da2041dbbb0> begin[:] call[name[os].makedirs, parameter[name[directory]]] <ast.Try object at 0x7da2041d9330> return[tuple[[<ast.Constant object at 0x7da2041d9360>, <ast.Constant object at 0x7da2041da0b0>]]]
keyword[def] identifier[save] ( identifier[self] ): literal[string] keyword[for] identifier[name] keyword[in] identifier[self] . identifier[mutedGlyphsNames] : keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[font] : keyword[continue] keyword[if] identifier[self] . identifier[logger] : identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[name] ) keyword[del] identifier[self] . identifier[font] [ identifier[name] ] identifier[directory] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[normpath] ( identifier[self] . identifier[path] )) keyword[if] identifier[directory] keyword[and] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[directory] ): identifier[os] . identifier[makedirs] ( identifier[directory] ) keyword[try] : identifier[self] . identifier[font] . identifier[save] ( identifier[os] . identifier[path] . identifier[abspath] ( identifier[self] . identifier[path] ), identifier[self] . identifier[ufoVersion] ) keyword[except] identifier[defcon] . identifier[DefconError] keyword[as] identifier[error] : keyword[if] identifier[self] . identifier[logger] : identifier[self] . identifier[logger] . identifier[exception] ( literal[string] ) keyword[return] keyword[False] , identifier[error] . identifier[report] keyword[return] keyword[True] , keyword[None]
def save(self): """ Save the UFO.""" # handle glyphs that were muted for name in self.mutedGlyphsNames: if name not in self.font: continue # depends on [control=['if'], data=[]] if self.logger: self.logger.info('removing muted glyph %s', name) # depends on [control=['if'], data=[]] del self.font[name] # depends on [control=['for'], data=['name']] # XXX housekeeping: # remove glyph from groups / kerning as well? # remove components referencing this glyph? # fontTools.ufoLib no longer calls os.makedirs for us if the # parent directories of the Font we are saving do not exist. # We want to keep backward compatibility with the previous # MutatorMath behavior, so we create the instance' parent # directories if they do not exist. We assume that the users # knows what they are doing... directory = os.path.dirname(os.path.normpath(self.path)) if directory and (not os.path.exists(directory)): os.makedirs(directory) # depends on [control=['if'], data=[]] try: self.font.save(os.path.abspath(self.path), self.ufoVersion) # depends on [control=['try'], data=[]] except defcon.DefconError as error: if self.logger: self.logger.exception('Error generating.') # depends on [control=['if'], data=[]] return (False, error.report) # depends on [control=['except'], data=['error']] return (True, None)
async def expn( self, address: str, timeout: DefaultNumType = _default ) -> SMTPResponse: """ Send an SMTP EXPN command, which expands a mailing list. Not many servers support this command. :raises SMTPResponseException: on unexpected server response code """ await self._ehlo_or_helo_if_needed() parsed_address = parse_address(address) async with self._command_lock: response = await self.execute_command( b"EXPN", parsed_address.encode("ascii"), timeout=timeout ) if response.code != SMTPStatus.completed: raise SMTPResponseException(response.code, response.message) return response
<ast.AsyncFunctionDef object at 0x7da204345c90>
keyword[async] keyword[def] identifier[expn] ( identifier[self] , identifier[address] : identifier[str] , identifier[timeout] : identifier[DefaultNumType] = identifier[_default] )-> identifier[SMTPResponse] : literal[string] keyword[await] identifier[self] . identifier[_ehlo_or_helo_if_needed] () identifier[parsed_address] = identifier[parse_address] ( identifier[address] ) keyword[async] keyword[with] identifier[self] . identifier[_command_lock] : identifier[response] = keyword[await] identifier[self] . identifier[execute_command] ( literal[string] , identifier[parsed_address] . identifier[encode] ( literal[string] ), identifier[timeout] = identifier[timeout] ) keyword[if] identifier[response] . identifier[code] != identifier[SMTPStatus] . identifier[completed] : keyword[raise] identifier[SMTPResponseException] ( identifier[response] . identifier[code] , identifier[response] . identifier[message] ) keyword[return] identifier[response]
async def expn(self, address: str, timeout: DefaultNumType=_default) -> SMTPResponse: """ Send an SMTP EXPN command, which expands a mailing list. Not many servers support this command. :raises SMTPResponseException: on unexpected server response code """ await self._ehlo_or_helo_if_needed() parsed_address = parse_address(address) async with self._command_lock: response = await self.execute_command(b'EXPN', parsed_address.encode('ascii'), timeout=timeout) if response.code != SMTPStatus.completed: raise SMTPResponseException(response.code, response.message) # depends on [control=['if'], data=[]] return response
def add_hooks(): # type: () -> None """ Add git hooks for commit and push to run linting and tests. """ # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: log.err("You are not inside a virtualenv") confirm_msg = ( "Are you sure you want to use global python installation " "to run your git hooks? [y/N] " ) click.prompt(confirm_msg, default=False) if not click.confirm(confirm_msg): log.info("Cancelling") return load_venv = '' else: load_venv = 'source "{}/bin/activate"'.format(virtual_env) commit_hook = conf.proj_path('.git/hooks/pre-commit') push_hook = conf.proj_path('.git/hooks/pre-push') # Write pre-commit hook log.info("Adding pre-commit hook <33>{}", commit_hook) fs.write_file(commit_hook, util.remove_indent(''' #!/bin/bash PATH="/opt/local/libexec/gnubin:$PATH" {load_venv} peltak lint --commit '''.format(load_venv=load_venv))) # Write pre-push hook log.info("Adding pre-push hook: <33>{}", push_hook) fs.write_file(push_hook, util.remove_indent(''' #!/bin/bash PATH="/opt/local/libexec/gnubin:$PATH" {load_venv} peltak test --allow-empty '''.format(load_venv=load_venv))) log.info("Making hooks executable") if not context.get('pretend', False): os.chmod(conf.proj_path('.git/hooks/pre-commit'), 0o755) os.chmod(conf.proj_path('.git/hooks/pre-push'), 0o755)
def function[add_hooks, parameter[]]: constant[ Add git hooks for commit and push to run linting and tests. ] variable[virtual_env] assign[=] call[name[conf].getenv, parameter[constant[VIRTUAL_ENV]]] if compare[name[virtual_env] is constant[None]] begin[:] call[name[log].err, parameter[constant[You are not inside a virtualenv]]] variable[confirm_msg] assign[=] constant[Are you sure you want to use global python installation to run your git hooks? [y/N] ] call[name[click].prompt, parameter[name[confirm_msg]]] if <ast.UnaryOp object at 0x7da1b10e44c0> begin[:] call[name[log].info, parameter[constant[Cancelling]]] return[None] variable[load_venv] assign[=] constant[] variable[commit_hook] assign[=] call[name[conf].proj_path, parameter[constant[.git/hooks/pre-commit]]] variable[push_hook] assign[=] call[name[conf].proj_path, parameter[constant[.git/hooks/pre-push]]] call[name[log].info, parameter[constant[Adding pre-commit hook <33>{}], name[commit_hook]]] call[name[fs].write_file, parameter[name[commit_hook], call[name[util].remove_indent, parameter[call[constant[ #!/bin/bash PATH="/opt/local/libexec/gnubin:$PATH" {load_venv} peltak lint --commit ].format, parameter[]]]]]] call[name[log].info, parameter[constant[Adding pre-push hook: <33>{}], name[push_hook]]] call[name[fs].write_file, parameter[name[push_hook], call[name[util].remove_indent, parameter[call[constant[ #!/bin/bash PATH="/opt/local/libexec/gnubin:$PATH" {load_venv} peltak test --allow-empty ].format, parameter[]]]]]] call[name[log].info, parameter[constant[Making hooks executable]]] if <ast.UnaryOp object at 0x7da1b10c6d40> begin[:] call[name[os].chmod, parameter[call[name[conf].proj_path, parameter[constant[.git/hooks/pre-commit]]], constant[493]]] call[name[os].chmod, parameter[call[name[conf].proj_path, parameter[constant[.git/hooks/pre-push]]], constant[493]]]
keyword[def] identifier[add_hooks] (): literal[string] identifier[virtual_env] = identifier[conf] . identifier[getenv] ( literal[string] ) keyword[if] identifier[virtual_env] keyword[is] keyword[None] : identifier[log] . identifier[err] ( literal[string] ) identifier[confirm_msg] =( literal[string] literal[string] ) identifier[click] . identifier[prompt] ( identifier[confirm_msg] , identifier[default] = keyword[False] ) keyword[if] keyword[not] identifier[click] . identifier[confirm] ( identifier[confirm_msg] ): identifier[log] . identifier[info] ( literal[string] ) keyword[return] identifier[load_venv] = literal[string] keyword[else] : identifier[load_venv] = literal[string] . identifier[format] ( identifier[virtual_env] ) identifier[commit_hook] = identifier[conf] . identifier[proj_path] ( literal[string] ) identifier[push_hook] = identifier[conf] . identifier[proj_path] ( literal[string] ) identifier[log] . identifier[info] ( literal[string] , identifier[commit_hook] ) identifier[fs] . identifier[write_file] ( identifier[commit_hook] , identifier[util] . identifier[remove_indent] ( literal[string] . identifier[format] ( identifier[load_venv] = identifier[load_venv] ))) identifier[log] . identifier[info] ( literal[string] , identifier[push_hook] ) identifier[fs] . identifier[write_file] ( identifier[push_hook] , identifier[util] . identifier[remove_indent] ( literal[string] . identifier[format] ( identifier[load_venv] = identifier[load_venv] ))) identifier[log] . identifier[info] ( literal[string] ) keyword[if] keyword[not] identifier[context] . identifier[get] ( literal[string] , keyword[False] ): identifier[os] . identifier[chmod] ( identifier[conf] . identifier[proj_path] ( literal[string] ), literal[int] ) identifier[os] . identifier[chmod] ( identifier[conf] . identifier[proj_path] ( literal[string] ), literal[int] )
def add_hooks(): # type: () -> None ' Add git hooks for commit and push to run linting and tests. ' # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: log.err('You are not inside a virtualenv') confirm_msg = 'Are you sure you want to use global python installation to run your git hooks? [y/N] ' click.prompt(confirm_msg, default=False) if not click.confirm(confirm_msg): log.info('Cancelling') return # depends on [control=['if'], data=[]] load_venv = '' # depends on [control=['if'], data=[]] else: load_venv = 'source "{}/bin/activate"'.format(virtual_env) commit_hook = conf.proj_path('.git/hooks/pre-commit') push_hook = conf.proj_path('.git/hooks/pre-push') # Write pre-commit hook log.info('Adding pre-commit hook <33>{}', commit_hook) fs.write_file(commit_hook, util.remove_indent('\n #!/bin/bash\n PATH="/opt/local/libexec/gnubin:$PATH"\n \n {load_venv}\n \n peltak lint --commit\n \n '.format(load_venv=load_venv))) # Write pre-push hook log.info('Adding pre-push hook: <33>{}', push_hook) fs.write_file(push_hook, util.remove_indent('\n #!/bin/bash\n PATH="/opt/local/libexec/gnubin:$PATH"\n \n {load_venv}\n \n peltak test --allow-empty\n \n '.format(load_venv=load_venv))) log.info('Making hooks executable') if not context.get('pretend', False): os.chmod(conf.proj_path('.git/hooks/pre-commit'), 493) os.chmod(conf.proj_path('.git/hooks/pre-push'), 493) # depends on [control=['if'], data=[]]
def _find_ancestor_from_name(self, name): """ Returns the ancestor that has a task with the given name assigned. Returns None if no such ancestor was found. :type name: str :param name: The name of the wanted task. :rtype: Task :returns: The ancestor. """ if self.parent is None: return None if self.parent.get_name() == name: return self.parent return self.parent._find_ancestor_from_name(name)
def function[_find_ancestor_from_name, parameter[self, name]]: constant[ Returns the ancestor that has a task with the given name assigned. Returns None if no such ancestor was found. :type name: str :param name: The name of the wanted task. :rtype: Task :returns: The ancestor. ] if compare[name[self].parent is constant[None]] begin[:] return[constant[None]] if compare[call[name[self].parent.get_name, parameter[]] equal[==] name[name]] begin[:] return[name[self].parent] return[call[name[self].parent._find_ancestor_from_name, parameter[name[name]]]]
keyword[def] identifier[_find_ancestor_from_name] ( identifier[self] , identifier[name] ): literal[string] keyword[if] identifier[self] . identifier[parent] keyword[is] keyword[None] : keyword[return] keyword[None] keyword[if] identifier[self] . identifier[parent] . identifier[get_name] ()== identifier[name] : keyword[return] identifier[self] . identifier[parent] keyword[return] identifier[self] . identifier[parent] . identifier[_find_ancestor_from_name] ( identifier[name] )
def _find_ancestor_from_name(self, name): """ Returns the ancestor that has a task with the given name assigned. Returns None if no such ancestor was found. :type name: str :param name: The name of the wanted task. :rtype: Task :returns: The ancestor. """ if self.parent is None: return None # depends on [control=['if'], data=[]] if self.parent.get_name() == name: return self.parent # depends on [control=['if'], data=[]] return self.parent._find_ancestor_from_name(name)
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1): ''' If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise) ''' if len(completeness_year) == 1: if (mag >= mmin) and (year >= completeness_year[0]): # No adjustment needed - event weight == 1 return 1.0 else: # Event should not be counted return False kval = int(((mag - mmin) / mag_inc)) + 1 if (kval >= 1) and (year >= completeness_year[kval - 1]): return t_f else: return False
def function[_get_adjustment, parameter[mag, year, mmin, completeness_year, t_f, mag_inc]]: constant[ If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise) ] if compare[call[name[len], parameter[name[completeness_year]]] equal[==] constant[1]] begin[:] if <ast.BoolOp object at 0x7da18ede50f0> begin[:] return[constant[1.0]] variable[kval] assign[=] binary_operation[call[name[int], parameter[binary_operation[binary_operation[name[mag] - name[mmin]] / name[mag_inc]]]] + constant[1]] if <ast.BoolOp object at 0x7da18ede7f70> begin[:] return[name[t_f]]
keyword[def] identifier[_get_adjustment] ( identifier[mag] , identifier[year] , identifier[mmin] , identifier[completeness_year] , identifier[t_f] , identifier[mag_inc] = literal[int] ): literal[string] keyword[if] identifier[len] ( identifier[completeness_year] )== literal[int] : keyword[if] ( identifier[mag] >= identifier[mmin] ) keyword[and] ( identifier[year] >= identifier[completeness_year] [ literal[int] ]): keyword[return] literal[int] keyword[else] : keyword[return] keyword[False] identifier[kval] = identifier[int] ((( identifier[mag] - identifier[mmin] )/ identifier[mag_inc] ))+ literal[int] keyword[if] ( identifier[kval] >= literal[int] ) keyword[and] ( identifier[year] >= identifier[completeness_year] [ identifier[kval] - literal[int] ]): keyword[return] identifier[t_f] keyword[else] : keyword[return] keyword[False]
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1): """ If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise) """ if len(completeness_year) == 1: if mag >= mmin and year >= completeness_year[0]: # No adjustment needed - event weight == 1 return 1.0 # depends on [control=['if'], data=[]] else: # Event should not be counted return False # depends on [control=['if'], data=[]] kval = int((mag - mmin) / mag_inc) + 1 if kval >= 1 and year >= completeness_year[kval - 1]: return t_f # depends on [control=['if'], data=[]] else: return False
def pad_aes256(s): """ Pads an input string to a given block size. :param s: string :returns: The padded string. """ if len(s) % AES.block_size == 0: return s return Padding.appendPadding(s, blocksize=AES.block_size)
def function[pad_aes256, parameter[s]]: constant[ Pads an input string to a given block size. :param s: string :returns: The padded string. ] if compare[binary_operation[call[name[len], parameter[name[s]]] <ast.Mod object at 0x7da2590d6920> name[AES].block_size] equal[==] constant[0]] begin[:] return[name[s]] return[call[name[Padding].appendPadding, parameter[name[s]]]]
keyword[def] identifier[pad_aes256] ( identifier[s] ): literal[string] keyword[if] identifier[len] ( identifier[s] )% identifier[AES] . identifier[block_size] == literal[int] : keyword[return] identifier[s] keyword[return] identifier[Padding] . identifier[appendPadding] ( identifier[s] , identifier[blocksize] = identifier[AES] . identifier[block_size] )
def pad_aes256(s): """ Pads an input string to a given block size. :param s: string :returns: The padded string. """ if len(s) % AES.block_size == 0: return s # depends on [control=['if'], data=[]] return Padding.appendPadding(s, blocksize=AES.block_size)
def close(self, reason=None): """ Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close. """ with self._closing: if self._closed: return self._websocket.close() self._consumer.join() self._consumer = None self._websocket = None self._closed = True for cb in self._close_callbacks: cb(self, reason)
def function[close, parameter[self, reason]]: constant[ Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close. ] with name[self]._closing begin[:] if name[self]._closed begin[:] return[None] call[name[self]._websocket.close, parameter[]] call[name[self]._consumer.join, parameter[]] name[self]._consumer assign[=] constant[None] name[self]._websocket assign[=] constant[None] name[self]._closed assign[=] constant[True] for taget[name[cb]] in starred[name[self]._close_callbacks] begin[:] call[name[cb], parameter[name[self], name[reason]]]
keyword[def] identifier[close] ( identifier[self] , identifier[reason] = keyword[None] ): literal[string] keyword[with] identifier[self] . identifier[_closing] : keyword[if] identifier[self] . identifier[_closed] : keyword[return] identifier[self] . identifier[_websocket] . identifier[close] () identifier[self] . identifier[_consumer] . identifier[join] () identifier[self] . identifier[_consumer] = keyword[None] identifier[self] . identifier[_websocket] = keyword[None] identifier[self] . identifier[_closed] = keyword[True] keyword[for] identifier[cb] keyword[in] identifier[self] . identifier[_close_callbacks] : identifier[cb] ( identifier[self] , identifier[reason] )
def close(self, reason=None): """ Stop consuming messages and perform an orderly shutdown. If ``reason`` is None, then this is considered a regular close. """ with self._closing: if self._closed: return # depends on [control=['if'], data=[]] self._websocket.close() self._consumer.join() self._consumer = None self._websocket = None self._closed = True for cb in self._close_callbacks: cb(self, reason) # depends on [control=['for'], data=['cb']] # depends on [control=['with'], data=[]]
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 kwargs['order_type'] = "MARKET" self.parent.order("BUY", self, quantity=quantity, **kwargs)
def function[buy_market, parameter[self, quantity]]: constant[ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity ] call[name[kwargs]][constant[limit_price]] assign[=] constant[0] call[name[kwargs]][constant[order_type]] assign[=] constant[MARKET] call[name[self].parent.order, parameter[constant[BUY], name[self]]]
keyword[def] identifier[buy_market] ( identifier[self] , identifier[quantity] ,** identifier[kwargs] ): literal[string] identifier[kwargs] [ literal[string] ]= literal[int] identifier[kwargs] [ literal[string] ]= literal[string] identifier[self] . identifier[parent] . identifier[order] ( literal[string] , identifier[self] , identifier[quantity] = identifier[quantity] ,** identifier[kwargs] )
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 kwargs['order_type'] = 'MARKET' self.parent.order('BUY', self, quantity=quantity, **kwargs)
def read(self, length=None): """ Reads data from readble BIO. For test purposes. @param length - if specifed, limits amount of data read. If not BIO is read until end of buffer """ if not length is None: if not isinstance(length, inttype) : raise TypeError("length to read should be number") buf = create_string_buffer(length) readbytes = libcrypto.BIO_read(self.bio, buf, length) if readbytes == -2: raise NotImplementedError("Function is not supported by" + "this BIO") if readbytes == -1: raise IOError if readbytes == 0: return b"" return buf.raw[:readbytes] else: buf = create_string_buffer(1024) out = b"" readbytes = 1 while readbytes > 0: readbytes = libcrypto.BIO_read(self.bio, buf, 1024) if readbytes == -2: raise NotImplementedError("Function is not supported by " + "this BIO") if readbytes == -1: raise IOError if readbytes > 0: out += buf.raw[:readbytes] return out
def function[read, parameter[self, length]]: constant[ Reads data from readble BIO. For test purposes. @param length - if specifed, limits amount of data read. If not BIO is read until end of buffer ] if <ast.UnaryOp object at 0x7da1b28b4f70> begin[:] if <ast.UnaryOp object at 0x7da1b28b4340> begin[:] <ast.Raise object at 0x7da1b28b6b60> variable[buf] assign[=] call[name[create_string_buffer], parameter[name[length]]] variable[readbytes] assign[=] call[name[libcrypto].BIO_read, parameter[name[self].bio, name[buf], name[length]]] if compare[name[readbytes] equal[==] <ast.UnaryOp object at 0x7da1b28b7fa0>] begin[:] <ast.Raise object at 0x7da1b28b4a00> if compare[name[readbytes] equal[==] <ast.UnaryOp object at 0x7da1b28b6e00>] begin[:] <ast.Raise object at 0x7da1b28b48e0> if compare[name[readbytes] equal[==] constant[0]] begin[:] return[constant[b'']] return[call[name[buf].raw][<ast.Slice object at 0x7da1b28b52a0>]]
keyword[def] identifier[read] ( identifier[self] , identifier[length] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[length] keyword[is] keyword[None] : keyword[if] keyword[not] identifier[isinstance] ( identifier[length] , identifier[inttype] ): keyword[raise] identifier[TypeError] ( literal[string] ) identifier[buf] = identifier[create_string_buffer] ( identifier[length] ) identifier[readbytes] = identifier[libcrypto] . identifier[BIO_read] ( identifier[self] . identifier[bio] , identifier[buf] , identifier[length] ) keyword[if] identifier[readbytes] ==- literal[int] : keyword[raise] identifier[NotImplementedError] ( literal[string] + literal[string] ) keyword[if] identifier[readbytes] ==- literal[int] : keyword[raise] identifier[IOError] keyword[if] identifier[readbytes] == literal[int] : keyword[return] literal[string] keyword[return] identifier[buf] . identifier[raw] [: identifier[readbytes] ] keyword[else] : identifier[buf] = identifier[create_string_buffer] ( literal[int] ) identifier[out] = literal[string] identifier[readbytes] = literal[int] keyword[while] identifier[readbytes] > literal[int] : identifier[readbytes] = identifier[libcrypto] . identifier[BIO_read] ( identifier[self] . identifier[bio] , identifier[buf] , literal[int] ) keyword[if] identifier[readbytes] ==- literal[int] : keyword[raise] identifier[NotImplementedError] ( literal[string] + literal[string] ) keyword[if] identifier[readbytes] ==- literal[int] : keyword[raise] identifier[IOError] keyword[if] identifier[readbytes] > literal[int] : identifier[out] += identifier[buf] . identifier[raw] [: identifier[readbytes] ] keyword[return] identifier[out]
def read(self, length=None): """ Reads data from readble BIO. For test purposes. @param length - if specifed, limits amount of data read. If not BIO is read until end of buffer """ if not length is None: if not isinstance(length, inttype): raise TypeError('length to read should be number') # depends on [control=['if'], data=[]] buf = create_string_buffer(length) readbytes = libcrypto.BIO_read(self.bio, buf, length) if readbytes == -2: raise NotImplementedError('Function is not supported by' + 'this BIO') # depends on [control=['if'], data=[]] if readbytes == -1: raise IOError # depends on [control=['if'], data=[]] if readbytes == 0: return b'' # depends on [control=['if'], data=[]] return buf.raw[:readbytes] # depends on [control=['if'], data=[]] else: buf = create_string_buffer(1024) out = b'' readbytes = 1 while readbytes > 0: readbytes = libcrypto.BIO_read(self.bio, buf, 1024) if readbytes == -2: raise NotImplementedError('Function is not supported by ' + 'this BIO') # depends on [control=['if'], data=[]] if readbytes == -1: raise IOError # depends on [control=['if'], data=[]] if readbytes > 0: out += buf.raw[:readbytes] # depends on [control=['if'], data=['readbytes']] # depends on [control=['while'], data=['readbytes']] return out
def add_comments(self, comments): """ Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'message': 'inline message'}]) add_comments([{'filename': 'Makefile', 'range': {'start_line': 0, 'start_character': 1, 'end_line': 0, 'end_character': 5}, 'message': 'inline message'}]) """ for comment in comments: if 'filename' and 'message' in comment.keys(): msg = {} if 'range' in comment.keys(): msg = {"range": comment['range'], "message": comment['message']} elif 'line' in comment.keys(): msg = {"line": comment['line'], "message": comment['message']} else: continue file_comment = {comment['filename']: [msg]} if self.comments: if comment['filename'] in self.comments.keys(): self.comments[comment['filename']].append(msg) else: self.comments.update(file_comment) else: self.comments.update(file_comment)
def function[add_comments, parameter[self, comments]]: constant[ Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'message': 'inline message'}]) add_comments([{'filename': 'Makefile', 'range': {'start_line': 0, 'start_character': 1, 'end_line': 0, 'end_character': 5}, 'message': 'inline message'}]) ] for taget[name[comment]] in starred[name[comments]] begin[:] if <ast.BoolOp object at 0x7da1b101a110> begin[:] variable[msg] assign[=] dictionary[[], []] if compare[constant[range] in call[name[comment].keys, parameter[]]] begin[:] variable[msg] assign[=] dictionary[[<ast.Constant object at 0x7da1b1019d50>, <ast.Constant object at 0x7da1b101a290>], [<ast.Subscript object at 0x7da1b101b730>, <ast.Subscript object at 0x7da1b1018640>]] variable[file_comment] assign[=] dictionary[[<ast.Subscript object at 0x7da1b1019d20>], [<ast.List object at 0x7da1b1018430>]] if name[self].comments begin[:] if compare[call[name[comment]][constant[filename]] in call[name[self].comments.keys, parameter[]]] begin[:] call[call[name[self].comments][call[name[comment]][constant[filename]]].append, parameter[name[msg]]]
keyword[def] identifier[add_comments] ( identifier[self] , identifier[comments] ): literal[string] keyword[for] identifier[comment] keyword[in] identifier[comments] : keyword[if] literal[string] keyword[and] literal[string] keyword[in] identifier[comment] . identifier[keys] (): identifier[msg] ={} keyword[if] literal[string] keyword[in] identifier[comment] . identifier[keys] (): identifier[msg] ={ literal[string] : identifier[comment] [ literal[string] ], literal[string] : identifier[comment] [ literal[string] ]} keyword[elif] literal[string] keyword[in] identifier[comment] . identifier[keys] (): identifier[msg] ={ literal[string] : identifier[comment] [ literal[string] ], literal[string] : identifier[comment] [ literal[string] ]} keyword[else] : keyword[continue] identifier[file_comment] ={ identifier[comment] [ literal[string] ]:[ identifier[msg] ]} keyword[if] identifier[self] . identifier[comments] : keyword[if] identifier[comment] [ literal[string] ] keyword[in] identifier[self] . identifier[comments] . identifier[keys] (): identifier[self] . identifier[comments] [ identifier[comment] [ literal[string] ]]. identifier[append] ( identifier[msg] ) keyword[else] : identifier[self] . identifier[comments] . identifier[update] ( identifier[file_comment] ) keyword[else] : identifier[self] . identifier[comments] . identifier[update] ( identifier[file_comment] )
def add_comments(self, comments): """ Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'message': 'inline message'}]) add_comments([{'filename': 'Makefile', 'range': {'start_line': 0, 'start_character': 1, 'end_line': 0, 'end_character': 5}, 'message': 'inline message'}]) """ for comment in comments: if 'filename' and 'message' in comment.keys(): msg = {} if 'range' in comment.keys(): msg = {'range': comment['range'], 'message': comment['message']} # depends on [control=['if'], data=[]] elif 'line' in comment.keys(): msg = {'line': comment['line'], 'message': comment['message']} # depends on [control=['if'], data=[]] else: continue file_comment = {comment['filename']: [msg]} if self.comments: if comment['filename'] in self.comments.keys(): self.comments[comment['filename']].append(msg) # depends on [control=['if'], data=[]] else: self.comments.update(file_comment) # depends on [control=['if'], data=[]] else: self.comments.update(file_comment) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['comment']]
def valid_daily_min_temperature(comp, units='K'): r"""Decorator to check that a computation runs on a valid temperature dataset.""" @wraps(comp) def func(tasmin, *args, **kwds): check_valid_temperature(tasmin, units) check_valid(tasmin, 'cell_methods', 'time: minimum within days') return comp(tasmin, **kwds) return func
def function[valid_daily_min_temperature, parameter[comp, units]]: constant[Decorator to check that a computation runs on a valid temperature dataset.] def function[func, parameter[tasmin]]: call[name[check_valid_temperature], parameter[name[tasmin], name[units]]] call[name[check_valid], parameter[name[tasmin], constant[cell_methods], constant[time: minimum within days]]] return[call[name[comp], parameter[name[tasmin]]]] return[name[func]]
keyword[def] identifier[valid_daily_min_temperature] ( identifier[comp] , identifier[units] = literal[string] ): literal[string] @ identifier[wraps] ( identifier[comp] ) keyword[def] identifier[func] ( identifier[tasmin] ,* identifier[args] ,** identifier[kwds] ): identifier[check_valid_temperature] ( identifier[tasmin] , identifier[units] ) identifier[check_valid] ( identifier[tasmin] , literal[string] , literal[string] ) keyword[return] identifier[comp] ( identifier[tasmin] ,** identifier[kwds] ) keyword[return] identifier[func]
def valid_daily_min_temperature(comp, units='K'): """Decorator to check that a computation runs on a valid temperature dataset.""" @wraps(comp) def func(tasmin, *args, **kwds): check_valid_temperature(tasmin, units) check_valid(tasmin, 'cell_methods', 'time: minimum within days') return comp(tasmin, **kwds) return func
def _remove_attributes(attrs, remove_list): """ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. """ new_attrs = {} for attr in attrs.keys(): if attr not in remove_list: new_attrs[attr] = attrs[attr] return new_attrs
def function[_remove_attributes, parameter[attrs, remove_list]]: constant[ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. ] variable[new_attrs] assign[=] dictionary[[], []] for taget[name[attr]] in starred[call[name[attrs].keys, parameter[]]] begin[:] if compare[name[attr] <ast.NotIn object at 0x7da2590d7190> name[remove_list]] begin[:] call[name[new_attrs]][name[attr]] assign[=] call[name[attrs]][name[attr]] return[name[new_attrs]]
keyword[def] identifier[_remove_attributes] ( identifier[attrs] , identifier[remove_list] ): literal[string] identifier[new_attrs] ={} keyword[for] identifier[attr] keyword[in] identifier[attrs] . identifier[keys] (): keyword[if] identifier[attr] keyword[not] keyword[in] identifier[remove_list] : identifier[new_attrs] [ identifier[attr] ]= identifier[attrs] [ identifier[attr] ] keyword[return] identifier[new_attrs]
def _remove_attributes(attrs, remove_list): """ Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. """ new_attrs = {} for attr in attrs.keys(): if attr not in remove_list: new_attrs[attr] = attrs[attr] # depends on [control=['if'], data=['attr']] # depends on [control=['for'], data=['attr']] return new_attrs
def worker_exec(self, queue_timeout=2, req_timeout=5, max_retry=3, **kwargs): """Target method of workers. Firstly download the page and then call the :func:`parse` method. A parser thread will exit in either of the following cases: 1. All feeder threads have exited and the ``url_queue`` is empty. 2. Downloaded image number has reached required number. Args: queue_timeout (int): Timeout of getting urls from ``url_queue``. req_timeout (int): Timeout of making requests for downloading pages. max_retry (int): Max retry times if the request fails. **kwargs: Arguments to be passed to the :func:`parse` method. """ while True: if self.signal.get('reach_max_num'): self.logger.info('downloaded image reached max num, thread %s ' 'is ready to exit', current_thread().name) break # get the page url try: url = self.in_queue.get(timeout=queue_timeout) except queue.Empty: if self.signal.get('feeder_exited'): self.logger.info( 'no more page urls for thread %s to parse', current_thread().name) break else: self.logger.info('%s is waiting for new page urls', current_thread().name) continue except: self.logger.error('exception in thread %s', current_thread().name) continue else: self.logger.debug('start fetching page {}'.format(url)) # fetch and parse the page retry = max_retry while retry > 0: try: base_url = '{0.scheme}://{0.netloc}'.format(urlsplit(url)) response = self.session.get(url, timeout=req_timeout, headers={'Referer': base_url}) except Exception as e: self.logger.error( 'Exception caught when fetching page %s, ' 'error: %s, remaining retry times: %d', url, e, retry - 1) else: self.logger.info('parsing result page {}'.format(url)) for task in self.parse(response, **kwargs): while not self.signal.get('reach_max_num'): try: if isinstance(task, dict): self.output(task, timeout=1) elif isinstance(task, str): # this case only work for GreedyCrawler, # which need to feed the url back to # url_queue, dirty implementation self.input(task, timeout=1) except queue.Full: time.sleep(1) except Exception as e: self.logger.error( 'Exception caught when put task %s into ' 'queue, error: %s', task, url) else: break if self.signal.get('reach_max_num'): break self.in_queue.task_done() break finally: retry -= 1 self.logger.info('thread {} exit'.format(current_thread().name))
def function[worker_exec, parameter[self, queue_timeout, req_timeout, max_retry]]: constant[Target method of workers. Firstly download the page and then call the :func:`parse` method. A parser thread will exit in either of the following cases: 1. All feeder threads have exited and the ``url_queue`` is empty. 2. Downloaded image number has reached required number. Args: queue_timeout (int): Timeout of getting urls from ``url_queue``. req_timeout (int): Timeout of making requests for downloading pages. max_retry (int): Max retry times if the request fails. **kwargs: Arguments to be passed to the :func:`parse` method. ] while constant[True] begin[:] if call[name[self].signal.get, parameter[constant[reach_max_num]]] begin[:] call[name[self].logger.info, parameter[constant[downloaded image reached max num, thread %s is ready to exit], call[name[current_thread], parameter[]].name]] break <ast.Try object at 0x7da1b18bc550> variable[retry] assign[=] name[max_retry] while compare[name[retry] greater[>] constant[0]] begin[:] <ast.Try object at 0x7da1b18bd2a0> call[name[self].logger.info, parameter[call[constant[thread {} exit].format, parameter[call[name[current_thread], parameter[]].name]]]]
keyword[def] identifier[worker_exec] ( identifier[self] , identifier[queue_timeout] = literal[int] , identifier[req_timeout] = literal[int] , identifier[max_retry] = literal[int] , ** identifier[kwargs] ): literal[string] keyword[while] keyword[True] : keyword[if] identifier[self] . identifier[signal] . identifier[get] ( literal[string] ): identifier[self] . identifier[logger] . identifier[info] ( literal[string] literal[string] , identifier[current_thread] (). identifier[name] ) keyword[break] keyword[try] : identifier[url] = identifier[self] . identifier[in_queue] . identifier[get] ( identifier[timeout] = identifier[queue_timeout] ) keyword[except] identifier[queue] . identifier[Empty] : keyword[if] identifier[self] . identifier[signal] . identifier[get] ( literal[string] ): identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[current_thread] (). identifier[name] ) keyword[break] keyword[else] : identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[current_thread] (). identifier[name] ) keyword[continue] keyword[except] : identifier[self] . identifier[logger] . identifier[error] ( literal[string] , identifier[current_thread] (). identifier[name] ) keyword[continue] keyword[else] : identifier[self] . identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[url] )) identifier[retry] = identifier[max_retry] keyword[while] identifier[retry] > literal[int] : keyword[try] : identifier[base_url] = literal[string] . identifier[format] ( identifier[urlsplit] ( identifier[url] )) identifier[response] = identifier[self] . identifier[session] . identifier[get] ( identifier[url] , identifier[timeout] = identifier[req_timeout] , identifier[headers] ={ literal[string] : identifier[base_url] }) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[logger] . identifier[error] ( literal[string] literal[string] , identifier[url] , identifier[e] , identifier[retry] - literal[int] ) keyword[else] : identifier[self] . identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[url] )) keyword[for] identifier[task] keyword[in] identifier[self] . identifier[parse] ( identifier[response] ,** identifier[kwargs] ): keyword[while] keyword[not] identifier[self] . identifier[signal] . identifier[get] ( literal[string] ): keyword[try] : keyword[if] identifier[isinstance] ( identifier[task] , identifier[dict] ): identifier[self] . identifier[output] ( identifier[task] , identifier[timeout] = literal[int] ) keyword[elif] identifier[isinstance] ( identifier[task] , identifier[str] ): identifier[self] . identifier[input] ( identifier[task] , identifier[timeout] = literal[int] ) keyword[except] identifier[queue] . identifier[Full] : identifier[time] . identifier[sleep] ( literal[int] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[logger] . identifier[error] ( literal[string] literal[string] , identifier[task] , identifier[url] ) keyword[else] : keyword[break] keyword[if] identifier[self] . identifier[signal] . identifier[get] ( literal[string] ): keyword[break] identifier[self] . identifier[in_queue] . identifier[task_done] () keyword[break] keyword[finally] : identifier[retry] -= literal[int] identifier[self] . identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[current_thread] (). identifier[name] ))
def worker_exec(self, queue_timeout=2, req_timeout=5, max_retry=3, **kwargs): """Target method of workers. Firstly download the page and then call the :func:`parse` method. A parser thread will exit in either of the following cases: 1. All feeder threads have exited and the ``url_queue`` is empty. 2. Downloaded image number has reached required number. Args: queue_timeout (int): Timeout of getting urls from ``url_queue``. req_timeout (int): Timeout of making requests for downloading pages. max_retry (int): Max retry times if the request fails. **kwargs: Arguments to be passed to the :func:`parse` method. """ while True: if self.signal.get('reach_max_num'): self.logger.info('downloaded image reached max num, thread %s is ready to exit', current_thread().name) break # depends on [control=['if'], data=[]] # get the page url try: url = self.in_queue.get(timeout=queue_timeout) # depends on [control=['try'], data=[]] except queue.Empty: if self.signal.get('feeder_exited'): self.logger.info('no more page urls for thread %s to parse', current_thread().name) break # depends on [control=['if'], data=[]] else: self.logger.info('%s is waiting for new page urls', current_thread().name) continue # depends on [control=['except'], data=[]] except: self.logger.error('exception in thread %s', current_thread().name) continue # depends on [control=['except'], data=[]] else: self.logger.debug('start fetching page {}'.format(url)) # fetch and parse the page retry = max_retry while retry > 0: try: base_url = '{0.scheme}://{0.netloc}'.format(urlsplit(url)) response = self.session.get(url, timeout=req_timeout, headers={'Referer': base_url}) # depends on [control=['try'], data=[]] except Exception as e: self.logger.error('Exception caught when fetching page %s, error: %s, remaining retry times: %d', url, e, retry - 1) # depends on [control=['except'], data=['e']] else: self.logger.info('parsing result page {}'.format(url)) for task in self.parse(response, **kwargs): while not self.signal.get('reach_max_num'): try: if isinstance(task, dict): self.output(task, timeout=1) # depends on [control=['if'], data=[]] elif isinstance(task, str): # this case only work for GreedyCrawler, # which need to feed the url back to # url_queue, dirty implementation self.input(task, timeout=1) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except queue.Full: time.sleep(1) # depends on [control=['except'], data=[]] except Exception as e: self.logger.error('Exception caught when put task %s into queue, error: %s', task, url) # depends on [control=['except'], data=[]] else: break # depends on [control=['while'], data=[]] if self.signal.get('reach_max_num'): break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['task']] self.in_queue.task_done() break finally: retry -= 1 # depends on [control=['while'], data=['retry']] # depends on [control=['while'], data=[]] self.logger.info('thread {} exit'.format(current_thread().name))
def build_b(self): """build Bp and Bpp for fast decoupled method""" if not self.n: return method = self.system.pflow.config.method.lower() # Build B prime matrix y1 = mul( self.u, self.g1 ) # y1 neglects line charging shunt, and g1 is usually 0 in HV lines y2 = mul( self.u, self.g2 ) # y2 neglects line charging shunt, and g2 is usually 0 in HV lines m = polar(1.0, self.phi * deg2rad) # neglected tap ratio self.mconj = conj(m) m2 = matrix(1.0, (self.n, 1), 'z') if method in ('fdxb', 'dcpf'): # neglect line resistance in Bp in XB method y12 = div(self.u, self.x * 1j) else: y12 = div(self.u, self.r + self.x * 1j) self.Bp = spmatrix( div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z') self.Bp -= spmatrix( div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z') self.Bp -= spmatrix( div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z') self.Bp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb), 'z') self.Bp = self.Bp.imag() # Build B double prime matrix y1 = mul( self.u, self.g1 + self.b1 * 1j ) # y1 neglected line charging shunt, and g1 is usually 0 in HV lines y2 = mul( self.u, self.g2 + self.b2 * 1j ) # y2 neglected line charging shunt, and g2 is usually 0 in HV lines m = self.tap + 0j # neglected phase shifter m2 = abs(m)**2 + 0j if method in ('fdbx', 'fdpf', 'dcpf'): # neglect line resistance in Bpp in BX method y12 = div(self.u, self.x * 1j) else: y12 = div(self.u, self.r + self.x * 1j) self.Bpp = spmatrix( div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z') self.Bpp -= spmatrix( div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z') self.Bpp -= spmatrix( div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z') self.Bpp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb), 'z') self.Bpp = self.Bpp.imag() for item in range(self.nb): if abs(self.Bp[item, item]) == 0: self.Bp[item, item] = 1e-6 + 0j if abs(self.Bpp[item, item]) == 0: self.Bpp[item, item] = 1e-6 + 0j
def function[build_b, parameter[self]]: constant[build Bp and Bpp for fast decoupled method] if <ast.UnaryOp object at 0x7da18bc70640> begin[:] return[None] variable[method] assign[=] call[name[self].system.pflow.config.method.lower, parameter[]] variable[y1] assign[=] call[name[mul], parameter[name[self].u, name[self].g1]] variable[y2] assign[=] call[name[mul], parameter[name[self].u, name[self].g2]] variable[m] assign[=] call[name[polar], parameter[constant[1.0], binary_operation[name[self].phi * name[deg2rad]]]] name[self].mconj assign[=] call[name[conj], parameter[name[m]]] variable[m2] assign[=] call[name[matrix], parameter[constant[1.0], tuple[[<ast.Attribute object at 0x7da18dc07c10>, <ast.Constant object at 0x7da18dc05720>]], constant[z]]] if compare[name[method] in tuple[[<ast.Constant object at 0x7da18dc07e20>, <ast.Constant object at 0x7da18dc05a80>]]] begin[:] variable[y12] assign[=] call[name[div], parameter[name[self].u, binary_operation[name[self].x * constant[1j]]]] name[self].Bp assign[=] call[name[spmatrix], parameter[call[name[div], parameter[binary_operation[name[y12] + name[y1]], name[m2]]], name[self].a1, name[self].a1, tuple[[<ast.Attribute object at 0x7da18dc07460>, <ast.Attribute object at 0x7da18dc060b0>]], constant[z]]] <ast.AugAssign object at 0x7da18dc06bf0> <ast.AugAssign object at 0x7da18dc05810> <ast.AugAssign object at 0x7da18dc074f0> name[self].Bp assign[=] call[name[self].Bp.imag, parameter[]] variable[y1] assign[=] call[name[mul], parameter[name[self].u, binary_operation[name[self].g1 + binary_operation[name[self].b1 * constant[1j]]]]] variable[y2] assign[=] call[name[mul], parameter[name[self].u, binary_operation[name[self].g2 + binary_operation[name[self].b2 * constant[1j]]]]] variable[m] assign[=] binary_operation[name[self].tap + constant[0j]] variable[m2] assign[=] binary_operation[binary_operation[call[name[abs], parameter[name[m]]] ** constant[2]] + constant[0j]] if compare[name[method] in tuple[[<ast.Constant object at 0x7da18dc041f0>, <ast.Constant object at 0x7da18dc045b0>, <ast.Constant object at 0x7da18dc05360>]]] begin[:] variable[y12] assign[=] call[name[div], parameter[name[self].u, binary_operation[name[self].x * constant[1j]]]] name[self].Bpp assign[=] call[name[spmatrix], parameter[call[name[div], parameter[binary_operation[name[y12] + name[y1]], name[m2]]], name[self].a1, name[self].a1, tuple[[<ast.Attribute object at 0x7da18dc06f80>, <ast.Attribute object at 0x7da18dc06470>]], constant[z]]] <ast.AugAssign object at 0x7da18dc07640> <ast.AugAssign object at 0x7da18dc07160> <ast.AugAssign object at 0x7da18dc044f0> name[self].Bpp assign[=] call[name[self].Bpp.imag, parameter[]] for taget[name[item]] in starred[call[name[range], parameter[name[self].nb]]] begin[:] if compare[call[name[abs], parameter[call[name[self].Bp][tuple[[<ast.Name object at 0x7da207f01c30>, <ast.Name object at 0x7da207f002b0>]]]]] equal[==] constant[0]] begin[:] call[name[self].Bp][tuple[[<ast.Name object at 0x7da207f00d90>, <ast.Name object at 0x7da207f01930>]]] assign[=] binary_operation[constant[1e-06] + constant[0j]] if compare[call[name[abs], parameter[call[name[self].Bpp][tuple[[<ast.Name object at 0x7da207f00f70>, <ast.Name object at 0x7da207f00910>]]]]] equal[==] constant[0]] begin[:] call[name[self].Bpp][tuple[[<ast.Name object at 0x7da207f00dc0>, <ast.Name object at 0x7da207f011e0>]]] assign[=] binary_operation[constant[1e-06] + constant[0j]]
keyword[def] identifier[build_b] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[n] : keyword[return] identifier[method] = identifier[self] . identifier[system] . identifier[pflow] . identifier[config] . identifier[method] . identifier[lower] () identifier[y1] = identifier[mul] ( identifier[self] . identifier[u] , identifier[self] . identifier[g1] ) identifier[y2] = identifier[mul] ( identifier[self] . identifier[u] , identifier[self] . identifier[g2] ) identifier[m] = identifier[polar] ( literal[int] , identifier[self] . identifier[phi] * identifier[deg2rad] ) identifier[self] . identifier[mconj] = identifier[conj] ( identifier[m] ) identifier[m2] = identifier[matrix] ( literal[int] ,( identifier[self] . identifier[n] , literal[int] ), literal[string] ) keyword[if] identifier[method] keyword[in] ( literal[string] , literal[string] ): identifier[y12] = identifier[div] ( identifier[self] . identifier[u] , identifier[self] . identifier[x] * literal[int] ) keyword[else] : identifier[y12] = identifier[div] ( identifier[self] . identifier[u] , identifier[self] . identifier[r] + identifier[self] . identifier[x] * literal[int] ) identifier[self] . identifier[Bp] = identifier[spmatrix] ( identifier[div] ( identifier[y12] + identifier[y1] , identifier[m2] ), identifier[self] . identifier[a1] , identifier[self] . identifier[a1] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bp] -= identifier[spmatrix] ( identifier[div] ( identifier[y12] , identifier[conj] ( identifier[m] )), identifier[self] . identifier[a1] , identifier[self] . identifier[a2] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bp] -= identifier[spmatrix] ( identifier[div] ( identifier[y12] , identifier[m] ), identifier[self] . identifier[a2] , identifier[self] . identifier[a1] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bp] += identifier[spmatrix] ( identifier[y12] + identifier[y2] , identifier[self] . identifier[a2] , identifier[self] . identifier[a2] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bp] = identifier[self] . identifier[Bp] . identifier[imag] () identifier[y1] = identifier[mul] ( identifier[self] . identifier[u] , identifier[self] . identifier[g1] + identifier[self] . identifier[b1] * literal[int] ) identifier[y2] = identifier[mul] ( identifier[self] . identifier[u] , identifier[self] . identifier[g2] + identifier[self] . identifier[b2] * literal[int] ) identifier[m] = identifier[self] . identifier[tap] + literal[int] identifier[m2] = identifier[abs] ( identifier[m] )** literal[int] + literal[int] keyword[if] identifier[method] keyword[in] ( literal[string] , literal[string] , literal[string] ): identifier[y12] = identifier[div] ( identifier[self] . identifier[u] , identifier[self] . identifier[x] * literal[int] ) keyword[else] : identifier[y12] = identifier[div] ( identifier[self] . identifier[u] , identifier[self] . identifier[r] + identifier[self] . identifier[x] * literal[int] ) identifier[self] . identifier[Bpp] = identifier[spmatrix] ( identifier[div] ( identifier[y12] + identifier[y1] , identifier[m2] ), identifier[self] . identifier[a1] , identifier[self] . identifier[a1] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bpp] -= identifier[spmatrix] ( identifier[div] ( identifier[y12] , identifier[conj] ( identifier[m] )), identifier[self] . identifier[a1] , identifier[self] . identifier[a2] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bpp] -= identifier[spmatrix] ( identifier[div] ( identifier[y12] , identifier[m] ), identifier[self] . identifier[a2] , identifier[self] . identifier[a1] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bpp] += identifier[spmatrix] ( identifier[y12] + identifier[y2] , identifier[self] . identifier[a2] , identifier[self] . identifier[a2] ,( identifier[self] . identifier[nb] , identifier[self] . identifier[nb] ), literal[string] ) identifier[self] . identifier[Bpp] = identifier[self] . identifier[Bpp] . identifier[imag] () keyword[for] identifier[item] keyword[in] identifier[range] ( identifier[self] . identifier[nb] ): keyword[if] identifier[abs] ( identifier[self] . identifier[Bp] [ identifier[item] , identifier[item] ])== literal[int] : identifier[self] . identifier[Bp] [ identifier[item] , identifier[item] ]= literal[int] + literal[int] keyword[if] identifier[abs] ( identifier[self] . identifier[Bpp] [ identifier[item] , identifier[item] ])== literal[int] : identifier[self] . identifier[Bpp] [ identifier[item] , identifier[item] ]= literal[int] + literal[int]
def build_b(self): """build Bp and Bpp for fast decoupled method""" if not self.n: return # depends on [control=['if'], data=[]] method = self.system.pflow.config.method.lower() # Build B prime matrix y1 = mul(self.u, self.g1) # y1 neglects line charging shunt, and g1 is usually 0 in HV lines y2 = mul(self.u, self.g2) # y2 neglects line charging shunt, and g2 is usually 0 in HV lines m = polar(1.0, self.phi * deg2rad) # neglected tap ratio self.mconj = conj(m) m2 = matrix(1.0, (self.n, 1), 'z') if method in ('fdxb', 'dcpf'): # neglect line resistance in Bp in XB method y12 = div(self.u, self.x * 1j) # depends on [control=['if'], data=[]] else: y12 = div(self.u, self.r + self.x * 1j) self.Bp = spmatrix(div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z') self.Bp -= spmatrix(div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z') self.Bp -= spmatrix(div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z') self.Bp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb), 'z') self.Bp = self.Bp.imag() # Build B double prime matrix y1 = mul(self.u, self.g1 + self.b1 * 1j) # y1 neglected line charging shunt, and g1 is usually 0 in HV lines y2 = mul(self.u, self.g2 + self.b2 * 1j) # y2 neglected line charging shunt, and g2 is usually 0 in HV lines m = self.tap + 0j # neglected phase shifter m2 = abs(m) ** 2 + 0j if method in ('fdbx', 'fdpf', 'dcpf'): # neglect line resistance in Bpp in BX method y12 = div(self.u, self.x * 1j) # depends on [control=['if'], data=[]] else: y12 = div(self.u, self.r + self.x * 1j) self.Bpp = spmatrix(div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z') self.Bpp -= spmatrix(div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z') self.Bpp -= spmatrix(div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z') self.Bpp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb), 'z') self.Bpp = self.Bpp.imag() for item in range(self.nb): if abs(self.Bp[item, item]) == 0: self.Bp[item, item] = 1e-06 + 0j # depends on [control=['if'], data=[]] if abs(self.Bpp[item, item]) == 0: self.Bpp[item, item] = 1e-06 + 0j # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['item']]
def p_statement(self, p): ''' statement : create_table_statement SEMICOLON | insert_into_statement SEMICOLON | create_rop_statement SEMICOLON | create_index_statement SEMICOLON ''' p[0] = p[1] p[0].offset = p.lexpos(1) p[0].lineno = p.lineno(1) p[0].filename = p.lexer.filename
def function[p_statement, parameter[self, p]]: constant[ statement : create_table_statement SEMICOLON | insert_into_statement SEMICOLON | create_rop_statement SEMICOLON | create_index_statement SEMICOLON ] call[name[p]][constant[0]] assign[=] call[name[p]][constant[1]] call[name[p]][constant[0]].offset assign[=] call[name[p].lexpos, parameter[constant[1]]] call[name[p]][constant[0]].lineno assign[=] call[name[p].lineno, parameter[constant[1]]] call[name[p]][constant[0]].filename assign[=] name[p].lexer.filename
keyword[def] identifier[p_statement] ( identifier[self] , identifier[p] ): literal[string] identifier[p] [ literal[int] ]= identifier[p] [ literal[int] ] identifier[p] [ literal[int] ]. identifier[offset] = identifier[p] . identifier[lexpos] ( literal[int] ) identifier[p] [ literal[int] ]. identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ) identifier[p] [ literal[int] ]. identifier[filename] = identifier[p] . identifier[lexer] . identifier[filename]
def p_statement(self, p): """ statement : create_table_statement SEMICOLON | insert_into_statement SEMICOLON | create_rop_statement SEMICOLON | create_index_statement SEMICOLON """ p[0] = p[1] p[0].offset = p.lexpos(1) p[0].lineno = p.lineno(1) p[0].filename = p.lexer.filename
def get_spec(self): """ Parse this process (if it has not already been parsed), and return the workflow spec. """ if self.is_parsed: return self.spec if self.parsing_started: raise NotImplementedError( 'Recursive call Activities are not supported.') self._parse() return self.get_spec()
def function[get_spec, parameter[self]]: constant[ Parse this process (if it has not already been parsed), and return the workflow spec. ] if name[self].is_parsed begin[:] return[name[self].spec] if name[self].parsing_started begin[:] <ast.Raise object at 0x7da1b016f910> call[name[self]._parse, parameter[]] return[call[name[self].get_spec, parameter[]]]
keyword[def] identifier[get_spec] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[is_parsed] : keyword[return] identifier[self] . identifier[spec] keyword[if] identifier[self] . identifier[parsing_started] : keyword[raise] identifier[NotImplementedError] ( literal[string] ) identifier[self] . identifier[_parse] () keyword[return] identifier[self] . identifier[get_spec] ()
def get_spec(self): """ Parse this process (if it has not already been parsed), and return the workflow spec. """ if self.is_parsed: return self.spec # depends on [control=['if'], data=[]] if self.parsing_started: raise NotImplementedError('Recursive call Activities are not supported.') # depends on [control=['if'], data=[]] self._parse() return self.get_spec()
def levels(self): """ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` """ ret = [[] for i in range(self.height)] for node in self.subtree: ret[node.level - self.level].append(node) return ret
def function[levels, parameter[self]]: constant[ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` ] variable[ret] assign[=] <ast.ListComp object at 0x7da2054a41f0> for taget[name[node]] in starred[name[self].subtree] begin[:] call[call[name[ret]][binary_operation[name[node].level - name[self].level]].append, parameter[name[node]]] return[name[ret]]
keyword[def] identifier[levels] ( identifier[self] ): literal[string] identifier[ret] =[[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[height] )] keyword[for] identifier[node] keyword[in] identifier[self] . identifier[subtree] : identifier[ret] [ identifier[node] . identifier[level] - identifier[self] . identifier[level] ]. identifier[append] ( identifier[node] ) keyword[return] identifier[ret]
def levels(self): """ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` """ ret = [[] for i in range(self.height)] for node in self.subtree: ret[node.level - self.level].append(node) # depends on [control=['for'], data=['node']] return ret
def destroy(self, folder=None, as_coro=False): """Destroy the multiprocessing environment and its slave environments. """ async def _destroy(folder): ret = self.save_info(folder) await self.stop_slaves() # Terminate and join the process pool when we are destroyed. # Do not wait for unfinished processed with pool.close(), # the slaves should be anyway already stopped. if self._pool is not None: self._pool.terminate() self._pool.join() await self._env.shutdown(as_coro=True) return ret return run_or_coro(_destroy(folder), as_coro)
def function[destroy, parameter[self, folder, as_coro]]: constant[Destroy the multiprocessing environment and its slave environments. ] <ast.AsyncFunctionDef object at 0x7da18bcca800> return[call[name[run_or_coro], parameter[call[name[_destroy], parameter[name[folder]]], name[as_coro]]]]
keyword[def] identifier[destroy] ( identifier[self] , identifier[folder] = keyword[None] , identifier[as_coro] = keyword[False] ): literal[string] keyword[async] keyword[def] identifier[_destroy] ( identifier[folder] ): identifier[ret] = identifier[self] . identifier[save_info] ( identifier[folder] ) keyword[await] identifier[self] . identifier[stop_slaves] () keyword[if] identifier[self] . identifier[_pool] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[_pool] . identifier[terminate] () identifier[self] . identifier[_pool] . identifier[join] () keyword[await] identifier[self] . identifier[_env] . identifier[shutdown] ( identifier[as_coro] = keyword[True] ) keyword[return] identifier[ret] keyword[return] identifier[run_or_coro] ( identifier[_destroy] ( identifier[folder] ), identifier[as_coro] )
def destroy(self, folder=None, as_coro=False): """Destroy the multiprocessing environment and its slave environments. """ async def _destroy(folder): ret = self.save_info(folder) await self.stop_slaves() # Terminate and join the process pool when we are destroyed. # Do not wait for unfinished processed with pool.close(), # the slaves should be anyway already stopped. if self._pool is not None: self._pool.terminate() self._pool.join() # depends on [control=['if'], data=[]] await self._env.shutdown(as_coro=True) return ret return run_or_coro(_destroy(folder), as_coro)
def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines. whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings. doc = pep257.trim(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space. # 1) keep double new lines; # 2) keep ws after new lines if not empty line; # 3) all other new lines shall be changed to a space; # Solution: Match new lines between non white space and replace with space. doc = re.sub(r'(?<=\S)\n(?=\S)', ' ', doc, flags=re.M) return doc
def function[DocToHelp, parameter[doc]]: constant[Takes a __doc__ string and reformats it as help.] variable[doc] assign[=] call[name[doc].strip, parameter[]] variable[whitespace_only_line] assign[=] call[name[re].compile, parameter[constant[^[ ]+$], name[re].M]] variable[doc] assign[=] call[name[whitespace_only_line].sub, parameter[constant[], name[doc]]] variable[doc] assign[=] call[name[pep257].trim, parameter[name[doc]]] variable[doc] assign[=] call[name[re].sub, parameter[constant[(?<=\S)\n(?=\S)], constant[ ], name[doc]]] return[name[doc]]
keyword[def] identifier[DocToHelp] ( identifier[doc] ): literal[string] identifier[doc] = identifier[doc] . identifier[strip] () identifier[whitespace_only_line] = identifier[re] . identifier[compile] ( literal[string] , identifier[re] . identifier[M] ) identifier[doc] = identifier[whitespace_only_line] . identifier[sub] ( literal[string] , identifier[doc] ) identifier[doc] = identifier[pep257] . identifier[trim] ( identifier[doc] ) identifier[doc] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[doc] , identifier[flags] = identifier[re] . identifier[M] ) keyword[return] identifier[doc]
def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines. whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings. doc = pep257.trim(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space. # 1) keep double new lines; # 2) keep ws after new lines if not empty line; # 3) all other new lines shall be changed to a space; # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\\S)\\n(?=\\S)', ' ', doc, flags=re.M) return doc
async def send_request(self, connection: Connection, payment_handle: int): """ Approves the credential offer and submits a credential request. The result will be a credential stored in the prover's wallet. :param connection: connection to submit request from :param payment_handle: currently unused :return: Example: connection = await Connection.create(source_id) await connection.connect(phone_number) credential = await Credential.create(source_id, offer) await credential.send_request(connection, 0) """ if not hasattr(Credential.send_request, "cb"): self.logger.debug("vcx_credential_send_request: Creating callback") Credential.send_request.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32)) c_credential_handle = c_uint32(self.handle) c_connection_handle = c_uint32(connection.handle) c_payment = c_uint32(payment_handle) await do_call('vcx_credential_send_request', c_credential_handle, c_connection_handle, c_payment, Credential.send_request.cb)
<ast.AsyncFunctionDef object at 0x7da1b1f4b2e0>
keyword[async] keyword[def] identifier[send_request] ( identifier[self] , identifier[connection] : identifier[Connection] , identifier[payment_handle] : identifier[int] ): literal[string] keyword[if] keyword[not] identifier[hasattr] ( identifier[Credential] . identifier[send_request] , literal[string] ): identifier[self] . identifier[logger] . identifier[debug] ( literal[string] ) identifier[Credential] . identifier[send_request] . identifier[cb] = identifier[create_cb] ( identifier[CFUNCTYPE] ( keyword[None] , identifier[c_uint32] , identifier[c_uint32] )) identifier[c_credential_handle] = identifier[c_uint32] ( identifier[self] . identifier[handle] ) identifier[c_connection_handle] = identifier[c_uint32] ( identifier[connection] . identifier[handle] ) identifier[c_payment] = identifier[c_uint32] ( identifier[payment_handle] ) keyword[await] identifier[do_call] ( literal[string] , identifier[c_credential_handle] , identifier[c_connection_handle] , identifier[c_payment] , identifier[Credential] . identifier[send_request] . identifier[cb] )
async def send_request(self, connection: Connection, payment_handle: int): """ Approves the credential offer and submits a credential request. The result will be a credential stored in the prover's wallet. :param connection: connection to submit request from :param payment_handle: currently unused :return: Example: connection = await Connection.create(source_id) await connection.connect(phone_number) credential = await Credential.create(source_id, offer) await credential.send_request(connection, 0) """ if not hasattr(Credential.send_request, 'cb'): self.logger.debug('vcx_credential_send_request: Creating callback') Credential.send_request.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32)) # depends on [control=['if'], data=[]] c_credential_handle = c_uint32(self.handle) c_connection_handle = c_uint32(connection.handle) c_payment = c_uint32(payment_handle) await do_call('vcx_credential_send_request', c_credential_handle, c_connection_handle, c_payment, Credential.send_request.cb)
def get_text_with_eol(self): """Same as 'toPlainText', replace '\n' by correct end-of-line characters""" utext = to_text_string(self.toPlainText()) lines = utext.splitlines() linesep = self.get_line_separator() txt = linesep.join(lines) if utext.endswith('\n'): txt += linesep return txt
def function[get_text_with_eol, parameter[self]]: constant[Same as 'toPlainText', replace ' ' by correct end-of-line characters] variable[utext] assign[=] call[name[to_text_string], parameter[call[name[self].toPlainText, parameter[]]]] variable[lines] assign[=] call[name[utext].splitlines, parameter[]] variable[linesep] assign[=] call[name[self].get_line_separator, parameter[]] variable[txt] assign[=] call[name[linesep].join, parameter[name[lines]]] if call[name[utext].endswith, parameter[constant[ ]]] begin[:] <ast.AugAssign object at 0x7da20c76ee30> return[name[txt]]
keyword[def] identifier[get_text_with_eol] ( identifier[self] ): literal[string] identifier[utext] = identifier[to_text_string] ( identifier[self] . identifier[toPlainText] ()) identifier[lines] = identifier[utext] . identifier[splitlines] () identifier[linesep] = identifier[self] . identifier[get_line_separator] () identifier[txt] = identifier[linesep] . identifier[join] ( identifier[lines] ) keyword[if] identifier[utext] . identifier[endswith] ( literal[string] ): identifier[txt] += identifier[linesep] keyword[return] identifier[txt]
def get_text_with_eol(self): """Same as 'toPlainText', replace ' ' by correct end-of-line characters""" utext = to_text_string(self.toPlainText()) lines = utext.splitlines() linesep = self.get_line_separator() txt = linesep.join(lines) if utext.endswith('\n'): txt += linesep # depends on [control=['if'], data=[]] return txt
def dict_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: APDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: use_dict = as_class() # call the parent classes self.apci_contents(use_dict=use_dict, as_class=as_class) self.apdu_contents(use_dict=use_dict, as_class=as_class) # return what we built/updated return use_dict
def function[dict_contents, parameter[self, use_dict, as_class]]: constant[Return the contents of an object as a dict.] if name[_debug] begin[:] call[name[APDU]._debug, parameter[constant[dict_contents use_dict=%r as_class=%r], name[use_dict], name[as_class]]] if compare[name[use_dict] is constant[None]] begin[:] variable[use_dict] assign[=] call[name[as_class], parameter[]] call[name[self].apci_contents, parameter[]] call[name[self].apdu_contents, parameter[]] return[name[use_dict]]
keyword[def] identifier[dict_contents] ( identifier[self] , identifier[use_dict] = keyword[None] , identifier[as_class] = identifier[dict] ): literal[string] keyword[if] identifier[_debug] : identifier[APDU] . identifier[_debug] ( literal[string] , identifier[use_dict] , identifier[as_class] ) keyword[if] identifier[use_dict] keyword[is] keyword[None] : identifier[use_dict] = identifier[as_class] () identifier[self] . identifier[apci_contents] ( identifier[use_dict] = identifier[use_dict] , identifier[as_class] = identifier[as_class] ) identifier[self] . identifier[apdu_contents] ( identifier[use_dict] = identifier[use_dict] , identifier[as_class] = identifier[as_class] ) keyword[return] identifier[use_dict]
def dict_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: APDU._debug('dict_contents use_dict=%r as_class=%r', use_dict, as_class) # depends on [control=['if'], data=[]] # make/extend the dictionary of content if use_dict is None: use_dict = as_class() # depends on [control=['if'], data=['use_dict']] # call the parent classes self.apci_contents(use_dict=use_dict, as_class=as_class) self.apdu_contents(use_dict=use_dict, as_class=as_class) # return what we built/updated return use_dict
def execute(self, method, args, ref): """ Execute the method with args """ response = {'result': None, 'error': None, 'ref': ref} fun = self.methods.get(method) if not fun: response['error'] = 'Method `{}` not found'.format(method) else: try: response['result'] = fun(*args) except Exception as exception: logging.error(exception, exc_info=1) response['error'] = str(exception) return response
def function[execute, parameter[self, method, args, ref]]: constant[ Execute the method with args ] variable[response] assign[=] dictionary[[<ast.Constant object at 0x7da1b10220b0>, <ast.Constant object at 0x7da1b1021a50>, <ast.Constant object at 0x7da1b10206a0>], [<ast.Constant object at 0x7da1b11744c0>, <ast.Constant object at 0x7da1b1175150>, <ast.Name object at 0x7da1b1175270>]] variable[fun] assign[=] call[name[self].methods.get, parameter[name[method]]] if <ast.UnaryOp object at 0x7da1b10796c0> begin[:] call[name[response]][constant[error]] assign[=] call[constant[Method `{}` not found].format, parameter[name[method]]] return[name[response]]
keyword[def] identifier[execute] ( identifier[self] , identifier[method] , identifier[args] , identifier[ref] ): literal[string] identifier[response] ={ literal[string] : keyword[None] , literal[string] : keyword[None] , literal[string] : identifier[ref] } identifier[fun] = identifier[self] . identifier[methods] . identifier[get] ( identifier[method] ) keyword[if] keyword[not] identifier[fun] : identifier[response] [ literal[string] ]= literal[string] . identifier[format] ( identifier[method] ) keyword[else] : keyword[try] : identifier[response] [ literal[string] ]= identifier[fun] (* identifier[args] ) keyword[except] identifier[Exception] keyword[as] identifier[exception] : identifier[logging] . identifier[error] ( identifier[exception] , identifier[exc_info] = literal[int] ) identifier[response] [ literal[string] ]= identifier[str] ( identifier[exception] ) keyword[return] identifier[response]
def execute(self, method, args, ref): """ Execute the method with args """ response = {'result': None, 'error': None, 'ref': ref} fun = self.methods.get(method) if not fun: response['error'] = 'Method `{}` not found'.format(method) # depends on [control=['if'], data=[]] else: try: response['result'] = fun(*args) # depends on [control=['try'], data=[]] except Exception as exception: logging.error(exception, exc_info=1) response['error'] = str(exception) # depends on [control=['except'], data=['exception']] return response
def get_domain_workgroup(): ''' Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ''' with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} else: return {'Workgroup': computer.Workgroup}
def function[get_domain_workgroup, parameter[]]: constant[ Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup ] with call[name[salt].utils.winapi.Com, parameter[]] begin[:] variable[conn] assign[=] call[name[wmi].WMI, parameter[]] for taget[name[computer]] in starred[call[name[conn].Win32_ComputerSystem, parameter[]]] begin[:] if name[computer].PartOfDomain begin[:] return[dictionary[[<ast.Constant object at 0x7da18bc71300>], [<ast.Attribute object at 0x7da18bc711e0>]]]
keyword[def] identifier[get_domain_workgroup] (): literal[string] keyword[with] identifier[salt] . identifier[utils] . identifier[winapi] . identifier[Com] (): identifier[conn] = identifier[wmi] . identifier[WMI] () keyword[for] identifier[computer] keyword[in] identifier[conn] . identifier[Win32_ComputerSystem] (): keyword[if] identifier[computer] . identifier[PartOfDomain] : keyword[return] { literal[string] : identifier[computer] . identifier[Domain] } keyword[else] : keyword[return] { literal[string] : identifier[computer] . identifier[Workgroup] }
def get_domain_workgroup(): """ Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup """ with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {'Domain': computer.Domain} # depends on [control=['if'], data=[]] else: return {'Workgroup': computer.Workgroup} # depends on [control=['for'], data=['computer']] # depends on [control=['with'], data=[]]
def read_entry(self): """read the next bed entry from the stream""" line = self.fh.readline() if not line: return None m = re.match('([^\t]+)\t(\d+)\t(\d+)\t*(.*)',line.rstrip()) if not m: sys.stderr.write("ERROR: unknown line in bed format file\n"+line+"\n") sys.exit() g = GenomicRange(m.group(1),int(m.group(2))+1,int(m.group(3))) if len(m.group(4)) > 0: g.set_payload(m.group(4)) return g
def function[read_entry, parameter[self]]: constant[read the next bed entry from the stream] variable[line] assign[=] call[name[self].fh.readline, parameter[]] if <ast.UnaryOp object at 0x7da18c4cfe20> begin[:] return[constant[None]] variable[m] assign[=] call[name[re].match, parameter[constant[([^ ]+) (\d+) (\d+) *(.*)], call[name[line].rstrip, parameter[]]]] if <ast.UnaryOp object at 0x7da18c4cc9d0> begin[:] call[name[sys].stderr.write, parameter[binary_operation[binary_operation[constant[ERROR: unknown line in bed format file ] + name[line]] + constant[ ]]]] call[name[sys].exit, parameter[]] variable[g] assign[=] call[name[GenomicRange], parameter[call[name[m].group, parameter[constant[1]]], binary_operation[call[name[int], parameter[call[name[m].group, parameter[constant[2]]]]] + constant[1]], call[name[int], parameter[call[name[m].group, parameter[constant[3]]]]]]] if compare[call[name[len], parameter[call[name[m].group, parameter[constant[4]]]]] greater[>] constant[0]] begin[:] call[name[g].set_payload, parameter[call[name[m].group, parameter[constant[4]]]]] return[name[g]]
keyword[def] identifier[read_entry] ( identifier[self] ): literal[string] identifier[line] = identifier[self] . identifier[fh] . identifier[readline] () keyword[if] keyword[not] identifier[line] : keyword[return] keyword[None] identifier[m] = identifier[re] . identifier[match] ( literal[string] , identifier[line] . identifier[rstrip] ()) keyword[if] keyword[not] identifier[m] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] + identifier[line] + literal[string] ) identifier[sys] . identifier[exit] () identifier[g] = identifier[GenomicRange] ( identifier[m] . identifier[group] ( literal[int] ), identifier[int] ( identifier[m] . identifier[group] ( literal[int] ))+ literal[int] , identifier[int] ( identifier[m] . identifier[group] ( literal[int] ))) keyword[if] identifier[len] ( identifier[m] . identifier[group] ( literal[int] ))> literal[int] : identifier[g] . identifier[set_payload] ( identifier[m] . identifier[group] ( literal[int] )) keyword[return] identifier[g]
def read_entry(self): """read the next bed entry from the stream""" line = self.fh.readline() if not line: return None # depends on [control=['if'], data=[]] m = re.match('([^\t]+)\t(\\d+)\t(\\d+)\t*(.*)', line.rstrip()) if not m: sys.stderr.write('ERROR: unknown line in bed format file\n' + line + '\n') sys.exit() # depends on [control=['if'], data=[]] g = GenomicRange(m.group(1), int(m.group(2)) + 1, int(m.group(3))) if len(m.group(4)) > 0: g.set_payload(m.group(4)) # depends on [control=['if'], data=[]] return g
def get_messenger(config): """Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email. """ email_settings = EmailConfig(config) if config.get("mode") == "debug": return DebugMessenger(email_settings) problems = email_settings.validate() if problems: logger.info(problems + " Will log errors instead of emailing them.") return DebugMessenger(email_settings) return EmailingMessenger(email_settings)
def function[get_messenger, parameter[config]]: constant[Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email. ] variable[email_settings] assign[=] call[name[EmailConfig], parameter[name[config]]] if compare[call[name[config].get, parameter[constant[mode]]] equal[==] constant[debug]] begin[:] return[call[name[DebugMessenger], parameter[name[email_settings]]]] variable[problems] assign[=] call[name[email_settings].validate, parameter[]] if name[problems] begin[:] call[name[logger].info, parameter[binary_operation[name[problems] + constant[ Will log errors instead of emailing them.]]]] return[call[name[DebugMessenger], parameter[name[email_settings]]]] return[call[name[EmailingMessenger], parameter[name[email_settings]]]]
keyword[def] identifier[get_messenger] ( identifier[config] ): literal[string] identifier[email_settings] = identifier[EmailConfig] ( identifier[config] ) keyword[if] identifier[config] . identifier[get] ( literal[string] )== literal[string] : keyword[return] identifier[DebugMessenger] ( identifier[email_settings] ) identifier[problems] = identifier[email_settings] . identifier[validate] () keyword[if] identifier[problems] : identifier[logger] . identifier[info] ( identifier[problems] + literal[string] ) keyword[return] identifier[DebugMessenger] ( identifier[email_settings] ) keyword[return] identifier[EmailingMessenger] ( identifier[email_settings] )
def get_messenger(config): """Return an appropriate Messenger. If we're in debug mode, or email settings aren't set, return a debug version which logs the message instead of attempting to send a real email. """ email_settings = EmailConfig(config) if config.get('mode') == 'debug': return DebugMessenger(email_settings) # depends on [control=['if'], data=[]] problems = email_settings.validate() if problems: logger.info(problems + ' Will log errors instead of emailing them.') return DebugMessenger(email_settings) # depends on [control=['if'], data=[]] return EmailingMessenger(email_settings)
def within_limits(self, value): """ check whether a value falls within the set limits :parameter value: float or Quantity to test. If value is a float, it is assumed that it has the same units as default_units """ if isinstance(value, int) or isinstance(value, float): value = value * self.default_unit return (self.limits[0] is None or value >= self.limits[0]) and (self.limits[1] is None or value <= self.limits[1])
def function[within_limits, parameter[self, value]]: constant[ check whether a value falls within the set limits :parameter value: float or Quantity to test. If value is a float, it is assumed that it has the same units as default_units ] if <ast.BoolOp object at 0x7da1b26ad840> begin[:] variable[value] assign[=] binary_operation[name[value] * name[self].default_unit] return[<ast.BoolOp object at 0x7da1b26ac880>]
keyword[def] identifier[within_limits] ( identifier[self] , identifier[value] ): literal[string] keyword[if] identifier[isinstance] ( identifier[value] , identifier[int] ) keyword[or] identifier[isinstance] ( identifier[value] , identifier[float] ): identifier[value] = identifier[value] * identifier[self] . identifier[default_unit] keyword[return] ( identifier[self] . identifier[limits] [ literal[int] ] keyword[is] keyword[None] keyword[or] identifier[value] >= identifier[self] . identifier[limits] [ literal[int] ]) keyword[and] ( identifier[self] . identifier[limits] [ literal[int] ] keyword[is] keyword[None] keyword[or] identifier[value] <= identifier[self] . identifier[limits] [ literal[int] ])
def within_limits(self, value): """ check whether a value falls within the set limits :parameter value: float or Quantity to test. If value is a float, it is assumed that it has the same units as default_units """ if isinstance(value, int) or isinstance(value, float): value = value * self.default_unit # depends on [control=['if'], data=[]] return (self.limits[0] is None or value >= self.limits[0]) and (self.limits[1] is None or value <= self.limits[1])
def commit( self, confirm=False, confirm_delay=None, comment="", label="", delay_factor=1 ): """ Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_delay> label (which is a label name): command_string = commit label <label> comment: command_string = commit comment <comment> supported combinations label and confirm: command_string = commit label <label> confirmed <confirm_delay> label and comment: command_string = commit label <label> comment <comment> All other combinations will result in an exception. failed commit message: % Failed to commit one or more configuration items during a pseudo-atomic operation. All changes made have been reverted. Please issue 'show configuration failed [inheritance]' from this session to view the errors message XR shows if other commits occurred: One or more commits have occurred from other configuration sessions since this session started or since the last commit was made from this session. You can use the 'show configuration commit changes' command to browse the changes. Exit of configuration mode with pending changes will cause the changes to be discarded and an exception to be generated. """ delay_factor = self.select_delay_factor(delay_factor) if confirm and not confirm_delay: raise ValueError("Invalid arguments supplied to XR commit") if confirm_delay and not confirm: raise ValueError("Invalid arguments supplied to XR commit") if comment and confirm: raise ValueError("Invalid arguments supplied to XR commit") # wrap the comment in quotes if comment: if '"' in comment: raise ValueError("Invalid comment contains double quote") comment = '"{0}"'.format(comment) label = text_type(label) error_marker = "Failed to" alt_error_marker = "One or more commits have occurred from other" # Select proper command string based on arguments provided if label: if comment: command_string = "commit label {} comment {}".format(label, comment) elif confirm: command_string = "commit label {} confirmed {}".format( label, text_type(confirm_delay) ) else: command_string = "commit label {}".format(label) elif confirm: command_string = "commit confirmed {}".format(text_type(confirm_delay)) elif comment: command_string = "commit comment {}".format(comment) else: command_string = "commit" # Enter config mode (if necessary) output = self.config_mode() output += self.send_command_expect( command_string, strip_prompt=False, strip_command=False, delay_factor=delay_factor, ) if error_marker in output: raise ValueError( "Commit failed with the following errors:\n\n{0}".format(output) ) if alt_error_marker in output: # Other commits occurred, don't proceed with commit output += self.send_command_timing( "no", strip_prompt=False, strip_command=False, delay_factor=delay_factor ) raise ValueError( "Commit failed with the following errors:\n\n{}".format(output) ) return output
def function[commit, parameter[self, confirm, confirm_delay, comment, label, delay_factor]]: constant[ Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_delay> label (which is a label name): command_string = commit label <label> comment: command_string = commit comment <comment> supported combinations label and confirm: command_string = commit label <label> confirmed <confirm_delay> label and comment: command_string = commit label <label> comment <comment> All other combinations will result in an exception. failed commit message: % Failed to commit one or more configuration items during a pseudo-atomic operation. All changes made have been reverted. Please issue 'show configuration failed [inheritance]' from this session to view the errors message XR shows if other commits occurred: One or more commits have occurred from other configuration sessions since this session started or since the last commit was made from this session. You can use the 'show configuration commit changes' command to browse the changes. Exit of configuration mode with pending changes will cause the changes to be discarded and an exception to be generated. ] variable[delay_factor] assign[=] call[name[self].select_delay_factor, parameter[name[delay_factor]]] if <ast.BoolOp object at 0x7da2044c21a0> begin[:] <ast.Raise object at 0x7da2044c07f0> if <ast.BoolOp object at 0x7da2044c1390> begin[:] <ast.Raise object at 0x7da2044c04f0> if <ast.BoolOp object at 0x7da2044c30a0> begin[:] <ast.Raise object at 0x7da1b2099180> if name[comment] begin[:] if compare[constant["] in name[comment]] begin[:] <ast.Raise object at 0x7da1b2098fd0> variable[comment] assign[=] call[constant["{0}"].format, parameter[name[comment]]] variable[label] assign[=] call[name[text_type], parameter[name[label]]] variable[error_marker] assign[=] constant[Failed to] variable[alt_error_marker] assign[=] constant[One or more commits have occurred from other] if name[label] begin[:] if name[comment] begin[:] variable[command_string] assign[=] call[constant[commit label {} comment {}].format, parameter[name[label], name[comment]]] variable[output] assign[=] call[name[self].config_mode, parameter[]] <ast.AugAssign object at 0x7da2054a5a20> if compare[name[error_marker] in name[output]] begin[:] <ast.Raise object at 0x7da2054a6620> if compare[name[alt_error_marker] in name[output]] begin[:] <ast.AugAssign object at 0x7da2054a72b0> <ast.Raise object at 0x7da2054a70d0> return[name[output]]
keyword[def] identifier[commit] ( identifier[self] , identifier[confirm] = keyword[False] , identifier[confirm_delay] = keyword[None] , identifier[comment] = literal[string] , identifier[label] = literal[string] , identifier[delay_factor] = literal[int] ): literal[string] identifier[delay_factor] = identifier[self] . identifier[select_delay_factor] ( identifier[delay_factor] ) keyword[if] identifier[confirm] keyword[and] keyword[not] identifier[confirm_delay] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[confirm_delay] keyword[and] keyword[not] identifier[confirm] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[comment] keyword[and] identifier[confirm] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[comment] : keyword[if] literal[string] keyword[in] identifier[comment] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[comment] = literal[string] . identifier[format] ( identifier[comment] ) identifier[label] = identifier[text_type] ( identifier[label] ) identifier[error_marker] = literal[string] identifier[alt_error_marker] = literal[string] keyword[if] identifier[label] : keyword[if] identifier[comment] : identifier[command_string] = literal[string] . identifier[format] ( identifier[label] , identifier[comment] ) keyword[elif] identifier[confirm] : identifier[command_string] = literal[string] . identifier[format] ( identifier[label] , identifier[text_type] ( identifier[confirm_delay] ) ) keyword[else] : identifier[command_string] = literal[string] . identifier[format] ( identifier[label] ) keyword[elif] identifier[confirm] : identifier[command_string] = literal[string] . identifier[format] ( identifier[text_type] ( identifier[confirm_delay] )) keyword[elif] identifier[comment] : identifier[command_string] = literal[string] . identifier[format] ( identifier[comment] ) keyword[else] : identifier[command_string] = literal[string] identifier[output] = identifier[self] . identifier[config_mode] () identifier[output] += identifier[self] . identifier[send_command_expect] ( identifier[command_string] , identifier[strip_prompt] = keyword[False] , identifier[strip_command] = keyword[False] , identifier[delay_factor] = identifier[delay_factor] , ) keyword[if] identifier[error_marker] keyword[in] identifier[output] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[output] ) ) keyword[if] identifier[alt_error_marker] keyword[in] identifier[output] : identifier[output] += identifier[self] . identifier[send_command_timing] ( literal[string] , identifier[strip_prompt] = keyword[False] , identifier[strip_command] = keyword[False] , identifier[delay_factor] = identifier[delay_factor] ) keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[output] ) ) keyword[return] identifier[output]
def commit(self, confirm=False, confirm_delay=None, comment='', label='', delay_factor=1): """ Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_delay> label (which is a label name): command_string = commit label <label> comment: command_string = commit comment <comment> supported combinations label and confirm: command_string = commit label <label> confirmed <confirm_delay> label and comment: command_string = commit label <label> comment <comment> All other combinations will result in an exception. failed commit message: % Failed to commit one or more configuration items during a pseudo-atomic operation. All changes made have been reverted. Please issue 'show configuration failed [inheritance]' from this session to view the errors message XR shows if other commits occurred: One or more commits have occurred from other configuration sessions since this session started or since the last commit was made from this session. You can use the 'show configuration commit changes' command to browse the changes. Exit of configuration mode with pending changes will cause the changes to be discarded and an exception to be generated. """ delay_factor = self.select_delay_factor(delay_factor) if confirm and (not confirm_delay): raise ValueError('Invalid arguments supplied to XR commit') # depends on [control=['if'], data=[]] if confirm_delay and (not confirm): raise ValueError('Invalid arguments supplied to XR commit') # depends on [control=['if'], data=[]] if comment and confirm: raise ValueError('Invalid arguments supplied to XR commit') # depends on [control=['if'], data=[]] # wrap the comment in quotes if comment: if '"' in comment: raise ValueError('Invalid comment contains double quote') # depends on [control=['if'], data=[]] comment = '"{0}"'.format(comment) # depends on [control=['if'], data=[]] label = text_type(label) error_marker = 'Failed to' alt_error_marker = 'One or more commits have occurred from other' # Select proper command string based on arguments provided if label: if comment: command_string = 'commit label {} comment {}'.format(label, comment) # depends on [control=['if'], data=[]] elif confirm: command_string = 'commit label {} confirmed {}'.format(label, text_type(confirm_delay)) # depends on [control=['if'], data=[]] else: command_string = 'commit label {}'.format(label) # depends on [control=['if'], data=[]] elif confirm: command_string = 'commit confirmed {}'.format(text_type(confirm_delay)) # depends on [control=['if'], data=[]] elif comment: command_string = 'commit comment {}'.format(comment) # depends on [control=['if'], data=[]] else: command_string = 'commit' # Enter config mode (if necessary) output = self.config_mode() output += self.send_command_expect(command_string, strip_prompt=False, strip_command=False, delay_factor=delay_factor) if error_marker in output: raise ValueError('Commit failed with the following errors:\n\n{0}'.format(output)) # depends on [control=['if'], data=['output']] if alt_error_marker in output: # Other commits occurred, don't proceed with commit output += self.send_command_timing('no', strip_prompt=False, strip_command=False, delay_factor=delay_factor) raise ValueError('Commit failed with the following errors:\n\n{}'.format(output)) # depends on [control=['if'], data=['output']] return output
def website_exists(self, website, websites=None): """ Look for websites matching the one passed """ if websites is None: websites = self.list_websites() if isinstance(website, str): website = {"name": website} ignored_fields = ('id',) # changes in these fields are ignored results = [] for other in websites: different = False for key in website: if key in ignored_fields: continue if other.get(key) != website.get(key): different = True break if different is False: results.append(other) return results
def function[website_exists, parameter[self, website, websites]]: constant[ Look for websites matching the one passed ] if compare[name[websites] is constant[None]] begin[:] variable[websites] assign[=] call[name[self].list_websites, parameter[]] if call[name[isinstance], parameter[name[website], name[str]]] begin[:] variable[website] assign[=] dictionary[[<ast.Constant object at 0x7da1b130a0b0>], [<ast.Name object at 0x7da1b1309720>]] variable[ignored_fields] assign[=] tuple[[<ast.Constant object at 0x7da1b13087f0>]] variable[results] assign[=] list[[]] for taget[name[other]] in starred[name[websites]] begin[:] variable[different] assign[=] constant[False] for taget[name[key]] in starred[name[website]] begin[:] if compare[name[key] in name[ignored_fields]] begin[:] continue if compare[call[name[other].get, parameter[name[key]]] not_equal[!=] call[name[website].get, parameter[name[key]]]] begin[:] variable[different] assign[=] constant[True] break if compare[name[different] is constant[False]] begin[:] call[name[results].append, parameter[name[other]]] return[name[results]]
keyword[def] identifier[website_exists] ( identifier[self] , identifier[website] , identifier[websites] = keyword[None] ): literal[string] keyword[if] identifier[websites] keyword[is] keyword[None] : identifier[websites] = identifier[self] . identifier[list_websites] () keyword[if] identifier[isinstance] ( identifier[website] , identifier[str] ): identifier[website] ={ literal[string] : identifier[website] } identifier[ignored_fields] =( literal[string] ,) identifier[results] =[] keyword[for] identifier[other] keyword[in] identifier[websites] : identifier[different] = keyword[False] keyword[for] identifier[key] keyword[in] identifier[website] : keyword[if] identifier[key] keyword[in] identifier[ignored_fields] : keyword[continue] keyword[if] identifier[other] . identifier[get] ( identifier[key] )!= identifier[website] . identifier[get] ( identifier[key] ): identifier[different] = keyword[True] keyword[break] keyword[if] identifier[different] keyword[is] keyword[False] : identifier[results] . identifier[append] ( identifier[other] ) keyword[return] identifier[results]
def website_exists(self, website, websites=None): """ Look for websites matching the one passed """ if websites is None: websites = self.list_websites() # depends on [control=['if'], data=['websites']] if isinstance(website, str): website = {'name': website} # depends on [control=['if'], data=[]] ignored_fields = ('id',) # changes in these fields are ignored results = [] for other in websites: different = False for key in website: if key in ignored_fields: continue # depends on [control=['if'], data=[]] if other.get(key) != website.get(key): different = True break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['key']] if different is False: results.append(other) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['other']] return results
def _init_transformer(cls, data): """Convert input into a QuantumChannel subclass object or Operator object""" # This handles common conversion for all QuantumChannel subclasses. # If the input is already a QuantumChannel subclass it will return # the original object if isinstance(data, QuantumChannel): return data if hasattr(data, 'to_quantumchannel'): # If the data object is not a QuantumChannel it will give # preference to a 'to_quantumchannel' attribute that allows # an arbitrary object to define its own conversion to any # quantum channel subclass. return data.to_channel() if hasattr(data, 'to_channel'): # TODO: this 'to_channel' method is the same case as the above # but is used by current version of Aer. It should be removed # once Aer is nupdated to use `to_quantumchannel` # instead of `to_channel`, return data.to_channel() # Finally if the input is not a QuantumChannel and doesn't have a # 'to_quantumchannel' conversion method we try and initialize it as a # regular matrix Operator which can be converted into a QuantumChannel. return Operator(data)
def function[_init_transformer, parameter[cls, data]]: constant[Convert input into a QuantumChannel subclass object or Operator object] if call[name[isinstance], parameter[name[data], name[QuantumChannel]]] begin[:] return[name[data]] if call[name[hasattr], parameter[name[data], constant[to_quantumchannel]]] begin[:] return[call[name[data].to_channel, parameter[]]] if call[name[hasattr], parameter[name[data], constant[to_channel]]] begin[:] return[call[name[data].to_channel, parameter[]]] return[call[name[Operator], parameter[name[data]]]]
keyword[def] identifier[_init_transformer] ( identifier[cls] , identifier[data] ): literal[string] keyword[if] identifier[isinstance] ( identifier[data] , identifier[QuantumChannel] ): keyword[return] identifier[data] keyword[if] identifier[hasattr] ( identifier[data] , literal[string] ): keyword[return] identifier[data] . identifier[to_channel] () keyword[if] identifier[hasattr] ( identifier[data] , literal[string] ): keyword[return] identifier[data] . identifier[to_channel] () keyword[return] identifier[Operator] ( identifier[data] )
def _init_transformer(cls, data): """Convert input into a QuantumChannel subclass object or Operator object""" # This handles common conversion for all QuantumChannel subclasses. # If the input is already a QuantumChannel subclass it will return # the original object if isinstance(data, QuantumChannel): return data # depends on [control=['if'], data=[]] if hasattr(data, 'to_quantumchannel'): # If the data object is not a QuantumChannel it will give # preference to a 'to_quantumchannel' attribute that allows # an arbitrary object to define its own conversion to any # quantum channel subclass. return data.to_channel() # depends on [control=['if'], data=[]] if hasattr(data, 'to_channel'): # TODO: this 'to_channel' method is the same case as the above # but is used by current version of Aer. It should be removed # once Aer is nupdated to use `to_quantumchannel` # instead of `to_channel`, return data.to_channel() # depends on [control=['if'], data=[]] # Finally if the input is not a QuantumChannel and doesn't have a # 'to_quantumchannel' conversion method we try and initialize it as a # regular matrix Operator which can be converted into a QuantumChannel. return Operator(data)
def get_isolated_cpus(): """Get the list of isolated CPUs. Return a sorted list of CPU identifiers, or return None if no CPU is isolated. """ # The cpu/isolated sysfs was added in Linux 4.2 # (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49) path = sysfs_path('devices/system/cpu/isolated') isolated = read_first_line(path) if isolated: return parse_cpu_list(isolated) cmdline = read_first_line(proc_path('cmdline')) if cmdline: match = re.search(r'\bisolcpus=([^ ]+)', cmdline) if match: isolated = match.group(1) return parse_cpu_list(isolated) return None
def function[get_isolated_cpus, parameter[]]: constant[Get the list of isolated CPUs. Return a sorted list of CPU identifiers, or return None if no CPU is isolated. ] variable[path] assign[=] call[name[sysfs_path], parameter[constant[devices/system/cpu/isolated]]] variable[isolated] assign[=] call[name[read_first_line], parameter[name[path]]] if name[isolated] begin[:] return[call[name[parse_cpu_list], parameter[name[isolated]]]] variable[cmdline] assign[=] call[name[read_first_line], parameter[call[name[proc_path], parameter[constant[cmdline]]]]] if name[cmdline] begin[:] variable[match] assign[=] call[name[re].search, parameter[constant[\bisolcpus=([^ ]+)], name[cmdline]]] if name[match] begin[:] variable[isolated] assign[=] call[name[match].group, parameter[constant[1]]] return[call[name[parse_cpu_list], parameter[name[isolated]]]] return[constant[None]]
keyword[def] identifier[get_isolated_cpus] (): literal[string] identifier[path] = identifier[sysfs_path] ( literal[string] ) identifier[isolated] = identifier[read_first_line] ( identifier[path] ) keyword[if] identifier[isolated] : keyword[return] identifier[parse_cpu_list] ( identifier[isolated] ) identifier[cmdline] = identifier[read_first_line] ( identifier[proc_path] ( literal[string] )) keyword[if] identifier[cmdline] : identifier[match] = identifier[re] . identifier[search] ( literal[string] , identifier[cmdline] ) keyword[if] identifier[match] : identifier[isolated] = identifier[match] . identifier[group] ( literal[int] ) keyword[return] identifier[parse_cpu_list] ( identifier[isolated] ) keyword[return] keyword[None]
def get_isolated_cpus(): """Get the list of isolated CPUs. Return a sorted list of CPU identifiers, or return None if no CPU is isolated. """ # The cpu/isolated sysfs was added in Linux 4.2 # (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49) path = sysfs_path('devices/system/cpu/isolated') isolated = read_first_line(path) if isolated: return parse_cpu_list(isolated) # depends on [control=['if'], data=[]] cmdline = read_first_line(proc_path('cmdline')) if cmdline: match = re.search('\\bisolcpus=([^ ]+)', cmdline) if match: isolated = match.group(1) return parse_cpu_list(isolated) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return None
def download(self, url, file_name, headers=None, show_progress=True): '''stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add force: If the final image exists, don't overwrite ''' fd, tmp_file = tempfile.mkstemp(prefix=("%s.tmp." % file_name)) os.close(fd) # Should we verify the request? verify = self._verify() # Check here if exists if requests.head(url, verify=verify).status_code in [200, 401]: response = self.stream(url, headers=headers, stream_to=tmp_file) if isinstance(response, HTTPError): bot.error("Error downloading %s, exiting." %url) sys.exit(1) shutil.move(tmp_file, file_name) else: bot.error("Invalid url or permissions %s" %url) return file_name
def function[download, parameter[self, url, file_name, headers, show_progress]]: constant[stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add force: If the final image exists, don't overwrite ] <ast.Tuple object at 0x7da18f8131c0> assign[=] call[name[tempfile].mkstemp, parameter[]] call[name[os].close, parameter[name[fd]]] variable[verify] assign[=] call[name[self]._verify, parameter[]] if compare[call[name[requests].head, parameter[name[url]]].status_code in list[[<ast.Constant object at 0x7da20e954d60>, <ast.Constant object at 0x7da20e9573a0>]]] begin[:] variable[response] assign[=] call[name[self].stream, parameter[name[url]]] if call[name[isinstance], parameter[name[response], name[HTTPError]]] begin[:] call[name[bot].error, parameter[binary_operation[constant[Error downloading %s, exiting.] <ast.Mod object at 0x7da2590d6920> name[url]]]] call[name[sys].exit, parameter[constant[1]]] call[name[shutil].move, parameter[name[tmp_file], name[file_name]]] return[name[file_name]]
keyword[def] identifier[download] ( identifier[self] , identifier[url] , identifier[file_name] , identifier[headers] = keyword[None] , identifier[show_progress] = keyword[True] ): literal[string] identifier[fd] , identifier[tmp_file] = identifier[tempfile] . identifier[mkstemp] ( identifier[prefix] =( literal[string] % identifier[file_name] )) identifier[os] . identifier[close] ( identifier[fd] ) identifier[verify] = identifier[self] . identifier[_verify] () keyword[if] identifier[requests] . identifier[head] ( identifier[url] , identifier[verify] = identifier[verify] ). identifier[status_code] keyword[in] [ literal[int] , literal[int] ]: identifier[response] = identifier[self] . identifier[stream] ( identifier[url] , identifier[headers] = identifier[headers] , identifier[stream_to] = identifier[tmp_file] ) keyword[if] identifier[isinstance] ( identifier[response] , identifier[HTTPError] ): identifier[bot] . identifier[error] ( literal[string] % identifier[url] ) identifier[sys] . identifier[exit] ( literal[int] ) identifier[shutil] . identifier[move] ( identifier[tmp_file] , identifier[file_name] ) keyword[else] : identifier[bot] . identifier[error] ( literal[string] % identifier[url] ) keyword[return] identifier[file_name]
def download(self, url, file_name, headers=None, show_progress=True): """stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add force: If the final image exists, don't overwrite """ (fd, tmp_file) = tempfile.mkstemp(prefix='%s.tmp.' % file_name) os.close(fd) # Should we verify the request? verify = self._verify() # Check here if exists if requests.head(url, verify=verify).status_code in [200, 401]: response = self.stream(url, headers=headers, stream_to=tmp_file) if isinstance(response, HTTPError): bot.error('Error downloading %s, exiting.' % url) sys.exit(1) # depends on [control=['if'], data=[]] shutil.move(tmp_file, file_name) # depends on [control=['if'], data=[]] else: bot.error('Invalid url or permissions %s' % url) return file_name
def parse_config(self, config_file): """ Given a configuration file, read in and interpret the results :param config_file: :return: """ with open(config_file, 'r') as f: config = json.load(f) self.params = config if self.params['proxy']['proxy_type']: self.params['proxy'] = {self.params['proxy']['proxy_type']: self.params['proxy']['proxy_url']}
def function[parse_config, parameter[self, config_file]]: constant[ Given a configuration file, read in and interpret the results :param config_file: :return: ] with call[name[open], parameter[name[config_file], constant[r]]] begin[:] variable[config] assign[=] call[name[json].load, parameter[name[f]]] name[self].params assign[=] name[config] if call[call[name[self].params][constant[proxy]]][constant[proxy_type]] begin[:] call[name[self].params][constant[proxy]] assign[=] dictionary[[<ast.Subscript object at 0x7da1b283ab00>], [<ast.Subscript object at 0x7da1b2839780>]]
keyword[def] identifier[parse_config] ( identifier[self] , identifier[config_file] ): literal[string] keyword[with] identifier[open] ( identifier[config_file] , literal[string] ) keyword[as] identifier[f] : identifier[config] = identifier[json] . identifier[load] ( identifier[f] ) identifier[self] . identifier[params] = identifier[config] keyword[if] identifier[self] . identifier[params] [ literal[string] ][ literal[string] ]: identifier[self] . identifier[params] [ literal[string] ]={ identifier[self] . identifier[params] [ literal[string] ][ literal[string] ]: identifier[self] . identifier[params] [ literal[string] ][ literal[string] ]}
def parse_config(self, config_file): """ Given a configuration file, read in and interpret the results :param config_file: :return: """ with open(config_file, 'r') as f: config = json.load(f) # depends on [control=['with'], data=['f']] self.params = config if self.params['proxy']['proxy_type']: self.params['proxy'] = {self.params['proxy']['proxy_type']: self.params['proxy']['proxy_url']} # depends on [control=['if'], data=[]]
def merge_snapshots(self): """ Create component snapshots by merging other snapshots of same component """ self.publish_snapshots = [] for component, snapshots in self.components.items(): if len(snapshots) <= 1: # Only one snapshot, no need to merge lg.debug("Component %s has only one snapshot %s, not creating merge snapshot" % (component, snapshots)) self.publish_snapshots.append({ 'Component': component, 'Name': snapshots[0] }) continue # Look if merged snapshot doesn't already exist remote_snapshot = self._find_snapshot(r'^%s%s-%s-\d+' % (self.merge_prefix, self.name.replace('./', '').replace('/', '-'), component)) if remote_snapshot: source_snapshots = self._get_source_snapshots(remote_snapshot) # Check if latest merged snapshot has same source snapshots like us snapshots_want = list(snapshots) snapshots_want.sort() lg.debug("Comparing snapshots: snapshot_name=%s, snapshot_sources=%s, wanted_sources=%s" % (remote_snapshot['Name'], source_snapshots, snapshots_want)) if snapshots_want == source_snapshots: lg.info("Remote merge snapshot already exists: %s (%s)" % (remote_snapshot['Name'], source_snapshots)) self.publish_snapshots.append({ 'Component': component, 'Name': remote_snapshot['Name'] }) continue snapshot_name = '%s%s-%s-%s' % (self.merge_prefix, self.name.replace('./', '').replace('/', '-'), component, self.timestamp) lg.info("Creating merge snapshot %s for component %s of snapshots %s" % (snapshot_name, component, snapshots)) package_refs = [] for snapshot in snapshots: # Get package refs from each snapshot packages = self._get_packages(self.client, "snapshots", snapshot) package_refs.extend(packages) try: self.client.do_post( '/snapshots', data={ 'Name': snapshot_name, 'SourceSnapshots': snapshots, 'Description': "Merged from sources: %s" % ', '.join("'%s'" % snap for snap in snapshots), 'PackageRefs': package_refs, } ) except AptlyException as e: if e.res.status_code == 400: lg.warning("Error creating snapshot %s, assuming it already exists" % snapshot_name) else: raise self.publish_snapshots.append({ 'Component': component, 'Name': snapshot_name })
def function[merge_snapshots, parameter[self]]: constant[ Create component snapshots by merging other snapshots of same component ] name[self].publish_snapshots assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da20e9611b0>, <ast.Name object at 0x7da20e963dc0>]]] in starred[call[name[self].components.items, parameter[]]] begin[:] if compare[call[name[len], parameter[name[snapshots]]] less_or_equal[<=] constant[1]] begin[:] call[name[lg].debug, parameter[binary_operation[constant[Component %s has only one snapshot %s, not creating merge snapshot] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da20e960190>, <ast.Name object at 0x7da20e961ed0>]]]]] call[name[self].publish_snapshots.append, parameter[dictionary[[<ast.Constant object at 0x7da20e962920>, <ast.Constant object at 0x7da20e962cb0>], [<ast.Name object at 0x7da20e962020>, <ast.Subscript object at 0x7da20e963760>]]]] continue variable[remote_snapshot] assign[=] call[name[self]._find_snapshot, parameter[binary_operation[constant[^%s%s-%s-\d+] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da2044c2b30>, <ast.Call object at 0x7da2044c1c60>, <ast.Name object at 0x7da204345240>]]]]] if name[remote_snapshot] begin[:] variable[source_snapshots] assign[=] call[name[self]._get_source_snapshots, parameter[name[remote_snapshot]]] variable[snapshots_want] assign[=] call[name[list], parameter[name[snapshots]]] call[name[snapshots_want].sort, parameter[]] call[name[lg].debug, parameter[binary_operation[constant[Comparing snapshots: snapshot_name=%s, snapshot_sources=%s, wanted_sources=%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da204347eb0>, <ast.Name object at 0x7da204344c70>, <ast.Name object at 0x7da2043467a0>]]]]] if compare[name[snapshots_want] equal[==] name[source_snapshots]] begin[:] call[name[lg].info, parameter[binary_operation[constant[Remote merge snapshot already exists: %s (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da204344e80>, <ast.Name object at 0x7da204345900>]]]]] call[name[self].publish_snapshots.append, parameter[dictionary[[<ast.Constant object at 0x7da2043450c0>, <ast.Constant object at 0x7da204347730>], [<ast.Name object at 0x7da204347be0>, <ast.Subscript object at 0x7da2043475e0>]]]] continue variable[snapshot_name] assign[=] binary_operation[constant[%s%s-%s-%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da204347040>, <ast.Call object at 0x7da204347dc0>, <ast.Name object at 0x7da2043458a0>, <ast.Attribute object at 0x7da204344d60>]]] call[name[lg].info, parameter[binary_operation[constant[Creating merge snapshot %s for component %s of snapshots %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da2043459f0>, <ast.Name object at 0x7da204347160>, <ast.Name object at 0x7da204347670>]]]]] variable[package_refs] assign[=] list[[]] for taget[name[snapshot]] in starred[name[snapshots]] begin[:] variable[packages] assign[=] call[name[self]._get_packages, parameter[name[self].client, constant[snapshots], name[snapshot]]] call[name[package_refs].extend, parameter[name[packages]]] <ast.Try object at 0x7da204346d10> call[name[self].publish_snapshots.append, parameter[dictionary[[<ast.Constant object at 0x7da20e960ee0>, <ast.Constant object at 0x7da20e9600a0>], [<ast.Name object at 0x7da20e961510>, <ast.Name object at 0x7da20e961390>]]]]
keyword[def] identifier[merge_snapshots] ( identifier[self] ): literal[string] identifier[self] . identifier[publish_snapshots] =[] keyword[for] identifier[component] , identifier[snapshots] keyword[in] identifier[self] . identifier[components] . identifier[items] (): keyword[if] identifier[len] ( identifier[snapshots] )<= literal[int] : identifier[lg] . identifier[debug] ( literal[string] %( identifier[component] , identifier[snapshots] )) identifier[self] . identifier[publish_snapshots] . identifier[append] ({ literal[string] : identifier[component] , literal[string] : identifier[snapshots] [ literal[int] ] }) keyword[continue] identifier[remote_snapshot] = identifier[self] . identifier[_find_snapshot] ( literal[string] %( identifier[self] . identifier[merge_prefix] , identifier[self] . identifier[name] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ), identifier[component] )) keyword[if] identifier[remote_snapshot] : identifier[source_snapshots] = identifier[self] . identifier[_get_source_snapshots] ( identifier[remote_snapshot] ) identifier[snapshots_want] = identifier[list] ( identifier[snapshots] ) identifier[snapshots_want] . identifier[sort] () identifier[lg] . identifier[debug] ( literal[string] %( identifier[remote_snapshot] [ literal[string] ], identifier[source_snapshots] , identifier[snapshots_want] )) keyword[if] identifier[snapshots_want] == identifier[source_snapshots] : identifier[lg] . identifier[info] ( literal[string] %( identifier[remote_snapshot] [ literal[string] ], identifier[source_snapshots] )) identifier[self] . identifier[publish_snapshots] . identifier[append] ({ literal[string] : identifier[component] , literal[string] : identifier[remote_snapshot] [ literal[string] ] }) keyword[continue] identifier[snapshot_name] = literal[string] %( identifier[self] . identifier[merge_prefix] , identifier[self] . identifier[name] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ), identifier[component] , identifier[self] . identifier[timestamp] ) identifier[lg] . identifier[info] ( literal[string] %( identifier[snapshot_name] , identifier[component] , identifier[snapshots] )) identifier[package_refs] =[] keyword[for] identifier[snapshot] keyword[in] identifier[snapshots] : identifier[packages] = identifier[self] . identifier[_get_packages] ( identifier[self] . identifier[client] , literal[string] , identifier[snapshot] ) identifier[package_refs] . identifier[extend] ( identifier[packages] ) keyword[try] : identifier[self] . identifier[client] . identifier[do_post] ( literal[string] , identifier[data] ={ literal[string] : identifier[snapshot_name] , literal[string] : identifier[snapshots] , literal[string] : literal[string] % literal[string] . identifier[join] ( literal[string] % identifier[snap] keyword[for] identifier[snap] keyword[in] identifier[snapshots] ), literal[string] : identifier[package_refs] , } ) keyword[except] identifier[AptlyException] keyword[as] identifier[e] : keyword[if] identifier[e] . identifier[res] . identifier[status_code] == literal[int] : identifier[lg] . identifier[warning] ( literal[string] % identifier[snapshot_name] ) keyword[else] : keyword[raise] identifier[self] . identifier[publish_snapshots] . identifier[append] ({ literal[string] : identifier[component] , literal[string] : identifier[snapshot_name] })
def merge_snapshots(self): """ Create component snapshots by merging other snapshots of same component """ self.publish_snapshots = [] for (component, snapshots) in self.components.items(): if len(snapshots) <= 1: # Only one snapshot, no need to merge lg.debug('Component %s has only one snapshot %s, not creating merge snapshot' % (component, snapshots)) self.publish_snapshots.append({'Component': component, 'Name': snapshots[0]}) continue # depends on [control=['if'], data=[]] # Look if merged snapshot doesn't already exist remote_snapshot = self._find_snapshot('^%s%s-%s-\\d+' % (self.merge_prefix, self.name.replace('./', '').replace('/', '-'), component)) if remote_snapshot: source_snapshots = self._get_source_snapshots(remote_snapshot) # Check if latest merged snapshot has same source snapshots like us snapshots_want = list(snapshots) snapshots_want.sort() lg.debug('Comparing snapshots: snapshot_name=%s, snapshot_sources=%s, wanted_sources=%s' % (remote_snapshot['Name'], source_snapshots, snapshots_want)) if snapshots_want == source_snapshots: lg.info('Remote merge snapshot already exists: %s (%s)' % (remote_snapshot['Name'], source_snapshots)) self.publish_snapshots.append({'Component': component, 'Name': remote_snapshot['Name']}) continue # depends on [control=['if'], data=['source_snapshots']] # depends on [control=['if'], data=[]] snapshot_name = '%s%s-%s-%s' % (self.merge_prefix, self.name.replace('./', '').replace('/', '-'), component, self.timestamp) lg.info('Creating merge snapshot %s for component %s of snapshots %s' % (snapshot_name, component, snapshots)) package_refs = [] for snapshot in snapshots: # Get package refs from each snapshot packages = self._get_packages(self.client, 'snapshots', snapshot) package_refs.extend(packages) # depends on [control=['for'], data=['snapshot']] try: self.client.do_post('/snapshots', data={'Name': snapshot_name, 'SourceSnapshots': snapshots, 'Description': 'Merged from sources: %s' % ', '.join(("'%s'" % snap for snap in snapshots)), 'PackageRefs': package_refs}) # depends on [control=['try'], data=[]] except AptlyException as e: if e.res.status_code == 400: lg.warning('Error creating snapshot %s, assuming it already exists' % snapshot_name) # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=['e']] self.publish_snapshots.append({'Component': component, 'Name': snapshot_name}) # depends on [control=['for'], data=[]]
def transcripts(context, build): """Export all transcripts to .bed like format""" LOG.info("Running scout export transcripts") adapter = context.obj['adapter'] header = ["#Chrom\tStart\tEnd\tTranscript\tRefSeq\tHgncID"] for line in header: click.echo(line) transcript_string = ("{0}\t{1}\t{2}\t{3}\t{4}\t{5}") for tx_obj in export_transcripts(adapter): click.echo(transcript_string.format( tx_obj['chrom'], tx_obj['start'], tx_obj['end'], tx_obj['ensembl_transcript_id'], tx_obj.get('refseq_id',''), tx_obj['hgnc_id'], ) )
def function[transcripts, parameter[context, build]]: constant[Export all transcripts to .bed like format] call[name[LOG].info, parameter[constant[Running scout export transcripts]]] variable[adapter] assign[=] call[name[context].obj][constant[adapter]] variable[header] assign[=] list[[<ast.Constant object at 0x7da18f00ea40>]] for taget[name[line]] in starred[name[header]] begin[:] call[name[click].echo, parameter[name[line]]] variable[transcript_string] assign[=] constant[{0} {1} {2} {3} {4} {5}] for taget[name[tx_obj]] in starred[call[name[export_transcripts], parameter[name[adapter]]]] begin[:] call[name[click].echo, parameter[call[name[transcript_string].format, parameter[call[name[tx_obj]][constant[chrom]], call[name[tx_obj]][constant[start]], call[name[tx_obj]][constant[end]], call[name[tx_obj]][constant[ensembl_transcript_id]], call[name[tx_obj].get, parameter[constant[refseq_id], constant[]]], call[name[tx_obj]][constant[hgnc_id]]]]]]
keyword[def] identifier[transcripts] ( identifier[context] , identifier[build] ): literal[string] identifier[LOG] . identifier[info] ( literal[string] ) identifier[adapter] = identifier[context] . identifier[obj] [ literal[string] ] identifier[header] =[ literal[string] ] keyword[for] identifier[line] keyword[in] identifier[header] : identifier[click] . identifier[echo] ( identifier[line] ) identifier[transcript_string] =( literal[string] ) keyword[for] identifier[tx_obj] keyword[in] identifier[export_transcripts] ( identifier[adapter] ): identifier[click] . identifier[echo] ( identifier[transcript_string] . identifier[format] ( identifier[tx_obj] [ literal[string] ], identifier[tx_obj] [ literal[string] ], identifier[tx_obj] [ literal[string] ], identifier[tx_obj] [ literal[string] ], identifier[tx_obj] . identifier[get] ( literal[string] , literal[string] ), identifier[tx_obj] [ literal[string] ], ) )
def transcripts(context, build): """Export all transcripts to .bed like format""" LOG.info('Running scout export transcripts') adapter = context.obj['adapter'] header = ['#Chrom\tStart\tEnd\tTranscript\tRefSeq\tHgncID'] for line in header: click.echo(line) # depends on [control=['for'], data=['line']] transcript_string = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}' for tx_obj in export_transcripts(adapter): click.echo(transcript_string.format(tx_obj['chrom'], tx_obj['start'], tx_obj['end'], tx_obj['ensembl_transcript_id'], tx_obj.get('refseq_id', ''), tx_obj['hgnc_id'])) # depends on [control=['for'], data=['tx_obj']]
def list_instance_templates(self): """ List the available instance templates. """ response = self.get_proto(path='/instance-templates') message = rest_pb2.ListInstanceTemplatesResponse() message.ParseFromString(response.content) templates = getattr(message, 'template') return iter([InstanceTemplate(template) for template in templates])
def function[list_instance_templates, parameter[self]]: constant[ List the available instance templates. ] variable[response] assign[=] call[name[self].get_proto, parameter[]] variable[message] assign[=] call[name[rest_pb2].ListInstanceTemplatesResponse, parameter[]] call[name[message].ParseFromString, parameter[name[response].content]] variable[templates] assign[=] call[name[getattr], parameter[name[message], constant[template]]] return[call[name[iter], parameter[<ast.ListComp object at 0x7da18fe90370>]]]
keyword[def] identifier[list_instance_templates] ( identifier[self] ): literal[string] identifier[response] = identifier[self] . identifier[get_proto] ( identifier[path] = literal[string] ) identifier[message] = identifier[rest_pb2] . identifier[ListInstanceTemplatesResponse] () identifier[message] . identifier[ParseFromString] ( identifier[response] . identifier[content] ) identifier[templates] = identifier[getattr] ( identifier[message] , literal[string] ) keyword[return] identifier[iter] ([ identifier[InstanceTemplate] ( identifier[template] ) keyword[for] identifier[template] keyword[in] identifier[templates] ])
def list_instance_templates(self): """ List the available instance templates. """ response = self.get_proto(path='/instance-templates') message = rest_pb2.ListInstanceTemplatesResponse() message.ParseFromString(response.content) templates = getattr(message, 'template') return iter([InstanceTemplate(template) for template in templates])
def get_user_info(self, user_id, lang="zh_CN"): """ 获取用户基本信息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 """ return self.get( url="https://api.weixin.qq.com/cgi-bin/user/info", params={ "access_token": self.token, "openid": user_id, "lang": lang } )
def function[get_user_info, parameter[self, user_id, lang]]: constant[ 获取用户基本信息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 ] return[call[name[self].get, parameter[]]]
keyword[def] identifier[get_user_info] ( identifier[self] , identifier[user_id] , identifier[lang] = literal[string] ): literal[string] keyword[return] identifier[self] . identifier[get] ( identifier[url] = literal[string] , identifier[params] ={ literal[string] : identifier[self] . identifier[token] , literal[string] : identifier[user_id] , literal[string] : identifier[lang] } )
def get_user_info(self, user_id, lang='zh_CN'): """ 获取用户基本信息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 """ return self.get(url='https://api.weixin.qq.com/cgi-bin/user/info', params={'access_token': self.token, 'openid': user_id, 'lang': lang})
def parse_date(self, value): """A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if value is None: raise Exception("Unable to parse date from %r" % value) elif isinstance(value, string_types): return self.str2date(value) elif isinstance(value, int): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() elif isinstance(value, date): return value else: raise Exception("Unable to parse date from %r" % value)
def function[parse_date, parameter[self, value]]: constant[A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it ] if compare[name[value] is constant[None]] begin[:] <ast.Raise object at 0x7da2054a7640>
keyword[def] identifier[parse_date] ( identifier[self] , identifier[value] ): literal[string] keyword[if] identifier[value] keyword[is] keyword[None] : keyword[raise] identifier[Exception] ( literal[string] % identifier[value] ) keyword[elif] identifier[isinstance] ( identifier[value] , identifier[string_types] ): keyword[return] identifier[self] . identifier[str2date] ( identifier[value] ) keyword[elif] identifier[isinstance] ( identifier[value] , identifier[int] ): keyword[return] identifier[date] . identifier[fromordinal] ( identifier[value] ) keyword[elif] identifier[isinstance] ( identifier[value] , identifier[datetime] ): keyword[return] identifier[value] . identifier[date] () keyword[elif] identifier[isinstance] ( identifier[value] , identifier[date] ): keyword[return] identifier[value] keyword[else] : keyword[raise] identifier[Exception] ( literal[string] % identifier[value] )
def parse_date(self, value): """A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if value is None: raise Exception('Unable to parse date from %r' % value) # depends on [control=['if'], data=['value']] elif isinstance(value, string_types): return self.str2date(value) # depends on [control=['if'], data=[]] elif isinstance(value, int): return date.fromordinal(value) # depends on [control=['if'], data=[]] elif isinstance(value, datetime): return value.date() # depends on [control=['if'], data=[]] elif isinstance(value, date): return value # depends on [control=['if'], data=[]] else: raise Exception('Unable to parse date from %r' % value)
def predict_is(self, h=5, fit_once=True): """ Makes dynamic in-sample predictions with the estimated model Parameters ---------- h : int (default : 5) How many steps would you like to forecast? fit_once : boolean (default: True) Fits only once before the in-sample prediction; if False, fits after every new datapoint This method is not functional currently for this model Returns ---------- - pd.DataFrame with predicted values """ predictions = [] for t in range(0,h): x = NLLEV(family=self.family, integ=self.integ, data=self.data_original[:(-h+t)]) x.fit(print_progress=False) if t == 0: predictions = x.predict(h=1) else: predictions = pd.concat([predictions,x.predict(h=1)]) predictions.rename(columns={0:self.data_name}, inplace=True) predictions.index = self.index[-h:] return predictions
def function[predict_is, parameter[self, h, fit_once]]: constant[ Makes dynamic in-sample predictions with the estimated model Parameters ---------- h : int (default : 5) How many steps would you like to forecast? fit_once : boolean (default: True) Fits only once before the in-sample prediction; if False, fits after every new datapoint This method is not functional currently for this model Returns ---------- - pd.DataFrame with predicted values ] variable[predictions] assign[=] list[[]] for taget[name[t]] in starred[call[name[range], parameter[constant[0], name[h]]]] begin[:] variable[x] assign[=] call[name[NLLEV], parameter[]] call[name[x].fit, parameter[]] if compare[name[t] equal[==] constant[0]] begin[:] variable[predictions] assign[=] call[name[x].predict, parameter[]] call[name[predictions].rename, parameter[]] name[predictions].index assign[=] call[name[self].index][<ast.Slice object at 0x7da18f00e8f0>] return[name[predictions]]
keyword[def] identifier[predict_is] ( identifier[self] , identifier[h] = literal[int] , identifier[fit_once] = keyword[True] ): literal[string] identifier[predictions] =[] keyword[for] identifier[t] keyword[in] identifier[range] ( literal[int] , identifier[h] ): identifier[x] = identifier[NLLEV] ( identifier[family] = identifier[self] . identifier[family] , identifier[integ] = identifier[self] . identifier[integ] , identifier[data] = identifier[self] . identifier[data_original] [:(- identifier[h] + identifier[t] )]) identifier[x] . identifier[fit] ( identifier[print_progress] = keyword[False] ) keyword[if] identifier[t] == literal[int] : identifier[predictions] = identifier[x] . identifier[predict] ( identifier[h] = literal[int] ) keyword[else] : identifier[predictions] = identifier[pd] . identifier[concat] ([ identifier[predictions] , identifier[x] . identifier[predict] ( identifier[h] = literal[int] )]) identifier[predictions] . identifier[rename] ( identifier[columns] ={ literal[int] : identifier[self] . identifier[data_name] }, identifier[inplace] = keyword[True] ) identifier[predictions] . identifier[index] = identifier[self] . identifier[index] [- identifier[h] :] keyword[return] identifier[predictions]
def predict_is(self, h=5, fit_once=True): """ Makes dynamic in-sample predictions with the estimated model Parameters ---------- h : int (default : 5) How many steps would you like to forecast? fit_once : boolean (default: True) Fits only once before the in-sample prediction; if False, fits after every new datapoint This method is not functional currently for this model Returns ---------- - pd.DataFrame with predicted values """ predictions = [] for t in range(0, h): x = NLLEV(family=self.family, integ=self.integ, data=self.data_original[:-h + t]) x.fit(print_progress=False) if t == 0: predictions = x.predict(h=1) # depends on [control=['if'], data=[]] else: predictions = pd.concat([predictions, x.predict(h=1)]) # depends on [control=['for'], data=['t']] predictions.rename(columns={0: self.data_name}, inplace=True) predictions.index = self.index[-h:] return predictions
def remove_spot(self, feature=None, **kwargs): """ [NOT IMPLEMENTED] Shortcut to :meth:`remove_feature` but with kind='spot' """ kwargs.setdefault('kind', 'spot') return self.remove_feature(feature, **kwargs)
def function[remove_spot, parameter[self, feature]]: constant[ [NOT IMPLEMENTED] Shortcut to :meth:`remove_feature` but with kind='spot' ] call[name[kwargs].setdefault, parameter[constant[kind], constant[spot]]] return[call[name[self].remove_feature, parameter[name[feature]]]]
keyword[def] identifier[remove_spot] ( identifier[self] , identifier[feature] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[kwargs] . identifier[setdefault] ( literal[string] , literal[string] ) keyword[return] identifier[self] . identifier[remove_feature] ( identifier[feature] ,** identifier[kwargs] )
def remove_spot(self, feature=None, **kwargs): """ [NOT IMPLEMENTED] Shortcut to :meth:`remove_feature` but with kind='spot' """ kwargs.setdefault('kind', 'spot') return self.remove_feature(feature, **kwargs)
def proto_fill_from_dict(message, data, clear=True): """Fills protobuf message parameters inplace from a :class:`dict` :param message: protobuf message instance :param data: parameters and values :type data: dict :param clear: whether clear exisiting values :type clear: bool :return: value of message paramater :raises: incorrect types or values will raise """ if not isinstance(message, _ProtoMessageType): raise TypeError("Expected `message` to be a instance of protobuf message") if not isinstance(data, dict): raise TypeError("Expected `data` to be of type `dict`") if clear: message.Clear() field_descs = message.DESCRIPTOR.fields_by_name for key, val in data.items(): desc = field_descs[key] if desc.type == desc.TYPE_MESSAGE: if desc.label == desc.LABEL_REPEATED: if not isinstance(val, _list_types): raise TypeError("Expected %s to be of type list, got %s" % (repr(key), type(val))) list_ref = getattr(message, key) # Takes care of overwriting list fields when merging partial data (clear=False) if not clear: del list_ref[:] # clears the list for item in val: item_message = getattr(message, key).add() proto_fill_from_dict(item_message, item) else: if not isinstance(val, dict): raise TypeError("Expected %s to be of type dict, got %s" % (repr(key), type(dict))) proto_fill_from_dict(getattr(message, key), val) else: if isinstance(val, _list_types): list_ref = getattr(message, key) if not clear: del list_ref[:] # clears the list list_ref.extend(val) else: setattr(message, key, val) return message
def function[proto_fill_from_dict, parameter[message, data, clear]]: constant[Fills protobuf message parameters inplace from a :class:`dict` :param message: protobuf message instance :param data: parameters and values :type data: dict :param clear: whether clear exisiting values :type clear: bool :return: value of message paramater :raises: incorrect types or values will raise ] if <ast.UnaryOp object at 0x7da1b2313520> begin[:] <ast.Raise object at 0x7da1b2313640> if <ast.UnaryOp object at 0x7da1b23122f0> begin[:] <ast.Raise object at 0x7da1b2311d80> if name[clear] begin[:] call[name[message].Clear, parameter[]] variable[field_descs] assign[=] name[message].DESCRIPTOR.fields_by_name for taget[tuple[[<ast.Name object at 0x7da1b2313850>, <ast.Name object at 0x7da1b2310310>]]] in starred[call[name[data].items, parameter[]]] begin[:] variable[desc] assign[=] call[name[field_descs]][name[key]] if compare[name[desc].type equal[==] name[desc].TYPE_MESSAGE] begin[:] if compare[name[desc].label equal[==] name[desc].LABEL_REPEATED] begin[:] if <ast.UnaryOp object at 0x7da1b23127d0> begin[:] <ast.Raise object at 0x7da1b2312740> variable[list_ref] assign[=] call[name[getattr], parameter[name[message], name[key]]] if <ast.UnaryOp object at 0x7da1b23121d0> begin[:] <ast.Delete object at 0x7da1b2313970> for taget[name[item]] in starred[name[val]] begin[:] variable[item_message] assign[=] call[call[name[getattr], parameter[name[message], name[key]]].add, parameter[]] call[name[proto_fill_from_dict], parameter[name[item_message], name[item]]] return[name[message]]
keyword[def] identifier[proto_fill_from_dict] ( identifier[message] , identifier[data] , identifier[clear] = keyword[True] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[message] , identifier[_ProtoMessageType] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[dict] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[clear] : identifier[message] . identifier[Clear] () identifier[field_descs] = identifier[message] . identifier[DESCRIPTOR] . identifier[fields_by_name] keyword[for] identifier[key] , identifier[val] keyword[in] identifier[data] . identifier[items] (): identifier[desc] = identifier[field_descs] [ identifier[key] ] keyword[if] identifier[desc] . identifier[type] == identifier[desc] . identifier[TYPE_MESSAGE] : keyword[if] identifier[desc] . identifier[label] == identifier[desc] . identifier[LABEL_REPEATED] : keyword[if] keyword[not] identifier[isinstance] ( identifier[val] , identifier[_list_types] ): keyword[raise] identifier[TypeError] ( literal[string] %( identifier[repr] ( identifier[key] ), identifier[type] ( identifier[val] ))) identifier[list_ref] = identifier[getattr] ( identifier[message] , identifier[key] ) keyword[if] keyword[not] identifier[clear] : keyword[del] identifier[list_ref] [:] keyword[for] identifier[item] keyword[in] identifier[val] : identifier[item_message] = identifier[getattr] ( identifier[message] , identifier[key] ). identifier[add] () identifier[proto_fill_from_dict] ( identifier[item_message] , identifier[item] ) keyword[else] : keyword[if] keyword[not] identifier[isinstance] ( identifier[val] , identifier[dict] ): keyword[raise] identifier[TypeError] ( literal[string] %( identifier[repr] ( identifier[key] ), identifier[type] ( identifier[dict] ))) identifier[proto_fill_from_dict] ( identifier[getattr] ( identifier[message] , identifier[key] ), identifier[val] ) keyword[else] : keyword[if] identifier[isinstance] ( identifier[val] , identifier[_list_types] ): identifier[list_ref] = identifier[getattr] ( identifier[message] , identifier[key] ) keyword[if] keyword[not] identifier[clear] : keyword[del] identifier[list_ref] [:] identifier[list_ref] . identifier[extend] ( identifier[val] ) keyword[else] : identifier[setattr] ( identifier[message] , identifier[key] , identifier[val] ) keyword[return] identifier[message]
def proto_fill_from_dict(message, data, clear=True): """Fills protobuf message parameters inplace from a :class:`dict` :param message: protobuf message instance :param data: parameters and values :type data: dict :param clear: whether clear exisiting values :type clear: bool :return: value of message paramater :raises: incorrect types or values will raise """ if not isinstance(message, _ProtoMessageType): raise TypeError('Expected `message` to be a instance of protobuf message') # depends on [control=['if'], data=[]] if not isinstance(data, dict): raise TypeError('Expected `data` to be of type `dict`') # depends on [control=['if'], data=[]] if clear: message.Clear() # depends on [control=['if'], data=[]] field_descs = message.DESCRIPTOR.fields_by_name for (key, val) in data.items(): desc = field_descs[key] if desc.type == desc.TYPE_MESSAGE: if desc.label == desc.LABEL_REPEATED: if not isinstance(val, _list_types): raise TypeError('Expected %s to be of type list, got %s' % (repr(key), type(val))) # depends on [control=['if'], data=[]] list_ref = getattr(message, key) # Takes care of overwriting list fields when merging partial data (clear=False) if not clear: del list_ref[:] # clears the list # depends on [control=['if'], data=[]] for item in val: item_message = getattr(message, key).add() proto_fill_from_dict(item_message, item) # depends on [control=['for'], data=['item']] # depends on [control=['if'], data=[]] else: if not isinstance(val, dict): raise TypeError('Expected %s to be of type dict, got %s' % (repr(key), type(dict))) # depends on [control=['if'], data=[]] proto_fill_from_dict(getattr(message, key), val) # depends on [control=['if'], data=[]] elif isinstance(val, _list_types): list_ref = getattr(message, key) if not clear: del list_ref[:] # clears the list # depends on [control=['if'], data=[]] list_ref.extend(val) # depends on [control=['if'], data=[]] else: setattr(message, key, val) # depends on [control=['for'], data=[]] return message
def compute_probability_settle(trajectory_files, bbox=None, nx=1000, ny=1000, method='overall'): """ This function creates a probability (stochastic) grid for trajectory model data based on settlement location, normalized by run. probability_grid = compute_probability_settle([myfile1.nc, myfile2.nc], bbox = [-75, 23, -60, 45], nx = 1000, ny = 1000, method='overall') """ prob = compute_probability(trajectory_files, bbox, nx, ny, method, parameter='settlement', ) return prob
def function[compute_probability_settle, parameter[trajectory_files, bbox, nx, ny, method]]: constant[ This function creates a probability (stochastic) grid for trajectory model data based on settlement location, normalized by run. probability_grid = compute_probability_settle([myfile1.nc, myfile2.nc], bbox = [-75, 23, -60, 45], nx = 1000, ny = 1000, method='overall') ] variable[prob] assign[=] call[name[compute_probability], parameter[name[trajectory_files], name[bbox], name[nx], name[ny], name[method]]] return[name[prob]]
keyword[def] identifier[compute_probability_settle] ( identifier[trajectory_files] , identifier[bbox] = keyword[None] , identifier[nx] = literal[int] , identifier[ny] = literal[int] , identifier[method] = literal[string] ): literal[string] identifier[prob] = identifier[compute_probability] ( identifier[trajectory_files] , identifier[bbox] , identifier[nx] , identifier[ny] , identifier[method] , identifier[parameter] = literal[string] , ) keyword[return] identifier[prob]
def compute_probability_settle(trajectory_files, bbox=None, nx=1000, ny=1000, method='overall'): """ This function creates a probability (stochastic) grid for trajectory model data based on settlement location, normalized by run. probability_grid = compute_probability_settle([myfile1.nc, myfile2.nc], bbox = [-75, 23, -60, 45], nx = 1000, ny = 1000, method='overall') """ prob = compute_probability(trajectory_files, bbox, nx, ny, method, parameter='settlement') return prob
def covariance_mtx_to_superop(self, mtx): """ Converts a covariance matrix to the corresponding superoperator, represented as a QuTiP Qobj with ``type="super"``. """ M = self.flat() return qt.Qobj( np.dot(np.dot(M.conj().T, mtx), M), dims=[[self.dims] * 2] * 2 )
def function[covariance_mtx_to_superop, parameter[self, mtx]]: constant[ Converts a covariance matrix to the corresponding superoperator, represented as a QuTiP Qobj with ``type="super"``. ] variable[M] assign[=] call[name[self].flat, parameter[]] return[call[name[qt].Qobj, parameter[call[name[np].dot, parameter[call[name[np].dot, parameter[call[name[M].conj, parameter[]].T, name[mtx]]], name[M]]]]]]
keyword[def] identifier[covariance_mtx_to_superop] ( identifier[self] , identifier[mtx] ): literal[string] identifier[M] = identifier[self] . identifier[flat] () keyword[return] identifier[qt] . identifier[Qobj] ( identifier[np] . identifier[dot] ( identifier[np] . identifier[dot] ( identifier[M] . identifier[conj] (). identifier[T] , identifier[mtx] ), identifier[M] ), identifier[dims] =[[ identifier[self] . identifier[dims] ]* literal[int] ]* literal[int] )
def covariance_mtx_to_superop(self, mtx): """ Converts a covariance matrix to the corresponding superoperator, represented as a QuTiP Qobj with ``type="super"``. """ M = self.flat() return qt.Qobj(np.dot(np.dot(M.conj().T, mtx), M), dims=[[self.dims] * 2] * 2)
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None): """Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with check_key. Example: "CNAME" Returns: json: Found Record. Returns None if no record found """ client = boto3.Session(profile_name=env).client('route53') pager = client.get_paginator('list_resource_record_sets') existingrecord = None for rset in pager.paginate(HostedZoneId=zone_id): for record in rset['ResourceRecordSets']: if check_key: if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value: LOG.info("Found existing record: %s", record) existingrecord = record break return existingrecord
def function[find_existing_record, parameter[env, zone_id, dns_name, check_key, check_value]]: constant[Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with check_key. Example: "CNAME" Returns: json: Found Record. Returns None if no record found ] variable[client] assign[=] call[call[name[boto3].Session, parameter[]].client, parameter[constant[route53]]] variable[pager] assign[=] call[name[client].get_paginator, parameter[constant[list_resource_record_sets]]] variable[existingrecord] assign[=] constant[None] for taget[name[rset]] in starred[call[name[pager].paginate, parameter[]]] begin[:] for taget[name[record]] in starred[call[name[rset]][constant[ResourceRecordSets]]] begin[:] if name[check_key] begin[:] if <ast.BoolOp object at 0x7da18f58f2b0> begin[:] call[name[LOG].info, parameter[constant[Found existing record: %s], name[record]]] variable[existingrecord] assign[=] name[record] break return[name[existingrecord]]
keyword[def] identifier[find_existing_record] ( identifier[env] , identifier[zone_id] , identifier[dns_name] , identifier[check_key] = keyword[None] , identifier[check_value] = keyword[None] ): literal[string] identifier[client] = identifier[boto3] . identifier[Session] ( identifier[profile_name] = identifier[env] ). identifier[client] ( literal[string] ) identifier[pager] = identifier[client] . identifier[get_paginator] ( literal[string] ) identifier[existingrecord] = keyword[None] keyword[for] identifier[rset] keyword[in] identifier[pager] . identifier[paginate] ( identifier[HostedZoneId] = identifier[zone_id] ): keyword[for] identifier[record] keyword[in] identifier[rset] [ literal[string] ]: keyword[if] identifier[check_key] : keyword[if] identifier[record] [ literal[string] ]. identifier[rstrip] ( literal[string] )== identifier[dns_name] keyword[and] identifier[record] . identifier[get] ( identifier[check_key] )== identifier[check_value] : identifier[LOG] . identifier[info] ( literal[string] , identifier[record] ) identifier[existingrecord] = identifier[record] keyword[break] keyword[return] identifier[existingrecord]
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None): """Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with check_key. Example: "CNAME" Returns: json: Found Record. Returns None if no record found """ client = boto3.Session(profile_name=env).client('route53') pager = client.get_paginator('list_resource_record_sets') existingrecord = None for rset in pager.paginate(HostedZoneId=zone_id): for record in rset['ResourceRecordSets']: if check_key: if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value: LOG.info('Found existing record: %s', record) existingrecord = record break # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['record']] # depends on [control=['for'], data=['rset']] return existingrecord
def parse(self, title, pageid=None): """ Returns Mediawiki action=parse query string """ qry = self.PARSE.substitute( WIKI=self.uri, ENDPOINT=self.endpoint, PAGE=safequote(title) or pageid) if pageid and not title: qry = qry.replace('&page=', '&pageid=').replace('&redirects', '') if self.variant: qry += '&variant=' + self.variant self.set_status('parse', pageid or title) return qry
def function[parse, parameter[self, title, pageid]]: constant[ Returns Mediawiki action=parse query string ] variable[qry] assign[=] call[name[self].PARSE.substitute, parameter[]] if <ast.BoolOp object at 0x7da1b12aae30> begin[:] variable[qry] assign[=] call[call[name[qry].replace, parameter[constant[&page=], constant[&pageid=]]].replace, parameter[constant[&redirects], constant[]]] if name[self].variant begin[:] <ast.AugAssign object at 0x7da1b12aa6b0> call[name[self].set_status, parameter[constant[parse], <ast.BoolOp object at 0x7da1b12a8d90>]] return[name[qry]]
keyword[def] identifier[parse] ( identifier[self] , identifier[title] , identifier[pageid] = keyword[None] ): literal[string] identifier[qry] = identifier[self] . identifier[PARSE] . identifier[substitute] ( identifier[WIKI] = identifier[self] . identifier[uri] , identifier[ENDPOINT] = identifier[self] . identifier[endpoint] , identifier[PAGE] = identifier[safequote] ( identifier[title] ) keyword[or] identifier[pageid] ) keyword[if] identifier[pageid] keyword[and] keyword[not] identifier[title] : identifier[qry] = identifier[qry] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ) keyword[if] identifier[self] . identifier[variant] : identifier[qry] += literal[string] + identifier[self] . identifier[variant] identifier[self] . identifier[set_status] ( literal[string] , identifier[pageid] keyword[or] identifier[title] ) keyword[return] identifier[qry]
def parse(self, title, pageid=None): """ Returns Mediawiki action=parse query string """ qry = self.PARSE.substitute(WIKI=self.uri, ENDPOINT=self.endpoint, PAGE=safequote(title) or pageid) if pageid and (not title): qry = qry.replace('&page=', '&pageid=').replace('&redirects', '') # depends on [control=['if'], data=[]] if self.variant: qry += '&variant=' + self.variant # depends on [control=['if'], data=[]] self.set_status('parse', pageid or title) return qry
def clone(self, into=None): """Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbage collected on interpreter exit. """ into = into or safe_mkdtemp() new_chroot = Chroot(into) for label, fileset in self.filesets.items(): for fn in fileset: new_chroot.link(os.path.join(self.chroot, fn), fn, label=label) return new_chroot
def function[clone, parameter[self, into]]: constant[Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbage collected on interpreter exit. ] variable[into] assign[=] <ast.BoolOp object at 0x7da2043456c0> variable[new_chroot] assign[=] call[name[Chroot], parameter[name[into]]] for taget[tuple[[<ast.Name object at 0x7da2043446a0>, <ast.Name object at 0x7da204347b50>]]] in starred[call[name[self].filesets.items, parameter[]]] begin[:] for taget[name[fn]] in starred[name[fileset]] begin[:] call[name[new_chroot].link, parameter[call[name[os].path.join, parameter[name[self].chroot, name[fn]]], name[fn]]] return[name[new_chroot]]
keyword[def] identifier[clone] ( identifier[self] , identifier[into] = keyword[None] ): literal[string] identifier[into] = identifier[into] keyword[or] identifier[safe_mkdtemp] () identifier[new_chroot] = identifier[Chroot] ( identifier[into] ) keyword[for] identifier[label] , identifier[fileset] keyword[in] identifier[self] . identifier[filesets] . identifier[items] (): keyword[for] identifier[fn] keyword[in] identifier[fileset] : identifier[new_chroot] . identifier[link] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[chroot] , identifier[fn] ), identifier[fn] , identifier[label] = identifier[label] ) keyword[return] identifier[new_chroot]
def clone(self, into=None): """Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbage collected on interpreter exit. """ into = into or safe_mkdtemp() new_chroot = Chroot(into) for (label, fileset) in self.filesets.items(): for fn in fileset: new_chroot.link(os.path.join(self.chroot, fn), fn, label=label) # depends on [control=['for'], data=['fn']] # depends on [control=['for'], data=[]] return new_chroot
def html_tags_for(self, asset_type, *args, **kwargs): """Return html tags for urls of asset_type """ html = [] for ref in self.depends: html.append(self._ref(ref).html_tags_for(asset_type, *args, **kwargs)) if asset_type in self.typed_bundles: html.append(render_asset_html_tags(asset_type, self.urls_for_self(asset_type, *args, **kwargs))) return "\n".join(html)
def function[html_tags_for, parameter[self, asset_type]]: constant[Return html tags for urls of asset_type ] variable[html] assign[=] list[[]] for taget[name[ref]] in starred[name[self].depends] begin[:] call[name[html].append, parameter[call[call[name[self]._ref, parameter[name[ref]]].html_tags_for, parameter[name[asset_type], <ast.Starred object at 0x7da1b01a75e0>]]]] if compare[name[asset_type] in name[self].typed_bundles] begin[:] call[name[html].append, parameter[call[name[render_asset_html_tags], parameter[name[asset_type], call[name[self].urls_for_self, parameter[name[asset_type], <ast.Starred object at 0x7da1b01a7f10>]]]]]] return[call[constant[ ].join, parameter[name[html]]]]
keyword[def] identifier[html_tags_for] ( identifier[self] , identifier[asset_type] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[html] =[] keyword[for] identifier[ref] keyword[in] identifier[self] . identifier[depends] : identifier[html] . identifier[append] ( identifier[self] . identifier[_ref] ( identifier[ref] ). identifier[html_tags_for] ( identifier[asset_type] ,* identifier[args] ,** identifier[kwargs] )) keyword[if] identifier[asset_type] keyword[in] identifier[self] . identifier[typed_bundles] : identifier[html] . identifier[append] ( identifier[render_asset_html_tags] ( identifier[asset_type] , identifier[self] . identifier[urls_for_self] ( identifier[asset_type] ,* identifier[args] ,** identifier[kwargs] ))) keyword[return] literal[string] . identifier[join] ( identifier[html] )
def html_tags_for(self, asset_type, *args, **kwargs): """Return html tags for urls of asset_type """ html = [] for ref in self.depends: html.append(self._ref(ref).html_tags_for(asset_type, *args, **kwargs)) # depends on [control=['for'], data=['ref']] if asset_type in self.typed_bundles: html.append(render_asset_html_tags(asset_type, self.urls_for_self(asset_type, *args, **kwargs))) # depends on [control=['if'], data=['asset_type']] return '\n'.join(html)
def __optimize(self): """ Merge overlapping or contacting subranges from ``self.__has`` attribute and update it. Called from all methods that modify object contents. Returns ------- None Method does not return. It does internal modifications on ``self.__has`` attribute. """ ret = [] for (begin, end) in sorted(self.__has): if ret and begin <= ret[-1][1] < end: # when current range overlaps with the last one from ret ret[-1] = (ret[-1][0], end) elif not ret or begin > ret[-1][1]: ret.append( (begin, end) ) self.__has = set(ret)
def function[__optimize, parameter[self]]: constant[ Merge overlapping or contacting subranges from ``self.__has`` attribute and update it. Called from all methods that modify object contents. Returns ------- None Method does not return. It does internal modifications on ``self.__has`` attribute. ] variable[ret] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b0ebdfc0>, <ast.Name object at 0x7da1b0ebe260>]]] in starred[call[name[sorted], parameter[name[self].__has]]] begin[:] if <ast.BoolOp object at 0x7da1b0ebfca0> begin[:] call[name[ret]][<ast.UnaryOp object at 0x7da1b0ebd510>] assign[=] tuple[[<ast.Subscript object at 0x7da1b0ebedd0>, <ast.Name object at 0x7da1b0ebfee0>]] name[self].__has assign[=] call[name[set], parameter[name[ret]]]
keyword[def] identifier[__optimize] ( identifier[self] ): literal[string] identifier[ret] =[] keyword[for] ( identifier[begin] , identifier[end] ) keyword[in] identifier[sorted] ( identifier[self] . identifier[__has] ): keyword[if] identifier[ret] keyword[and] identifier[begin] <= identifier[ret] [- literal[int] ][ literal[int] ]< identifier[end] : identifier[ret] [- literal[int] ]=( identifier[ret] [- literal[int] ][ literal[int] ], identifier[end] ) keyword[elif] keyword[not] identifier[ret] keyword[or] identifier[begin] > identifier[ret] [- literal[int] ][ literal[int] ]: identifier[ret] . identifier[append] (( identifier[begin] , identifier[end] )) identifier[self] . identifier[__has] = identifier[set] ( identifier[ret] )
def __optimize(self): """ Merge overlapping or contacting subranges from ``self.__has`` attribute and update it. Called from all methods that modify object contents. Returns ------- None Method does not return. It does internal modifications on ``self.__has`` attribute. """ ret = [] for (begin, end) in sorted(self.__has): if ret and begin <= ret[-1][1] < end: # when current range overlaps with the last one from ret ret[-1] = (ret[-1][0], end) # depends on [control=['if'], data=[]] elif not ret or begin > ret[-1][1]: ret.append((begin, end)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] self.__has = set(ret)
def recursive_derived(self): """list of all :class:`derive classes <hierarchy_info_t>`""" if self._recursive_derived is None: to_go = self.derived[:] all_derived = [] while to_go: derive = to_go.pop() if derive not in all_derived: all_derived.append(derive) to_go.extend(derive.related_class.derived) self._recursive_derived = all_derived return self._recursive_derived
def function[recursive_derived, parameter[self]]: constant[list of all :class:`derive classes <hierarchy_info_t>`] if compare[name[self]._recursive_derived is constant[None]] begin[:] variable[to_go] assign[=] call[name[self].derived][<ast.Slice object at 0x7da1b13a52d0>] variable[all_derived] assign[=] list[[]] while name[to_go] begin[:] variable[derive] assign[=] call[name[to_go].pop, parameter[]] if compare[name[derive] <ast.NotIn object at 0x7da2590d7190> name[all_derived]] begin[:] call[name[all_derived].append, parameter[name[derive]]] call[name[to_go].extend, parameter[name[derive].related_class.derived]] name[self]._recursive_derived assign[=] name[all_derived] return[name[self]._recursive_derived]
keyword[def] identifier[recursive_derived] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_recursive_derived] keyword[is] keyword[None] : identifier[to_go] = identifier[self] . identifier[derived] [:] identifier[all_derived] =[] keyword[while] identifier[to_go] : identifier[derive] = identifier[to_go] . identifier[pop] () keyword[if] identifier[derive] keyword[not] keyword[in] identifier[all_derived] : identifier[all_derived] . identifier[append] ( identifier[derive] ) identifier[to_go] . identifier[extend] ( identifier[derive] . identifier[related_class] . identifier[derived] ) identifier[self] . identifier[_recursive_derived] = identifier[all_derived] keyword[return] identifier[self] . identifier[_recursive_derived]
def recursive_derived(self): """list of all :class:`derive classes <hierarchy_info_t>`""" if self._recursive_derived is None: to_go = self.derived[:] all_derived = [] while to_go: derive = to_go.pop() if derive not in all_derived: all_derived.append(derive) to_go.extend(derive.related_class.derived) # depends on [control=['if'], data=['derive', 'all_derived']] # depends on [control=['while'], data=[]] self._recursive_derived = all_derived # depends on [control=['if'], data=[]] return self._recursive_derived
def _parse_plugin_data_as(content, data_oneof_field): """Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have 'data_oneof_field' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use. data_oneof_field: string. The name of the data oneof field to return. """ plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content) if plugin_data.version != PLUGIN_DATA_VERSION: raise error.HParamsError( 'Only supports plugin_data version: %s; found: %s in: %s' % (PLUGIN_DATA_VERSION, plugin_data.version, plugin_data)) if not plugin_data.HasField(data_oneof_field): raise error.HParamsError( 'Expected plugin_data.%s to be set. Got: %s' % (data_oneof_field, plugin_data)) return getattr(plugin_data, data_oneof_field)
def function[_parse_plugin_data_as, parameter[content, data_oneof_field]]: constant[Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have 'data_oneof_field' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use. data_oneof_field: string. The name of the data oneof field to return. ] variable[plugin_data] assign[=] call[name[plugin_data_pb2].HParamsPluginData.FromString, parameter[name[content]]] if compare[name[plugin_data].version not_equal[!=] name[PLUGIN_DATA_VERSION]] begin[:] <ast.Raise object at 0x7da18c4cfd90> if <ast.UnaryOp object at 0x7da18c4cc400> begin[:] <ast.Raise object at 0x7da18c4cd2a0> return[call[name[getattr], parameter[name[plugin_data], name[data_oneof_field]]]]
keyword[def] identifier[_parse_plugin_data_as] ( identifier[content] , identifier[data_oneof_field] ): literal[string] identifier[plugin_data] = identifier[plugin_data_pb2] . identifier[HParamsPluginData] . identifier[FromString] ( identifier[content] ) keyword[if] identifier[plugin_data] . identifier[version] != identifier[PLUGIN_DATA_VERSION] : keyword[raise] identifier[error] . identifier[HParamsError] ( literal[string] % ( identifier[PLUGIN_DATA_VERSION] , identifier[plugin_data] . identifier[version] , identifier[plugin_data] )) keyword[if] keyword[not] identifier[plugin_data] . identifier[HasField] ( identifier[data_oneof_field] ): keyword[raise] identifier[error] . identifier[HParamsError] ( literal[string] % ( identifier[data_oneof_field] , identifier[plugin_data] )) keyword[return] identifier[getattr] ( identifier[plugin_data] , identifier[data_oneof_field] )
def _parse_plugin_data_as(content, data_oneof_field): """Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have 'data_oneof_field' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.content to use. data_oneof_field: string. The name of the data oneof field to return. """ plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content) if plugin_data.version != PLUGIN_DATA_VERSION: raise error.HParamsError('Only supports plugin_data version: %s; found: %s in: %s' % (PLUGIN_DATA_VERSION, plugin_data.version, plugin_data)) # depends on [control=['if'], data=['PLUGIN_DATA_VERSION']] if not plugin_data.HasField(data_oneof_field): raise error.HParamsError('Expected plugin_data.%s to be set. Got: %s' % (data_oneof_field, plugin_data)) # depends on [control=['if'], data=[]] return getattr(plugin_data, data_oneof_field)
def replace_surrogate_decode(mybytes): """ Returns a (unicode) string """ decoded = [] for ch in mybytes: # We may be parsing newbytes (in which case ch is an int) or a native # str on Py2 if isinstance(ch, int): code = ch else: code = ord(ch) if 0x80 <= code <= 0xFF: decoded.append(_unichr(0xDC00 + code)) elif code <= 0x7F: decoded.append(_unichr(code)) else: # # It may be a bad byte # # Try swallowing it. # continue # print("RAISE!") raise NotASurrogateError return str().join(decoded)
def function[replace_surrogate_decode, parameter[mybytes]]: constant[ Returns a (unicode) string ] variable[decoded] assign[=] list[[]] for taget[name[ch]] in starred[name[mybytes]] begin[:] if call[name[isinstance], parameter[name[ch], name[int]]] begin[:] variable[code] assign[=] name[ch] if compare[constant[128] less_or_equal[<=] name[code]] begin[:] call[name[decoded].append, parameter[call[name[_unichr], parameter[binary_operation[constant[56320] + name[code]]]]]] return[call[call[name[str], parameter[]].join, parameter[name[decoded]]]]
keyword[def] identifier[replace_surrogate_decode] ( identifier[mybytes] ): literal[string] identifier[decoded] =[] keyword[for] identifier[ch] keyword[in] identifier[mybytes] : keyword[if] identifier[isinstance] ( identifier[ch] , identifier[int] ): identifier[code] = identifier[ch] keyword[else] : identifier[code] = identifier[ord] ( identifier[ch] ) keyword[if] literal[int] <= identifier[code] <= literal[int] : identifier[decoded] . identifier[append] ( identifier[_unichr] ( literal[int] + identifier[code] )) keyword[elif] identifier[code] <= literal[int] : identifier[decoded] . identifier[append] ( identifier[_unichr] ( identifier[code] )) keyword[else] : keyword[raise] identifier[NotASurrogateError] keyword[return] identifier[str] (). identifier[join] ( identifier[decoded] )
def replace_surrogate_decode(mybytes): """ Returns a (unicode) string """ decoded = [] for ch in mybytes: # We may be parsing newbytes (in which case ch is an int) or a native # str on Py2 if isinstance(ch, int): code = ch # depends on [control=['if'], data=[]] else: code = ord(ch) if 128 <= code <= 255: decoded.append(_unichr(56320 + code)) # depends on [control=['if'], data=['code']] elif code <= 127: decoded.append(_unichr(code)) # depends on [control=['if'], data=['code']] else: # # It may be a bad byte # # Try swallowing it. # continue # print("RAISE!") raise NotASurrogateError # depends on [control=['for'], data=['ch']] return str().join(decoded)
def find_by_index(self, cls, index_name, value): """Required functionality.""" return self._find(cls, {index_name: str(value)})
def function[find_by_index, parameter[self, cls, index_name, value]]: constant[Required functionality.] return[call[name[self]._find, parameter[name[cls], dictionary[[<ast.Name object at 0x7da204621ea0>], [<ast.Call object at 0x7da204623c10>]]]]]
keyword[def] identifier[find_by_index] ( identifier[self] , identifier[cls] , identifier[index_name] , identifier[value] ): literal[string] keyword[return] identifier[self] . identifier[_find] ( identifier[cls] ,{ identifier[index_name] : identifier[str] ( identifier[value] )})
def find_by_index(self, cls, index_name, value): """Required functionality.""" return self._find(cls, {index_name: str(value)})
def run(self): """ generate <nreq> requests taking a random amount of time between 0 and 0.5 seconds """ for i in xrange(self.nreq): req = '%s_%s' % (self.ident, i) pre_request(None, req) sleep(random() / 2) post_request(None, req)
def function[run, parameter[self]]: constant[ generate <nreq> requests taking a random amount of time between 0 and 0.5 seconds ] for taget[name[i]] in starred[call[name[xrange], parameter[name[self].nreq]]] begin[:] variable[req] assign[=] binary_operation[constant[%s_%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18c4cea70>, <ast.Name object at 0x7da18c4cf220>]]] call[name[pre_request], parameter[constant[None], name[req]]] call[name[sleep], parameter[binary_operation[call[name[random], parameter[]] / constant[2]]]] call[name[post_request], parameter[constant[None], name[req]]]
keyword[def] identifier[run] ( identifier[self] ): literal[string] keyword[for] identifier[i] keyword[in] identifier[xrange] ( identifier[self] . identifier[nreq] ): identifier[req] = literal[string] %( identifier[self] . identifier[ident] , identifier[i] ) identifier[pre_request] ( keyword[None] , identifier[req] ) identifier[sleep] ( identifier[random] ()/ literal[int] ) identifier[post_request] ( keyword[None] , identifier[req] )
def run(self): """ generate <nreq> requests taking a random amount of time between 0 and 0.5 seconds """ for i in xrange(self.nreq): req = '%s_%s' % (self.ident, i) pre_request(None, req) sleep(random() / 2) post_request(None, req) # depends on [control=['for'], data=['i']]
def get_summary(self, s, base=None): """ Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary'``. Otherwise, it will not be stored at all Returns ------- str The extracted summary""" summary = summary_patt.search(s).group() if base is not None: self.params[base + '.summary'] = summary return summary
def function[get_summary, parameter[self, s, base]]: constant[ Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary'``. Otherwise, it will not be stored at all Returns ------- str The extracted summary] variable[summary] assign[=] call[call[name[summary_patt].search, parameter[name[s]]].group, parameter[]] if compare[name[base] is_not constant[None]] begin[:] call[name[self].params][binary_operation[name[base] + constant[.summary]]] assign[=] name[summary] return[name[summary]]
keyword[def] identifier[get_summary] ( identifier[self] , identifier[s] , identifier[base] = keyword[None] ): literal[string] identifier[summary] = identifier[summary_patt] . identifier[search] ( identifier[s] ). identifier[group] () keyword[if] identifier[base] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[params] [ identifier[base] + literal[string] ]= identifier[summary] keyword[return] identifier[summary]
def get_summary(self, s, base=None): """ Get the summary of the given docstring This method extracts the summary from the given docstring `s` which is basicly the part until two newlines appear Parameters ---------- s: str The docstring to use base: str or None A key under which the summary shall be stored in the :attr:`params` attribute. If not None, the summary will be stored in ``base + '.summary'``. Otherwise, it will not be stored at all Returns ------- str The extracted summary""" summary = summary_patt.search(s).group() if base is not None: self.params[base + '.summary'] = summary # depends on [control=['if'], data=['base']] return summary
def columns_in_formula(formula): """ Returns the names of all the columns used in a patsy formula. Parameters ---------- formula : str, iterable, or dict Any formula construction supported by ``str_model_expression``. Returns ------- columns : list of str """ if formula is None: return [] formula = str_model_expression(formula, add_constant=False) columns = [] tokens = map( lambda x: x.extra, tz.remove( lambda x: x.extra is None, _tokens_from_patsy(patsy.parse_formula.parse_formula(formula)))) for tok in tokens: # if there are parentheses in the expression we # want to drop them and everything outside # and start again from the top if '(' in tok: start = tok.find('(') + 1 fin = tok.rfind(')') columns.extend(columns_in_formula(tok[start:fin])) else: for toknum, tokval, _, _, _ in generate_tokens( StringIO(tok).readline): if toknum == NAME: columns.append(tokval) return list(tz.unique(columns))
def function[columns_in_formula, parameter[formula]]: constant[ Returns the names of all the columns used in a patsy formula. Parameters ---------- formula : str, iterable, or dict Any formula construction supported by ``str_model_expression``. Returns ------- columns : list of str ] if compare[name[formula] is constant[None]] begin[:] return[list[[]]] variable[formula] assign[=] call[name[str_model_expression], parameter[name[formula]]] variable[columns] assign[=] list[[]] variable[tokens] assign[=] call[name[map], parameter[<ast.Lambda object at 0x7da18dc99f00>, call[name[tz].remove, parameter[<ast.Lambda object at 0x7da18dc99210>, call[name[_tokens_from_patsy], parameter[call[name[patsy].parse_formula.parse_formula, parameter[name[formula]]]]]]]]] for taget[name[tok]] in starred[name[tokens]] begin[:] if compare[constant[(] in name[tok]] begin[:] variable[start] assign[=] binary_operation[call[name[tok].find, parameter[constant[(]]] + constant[1]] variable[fin] assign[=] call[name[tok].rfind, parameter[constant[)]]] call[name[columns].extend, parameter[call[name[columns_in_formula], parameter[call[name[tok]][<ast.Slice object at 0x7da18f09df00>]]]]] return[call[name[list], parameter[call[name[tz].unique, parameter[name[columns]]]]]]
keyword[def] identifier[columns_in_formula] ( identifier[formula] ): literal[string] keyword[if] identifier[formula] keyword[is] keyword[None] : keyword[return] [] identifier[formula] = identifier[str_model_expression] ( identifier[formula] , identifier[add_constant] = keyword[False] ) identifier[columns] =[] identifier[tokens] = identifier[map] ( keyword[lambda] identifier[x] : identifier[x] . identifier[extra] , identifier[tz] . identifier[remove] ( keyword[lambda] identifier[x] : identifier[x] . identifier[extra] keyword[is] keyword[None] , identifier[_tokens_from_patsy] ( identifier[patsy] . identifier[parse_formula] . identifier[parse_formula] ( identifier[formula] )))) keyword[for] identifier[tok] keyword[in] identifier[tokens] : keyword[if] literal[string] keyword[in] identifier[tok] : identifier[start] = identifier[tok] . identifier[find] ( literal[string] )+ literal[int] identifier[fin] = identifier[tok] . identifier[rfind] ( literal[string] ) identifier[columns] . identifier[extend] ( identifier[columns_in_formula] ( identifier[tok] [ identifier[start] : identifier[fin] ])) keyword[else] : keyword[for] identifier[toknum] , identifier[tokval] , identifier[_] , identifier[_] , identifier[_] keyword[in] identifier[generate_tokens] ( identifier[StringIO] ( identifier[tok] ). identifier[readline] ): keyword[if] identifier[toknum] == identifier[NAME] : identifier[columns] . identifier[append] ( identifier[tokval] ) keyword[return] identifier[list] ( identifier[tz] . identifier[unique] ( identifier[columns] ))
def columns_in_formula(formula): """ Returns the names of all the columns used in a patsy formula. Parameters ---------- formula : str, iterable, or dict Any formula construction supported by ``str_model_expression``. Returns ------- columns : list of str """ if formula is None: return [] # depends on [control=['if'], data=[]] formula = str_model_expression(formula, add_constant=False) columns = [] tokens = map(lambda x: x.extra, tz.remove(lambda x: x.extra is None, _tokens_from_patsy(patsy.parse_formula.parse_formula(formula)))) for tok in tokens: # if there are parentheses in the expression we # want to drop them and everything outside # and start again from the top if '(' in tok: start = tok.find('(') + 1 fin = tok.rfind(')') columns.extend(columns_in_formula(tok[start:fin])) # depends on [control=['if'], data=['tok']] else: for (toknum, tokval, _, _, _) in generate_tokens(StringIO(tok).readline): if toknum == NAME: columns.append(tokval) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['tok']] return list(tz.unique(columns))
def _do_retrieve(url, fname): """Retrieve given url to target filepath fname.""" folder = os.path.dirname(fname) if not os.path.exists(folder): os.makedirs(folder) print("{}/ created.".format(folder)) if not os.path.exists(fname): with open(fname, 'wb') as fout: print("retrieving {}.".format(url)) resp = urlopen(url) fout.write(resp.read()) print("{} saved.".format(fname)) else: print("re-using artifact {}".format(fname)) return fname
def function[_do_retrieve, parameter[url, fname]]: constant[Retrieve given url to target filepath fname.] variable[folder] assign[=] call[name[os].path.dirname, parameter[name[fname]]] if <ast.UnaryOp object at 0x7da20e9b39a0> begin[:] call[name[os].makedirs, parameter[name[folder]]] call[name[print], parameter[call[constant[{}/ created.].format, parameter[name[folder]]]]] if <ast.UnaryOp object at 0x7da20e9b3ca0> begin[:] with call[name[open], parameter[name[fname], constant[wb]]] begin[:] call[name[print], parameter[call[constant[retrieving {}.].format, parameter[name[url]]]]] variable[resp] assign[=] call[name[urlopen], parameter[name[url]]] call[name[fout].write, parameter[call[name[resp].read, parameter[]]]] call[name[print], parameter[call[constant[{} saved.].format, parameter[name[fname]]]]] return[name[fname]]
keyword[def] identifier[_do_retrieve] ( identifier[url] , identifier[fname] ): literal[string] identifier[folder] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[fname] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[folder] ): identifier[os] . identifier[makedirs] ( identifier[folder] ) identifier[print] ( literal[string] . identifier[format] ( identifier[folder] )) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[fname] ): keyword[with] identifier[open] ( identifier[fname] , literal[string] ) keyword[as] identifier[fout] : identifier[print] ( literal[string] . identifier[format] ( identifier[url] )) identifier[resp] = identifier[urlopen] ( identifier[url] ) identifier[fout] . identifier[write] ( identifier[resp] . identifier[read] ()) identifier[print] ( literal[string] . identifier[format] ( identifier[fname] )) keyword[else] : identifier[print] ( literal[string] . identifier[format] ( identifier[fname] )) keyword[return] identifier[fname]
def _do_retrieve(url, fname): """Retrieve given url to target filepath fname.""" folder = os.path.dirname(fname) if not os.path.exists(folder): os.makedirs(folder) print('{}/ created.'.format(folder)) # depends on [control=['if'], data=[]] if not os.path.exists(fname): with open(fname, 'wb') as fout: print('retrieving {}.'.format(url)) resp = urlopen(url) fout.write(resp.read()) # depends on [control=['with'], data=['fout']] print('{} saved.'.format(fname)) # depends on [control=['if'], data=[]] else: print('re-using artifact {}'.format(fname)) return fname
def remove_webhook(self): """Remove webhook.""" if self._webhook.get('hook_id'): self._request( "{}/{}".format(MINUT_WEBHOOKS_URL, self._webhook['hook_id']), request_type='DELETE', )
def function[remove_webhook, parameter[self]]: constant[Remove webhook.] if call[name[self]._webhook.get, parameter[constant[hook_id]]] begin[:] call[name[self]._request, parameter[call[constant[{}/{}].format, parameter[name[MINUT_WEBHOOKS_URL], call[name[self]._webhook][constant[hook_id]]]]]]
keyword[def] identifier[remove_webhook] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_webhook] . identifier[get] ( literal[string] ): identifier[self] . identifier[_request] ( literal[string] . identifier[format] ( identifier[MINUT_WEBHOOKS_URL] , identifier[self] . identifier[_webhook] [ literal[string] ]), identifier[request_type] = literal[string] , )
def remove_webhook(self): """Remove webhook.""" if self._webhook.get('hook_id'): self._request('{}/{}'.format(MINUT_WEBHOOKS_URL, self._webhook['hook_id']), request_type='DELETE') # depends on [control=['if'], data=[]]
def write_with_mac(self, data, block): """Write one data block with additional integrity check. If prior to calling this method the tag was not authenticated, a :exc:`RuntimeError` exception is raised. Command execution errors raise :exc:`~nfc.tag.TagCommandError`. """ # Write a single data block protected with a mac. The card # will only accept the write if it computed the same mac. log.debug("write 1 block with mac") if len(data) != 16: raise ValueError("data must be 16 octets") if type(block) is not int: raise ValueError("block number must be int") if self._sk is None or self._iv is None: raise RuntimeError("tag must be authenticated first") # The write count is the first three byte of the wcnt block. wcnt = str(self.read_without_mac(0x90)[0:3]) log.debug("write count is 0x{0}".format(wcnt[::-1].encode("hex"))) # We must generate the mac_a block to write the data. The data # to encrypt to the mac is composed of write count and block # numbers (8 byte) and the data we want to write. The mac for # write must be generated with the key flipped (sk2 || sk1). def flip(sk): return sk[8:16] + sk[0:8] data = wcnt + "\x00" + chr(block) + "\x00\x91\x00" + data maca = self.generate_mac(data, flip(self._sk), self._iv) + wcnt+5*"\0" # Now we can write the data block with our computed mac to the # desired block and the maca block. Write without encryption # means that the data is not encrypted with a service key. sc_list = [tt3.ServiceCode(0, 0b001001)] bc_list = [tt3.BlockCode(block), tt3.BlockCode(0x91)] self.write_without_encryption(sc_list, bc_list, data[8:24] + maca)
def function[write_with_mac, parameter[self, data, block]]: constant[Write one data block with additional integrity check. If prior to calling this method the tag was not authenticated, a :exc:`RuntimeError` exception is raised. Command execution errors raise :exc:`~nfc.tag.TagCommandError`. ] call[name[log].debug, parameter[constant[write 1 block with mac]]] if compare[call[name[len], parameter[name[data]]] not_equal[!=] constant[16]] begin[:] <ast.Raise object at 0x7da2054a5f30> if compare[call[name[type], parameter[name[block]]] is_not name[int]] begin[:] <ast.Raise object at 0x7da2054a7610> if <ast.BoolOp object at 0x7da2054a5de0> begin[:] <ast.Raise object at 0x7da20c990d00> variable[wcnt] assign[=] call[name[str], parameter[call[call[name[self].read_without_mac, parameter[constant[144]]]][<ast.Slice object at 0x7da20c992e90>]]] call[name[log].debug, parameter[call[constant[write count is 0x{0}].format, parameter[call[call[name[wcnt]][<ast.Slice object at 0x7da20c993070>].encode, parameter[constant[hex]]]]]]] def function[flip, parameter[sk]]: return[binary_operation[call[name[sk]][<ast.Slice object at 0x7da20c991630>] + call[name[sk]][<ast.Slice object at 0x7da20c991780>]]] variable[data] assign[=] binary_operation[binary_operation[binary_operation[binary_operation[name[wcnt] + constant[]] + call[name[chr], parameter[name[block]]]] + constant[‘]] + name[data]] variable[maca] assign[=] binary_operation[binary_operation[call[name[self].generate_mac, parameter[name[data], call[name[flip], parameter[name[self]._sk]], name[self]._iv]] + name[wcnt]] + binary_operation[constant[5] * constant[]]] variable[sc_list] assign[=] list[[<ast.Call object at 0x7da20c9907c0>]] variable[bc_list] assign[=] list[[<ast.Call object at 0x7da20c9904c0>, <ast.Call object at 0x7da20c990280>]] call[name[self].write_without_encryption, parameter[name[sc_list], name[bc_list], binary_operation[call[name[data]][<ast.Slice object at 0x7da20c991e40>] + name[maca]]]]
keyword[def] identifier[write_with_mac] ( identifier[self] , identifier[data] , identifier[block] ): literal[string] identifier[log] . identifier[debug] ( literal[string] ) keyword[if] identifier[len] ( identifier[data] )!= literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[type] ( identifier[block] ) keyword[is] keyword[not] identifier[int] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[self] . identifier[_sk] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_iv] keyword[is] keyword[None] : keyword[raise] identifier[RuntimeError] ( literal[string] ) identifier[wcnt] = identifier[str] ( identifier[self] . identifier[read_without_mac] ( literal[int] )[ literal[int] : literal[int] ]) identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[wcnt] [::- literal[int] ]. identifier[encode] ( literal[string] ))) keyword[def] identifier[flip] ( identifier[sk] ): keyword[return] identifier[sk] [ literal[int] : literal[int] ]+ identifier[sk] [ literal[int] : literal[int] ] identifier[data] = identifier[wcnt] + literal[string] + identifier[chr] ( identifier[block] )+ literal[string] + identifier[data] identifier[maca] = identifier[self] . identifier[generate_mac] ( identifier[data] , identifier[flip] ( identifier[self] . identifier[_sk] ), identifier[self] . identifier[_iv] )+ identifier[wcnt] + literal[int] * literal[string] identifier[sc_list] =[ identifier[tt3] . identifier[ServiceCode] ( literal[int] , literal[int] )] identifier[bc_list] =[ identifier[tt3] . identifier[BlockCode] ( identifier[block] ), identifier[tt3] . identifier[BlockCode] ( literal[int] )] identifier[self] . identifier[write_without_encryption] ( identifier[sc_list] , identifier[bc_list] , identifier[data] [ literal[int] : literal[int] ]+ identifier[maca] )
def write_with_mac(self, data, block): """Write one data block with additional integrity check. If prior to calling this method the tag was not authenticated, a :exc:`RuntimeError` exception is raised. Command execution errors raise :exc:`~nfc.tag.TagCommandError`. """ # Write a single data block protected with a mac. The card # will only accept the write if it computed the same mac. log.debug('write 1 block with mac') if len(data) != 16: raise ValueError('data must be 16 octets') # depends on [control=['if'], data=[]] if type(block) is not int: raise ValueError('block number must be int') # depends on [control=['if'], data=[]] if self._sk is None or self._iv is None: raise RuntimeError('tag must be authenticated first') # depends on [control=['if'], data=[]] # The write count is the first three byte of the wcnt block. wcnt = str(self.read_without_mac(144)[0:3]) log.debug('write count is 0x{0}'.format(wcnt[::-1].encode('hex'))) # We must generate the mac_a block to write the data. The data # to encrypt to the mac is composed of write count and block # numbers (8 byte) and the data we want to write. The mac for # write must be generated with the key flipped (sk2 || sk1). def flip(sk): return sk[8:16] + sk[0:8] data = wcnt + '\x00' + chr(block) + '\x00\x91\x00' + data maca = self.generate_mac(data, flip(self._sk), self._iv) + wcnt + 5 * '\x00' # Now we can write the data block with our computed mac to the # desired block and the maca block. Write without encryption # means that the data is not encrypted with a service key. sc_list = [tt3.ServiceCode(0, 9)] bc_list = [tt3.BlockCode(block), tt3.BlockCode(145)] self.write_without_encryption(sc_list, bc_list, data[8:24] + maca)
def mount(self, volume): """Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is added to the subvolume set of this volume. Requires the user to enter the key manually. TODO: add support for :attr:`keys` :return: the Volume contained in the LUKS container, or None on failure. :raises NoLoopbackAvailableError: when no free loopback could be found :raises IncorrectFilesystemError: when this is not a LUKS volume :raises SubsystemError: when the underlying command fails """ # Open a loopback device volume._find_loopback() # Check if this is a LUKS device # noinspection PyBroadException try: _util.check_call_(["cryptsetup", "isLuks", volume.loopback], stderr=subprocess.STDOUT) # ret = 0 if isLuks except Exception: logger.warning("Not a LUKS volume") # clean the loopback device, we want this method to be clean as possible # noinspection PyBroadException try: volume._free_loopback() except Exception: pass raise IncorrectFilesystemError() try: extra_args = [] key = None if volume.key: t, v = volume.key.split(':', 1) if t == 'p': # passphrase key = v elif t == 'f': # key-file extra_args = ['--key-file', v] elif t == 'm': # master-key-file extra_args = ['--master-key-file', v] else: logger.warning("No key material provided for %s", volume) except ValueError: logger.exception("Invalid key material provided (%s) for %s. Expecting [arg]:[value]", volume.key, volume) volume._free_loopback() raise ArgumentError() # Open the LUKS container volume._paths['luks'] = 'image_mounter_luks_' + str(random.randint(10000, 99999)) # noinspection PyBroadException try: cmd = ["cryptsetup", "luksOpen", volume.loopback, volume._paths['luks']] cmd.extend(extra_args) if not volume.disk.read_write: cmd.insert(1, '-r') if key is not None: logger.debug('$ {0}'.format(' '.join(cmd))) # for py 3.2+, we could have used input=, but that doesn't exist in py2.7. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate(key.encode("utf-8")) p.wait() retcode = p.poll() if retcode: raise KeyInvalidError() else: _util.check_call_(cmd) except ImageMounterError: del volume._paths['luks'] volume._free_loopback() raise except Exception as e: del volume._paths['luks'] volume._free_loopback() raise SubsystemError(e) size = None # noinspection PyBroadException try: result = _util.check_output_(["cryptsetup", "status", volume._paths['luks']]) for l in result.splitlines(): if "size:" in l and "key" not in l: size = int(l.replace("size:", "").replace("sectors", "").strip()) * volume.disk.block_size except Exception: pass container = volume.volumes._make_single_subvolume(flag='alloc', offset=0, size=size) container.info['fsdescription'] = 'LUKS Volume' return container
def function[mount, parameter[self, volume]]: constant[Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is added to the subvolume set of this volume. Requires the user to enter the key manually. TODO: add support for :attr:`keys` :return: the Volume contained in the LUKS container, or None on failure. :raises NoLoopbackAvailableError: when no free loopback could be found :raises IncorrectFilesystemError: when this is not a LUKS volume :raises SubsystemError: when the underlying command fails ] call[name[volume]._find_loopback, parameter[]] <ast.Try object at 0x7da1b0404c10> <ast.Try object at 0x7da1b0405a50> call[name[volume]._paths][constant[luks]] assign[=] binary_operation[constant[image_mounter_luks_] + call[name[str], parameter[call[name[random].randint, parameter[constant[10000], constant[99999]]]]]] <ast.Try object at 0x7da1b06514b0> variable[size] assign[=] constant[None] <ast.Try object at 0x7da1b04983a0> variable[container] assign[=] call[name[volume].volumes._make_single_subvolume, parameter[]] call[name[container].info][constant[fsdescription]] assign[=] constant[LUKS Volume] return[name[container]]
keyword[def] identifier[mount] ( identifier[self] , identifier[volume] ): literal[string] identifier[volume] . identifier[_find_loopback] () keyword[try] : identifier[_util] . identifier[check_call_] ([ literal[string] , literal[string] , identifier[volume] . identifier[loopback] ], identifier[stderr] = identifier[subprocess] . identifier[STDOUT] ) keyword[except] identifier[Exception] : identifier[logger] . identifier[warning] ( literal[string] ) keyword[try] : identifier[volume] . identifier[_free_loopback] () keyword[except] identifier[Exception] : keyword[pass] keyword[raise] identifier[IncorrectFilesystemError] () keyword[try] : identifier[extra_args] =[] identifier[key] = keyword[None] keyword[if] identifier[volume] . identifier[key] : identifier[t] , identifier[v] = identifier[volume] . identifier[key] . identifier[split] ( literal[string] , literal[int] ) keyword[if] identifier[t] == literal[string] : identifier[key] = identifier[v] keyword[elif] identifier[t] == literal[string] : identifier[extra_args] =[ literal[string] , identifier[v] ] keyword[elif] identifier[t] == literal[string] : identifier[extra_args] =[ literal[string] , identifier[v] ] keyword[else] : identifier[logger] . identifier[warning] ( literal[string] , identifier[volume] ) keyword[except] identifier[ValueError] : identifier[logger] . identifier[exception] ( literal[string] , identifier[volume] . identifier[key] , identifier[volume] ) identifier[volume] . identifier[_free_loopback] () keyword[raise] identifier[ArgumentError] () identifier[volume] . identifier[_paths] [ literal[string] ]= literal[string] + identifier[str] ( identifier[random] . identifier[randint] ( literal[int] , literal[int] )) keyword[try] : identifier[cmd] =[ literal[string] , literal[string] , identifier[volume] . identifier[loopback] , identifier[volume] . identifier[_paths] [ literal[string] ]] identifier[cmd] . identifier[extend] ( identifier[extra_args] ) keyword[if] keyword[not] identifier[volume] . identifier[disk] . identifier[read_write] : identifier[cmd] . identifier[insert] ( literal[int] , literal[string] ) keyword[if] identifier[key] keyword[is] keyword[not] keyword[None] : identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( literal[string] . identifier[join] ( identifier[cmd] ))) identifier[p] = identifier[subprocess] . identifier[Popen] ( identifier[cmd] , identifier[stdin] = identifier[subprocess] . identifier[PIPE] , identifier[stdout] = identifier[subprocess] . identifier[PIPE] , identifier[stderr] = identifier[subprocess] . identifier[PIPE] ) identifier[p] . identifier[communicate] ( identifier[key] . identifier[encode] ( literal[string] )) identifier[p] . identifier[wait] () identifier[retcode] = identifier[p] . identifier[poll] () keyword[if] identifier[retcode] : keyword[raise] identifier[KeyInvalidError] () keyword[else] : identifier[_util] . identifier[check_call_] ( identifier[cmd] ) keyword[except] identifier[ImageMounterError] : keyword[del] identifier[volume] . identifier[_paths] [ literal[string] ] identifier[volume] . identifier[_free_loopback] () keyword[raise] keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[del] identifier[volume] . identifier[_paths] [ literal[string] ] identifier[volume] . identifier[_free_loopback] () keyword[raise] identifier[SubsystemError] ( identifier[e] ) identifier[size] = keyword[None] keyword[try] : identifier[result] = identifier[_util] . identifier[check_output_] ([ literal[string] , literal[string] , identifier[volume] . identifier[_paths] [ literal[string] ]]) keyword[for] identifier[l] keyword[in] identifier[result] . identifier[splitlines] (): keyword[if] literal[string] keyword[in] identifier[l] keyword[and] literal[string] keyword[not] keyword[in] identifier[l] : identifier[size] = identifier[int] ( identifier[l] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ). identifier[strip] ())* identifier[volume] . identifier[disk] . identifier[block_size] keyword[except] identifier[Exception] : keyword[pass] identifier[container] = identifier[volume] . identifier[volumes] . identifier[_make_single_subvolume] ( identifier[flag] = literal[string] , identifier[offset] = literal[int] , identifier[size] = identifier[size] ) identifier[container] . identifier[info] [ literal[string] ]= literal[string] keyword[return] identifier[container]
def mount(self, volume): """Command that is an alternative to the :func:`mount` command that opens a LUKS container. The opened volume is added to the subvolume set of this volume. Requires the user to enter the key manually. TODO: add support for :attr:`keys` :return: the Volume contained in the LUKS container, or None on failure. :raises NoLoopbackAvailableError: when no free loopback could be found :raises IncorrectFilesystemError: when this is not a LUKS volume :raises SubsystemError: when the underlying command fails """ # Open a loopback device volume._find_loopback() # Check if this is a LUKS device # noinspection PyBroadException try: _util.check_call_(['cryptsetup', 'isLuks', volume.loopback], stderr=subprocess.STDOUT) # depends on [control=['try'], data=[]] # ret = 0 if isLuks except Exception: logger.warning('Not a LUKS volume') # clean the loopback device, we want this method to be clean as possible # noinspection PyBroadException try: volume._free_loopback() # depends on [control=['try'], data=[]] except Exception: pass # depends on [control=['except'], data=[]] raise IncorrectFilesystemError() # depends on [control=['except'], data=[]] try: extra_args = [] key = None if volume.key: (t, v) = volume.key.split(':', 1) if t == 'p': # passphrase key = v # depends on [control=['if'], data=[]] elif t == 'f': # key-file extra_args = ['--key-file', v] # depends on [control=['if'], data=[]] elif t == 'm': # master-key-file extra_args = ['--master-key-file', v] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: logger.warning('No key material provided for %s', volume) # depends on [control=['try'], data=[]] except ValueError: logger.exception('Invalid key material provided (%s) for %s. Expecting [arg]:[value]', volume.key, volume) volume._free_loopback() raise ArgumentError() # depends on [control=['except'], data=[]] # Open the LUKS container volume._paths['luks'] = 'image_mounter_luks_' + str(random.randint(10000, 99999)) # noinspection PyBroadException try: cmd = ['cryptsetup', 'luksOpen', volume.loopback, volume._paths['luks']] cmd.extend(extra_args) if not volume.disk.read_write: cmd.insert(1, '-r') # depends on [control=['if'], data=[]] if key is not None: logger.debug('$ {0}'.format(' '.join(cmd))) # for py 3.2+, we could have used input=, but that doesn't exist in py2.7. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate(key.encode('utf-8')) p.wait() retcode = p.poll() if retcode: raise KeyInvalidError() # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['key']] else: _util.check_call_(cmd) # depends on [control=['try'], data=[]] except ImageMounterError: del volume._paths['luks'] volume._free_loopback() raise # depends on [control=['except'], data=[]] except Exception as e: del volume._paths['luks'] volume._free_loopback() raise SubsystemError(e) # depends on [control=['except'], data=['e']] size = None # noinspection PyBroadException try: result = _util.check_output_(['cryptsetup', 'status', volume._paths['luks']]) for l in result.splitlines(): if 'size:' in l and 'key' not in l: size = int(l.replace('size:', '').replace('sectors', '').strip()) * volume.disk.block_size # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['l']] # depends on [control=['try'], data=[]] except Exception: pass # depends on [control=['except'], data=[]] container = volume.volumes._make_single_subvolume(flag='alloc', offset=0, size=size) container.info['fsdescription'] = 'LUKS Volume' return container
def readline(self, timeout): """ Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads. """ buf = self.__remainder while not '\n' in buf: buf += self._read_timeout(timeout) n = buf.index('\n') self.__remainder = buf[n+1:] buf = buf[:n] if (len(buf) > 0) and (buf[-1] == '\r'): buf = buf[:-1] return buf
def function[readline, parameter[self, timeout]]: constant[ Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads. ] variable[buf] assign[=] name[self].__remainder while <ast.UnaryOp object at 0x7da20c6e7970> begin[:] <ast.AugAssign object at 0x7da20c6e5c90> variable[n] assign[=] call[name[buf].index, parameter[constant[ ]]] name[self].__remainder assign[=] call[name[buf]][<ast.Slice object at 0x7da20c6e7a60>] variable[buf] assign[=] call[name[buf]][<ast.Slice object at 0x7da1b0f51420>] if <ast.BoolOp object at 0x7da1b0f51f30> begin[:] variable[buf] assign[=] call[name[buf]][<ast.Slice object at 0x7da18f58df30>] return[name[buf]]
keyword[def] identifier[readline] ( identifier[self] , identifier[timeout] ): literal[string] identifier[buf] = identifier[self] . identifier[__remainder] keyword[while] keyword[not] literal[string] keyword[in] identifier[buf] : identifier[buf] += identifier[self] . identifier[_read_timeout] ( identifier[timeout] ) identifier[n] = identifier[buf] . identifier[index] ( literal[string] ) identifier[self] . identifier[__remainder] = identifier[buf] [ identifier[n] + literal[int] :] identifier[buf] = identifier[buf] [: identifier[n] ] keyword[if] ( identifier[len] ( identifier[buf] )> literal[int] ) keyword[and] ( identifier[buf] [- literal[int] ]== literal[string] ): identifier[buf] = identifier[buf] [:- literal[int] ] keyword[return] identifier[buf]
def readline(self, timeout): """ Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads. """ buf = self.__remainder while not '\n' in buf: buf += self._read_timeout(timeout) # depends on [control=['while'], data=[]] n = buf.index('\n') self.__remainder = buf[n + 1:] buf = buf[:n] if len(buf) > 0 and buf[-1] == '\r': buf = buf[:-1] # depends on [control=['if'], data=[]] return buf
def GetAttributes(self, urns, age=NEWEST_TIME): """Retrieves all the attributes for all the urns.""" urns = set([utils.SmartUnicode(u) for u in urns]) to_read = {urn: self._MakeCacheInvariant(urn, age) for urn in urns} # Urns not present in the cache we need to get from the database. if to_read: for subject, values in data_store.DB.MultiResolvePrefix( to_read, AFF4_PREFIXES, timestamp=self.ParseAgeSpecification(age), limit=None): # Ensure the values are sorted. values.sort(key=lambda x: x[-1], reverse=True) yield utils.SmartUnicode(subject), values
def function[GetAttributes, parameter[self, urns, age]]: constant[Retrieves all the attributes for all the urns.] variable[urns] assign[=] call[name[set], parameter[<ast.ListComp object at 0x7da1b23471f0>]] variable[to_read] assign[=] <ast.DictComp object at 0x7da1b2345120> if name[to_read] begin[:] for taget[tuple[[<ast.Name object at 0x7da1b23450c0>, <ast.Name object at 0x7da1b2346da0>]]] in starred[call[name[data_store].DB.MultiResolvePrefix, parameter[name[to_read], name[AFF4_PREFIXES]]]] begin[:] call[name[values].sort, parameter[]] <ast.Yield object at 0x7da1b2344fd0>
keyword[def] identifier[GetAttributes] ( identifier[self] , identifier[urns] , identifier[age] = identifier[NEWEST_TIME] ): literal[string] identifier[urns] = identifier[set] ([ identifier[utils] . identifier[SmartUnicode] ( identifier[u] ) keyword[for] identifier[u] keyword[in] identifier[urns] ]) identifier[to_read] ={ identifier[urn] : identifier[self] . identifier[_MakeCacheInvariant] ( identifier[urn] , identifier[age] ) keyword[for] identifier[urn] keyword[in] identifier[urns] } keyword[if] identifier[to_read] : keyword[for] identifier[subject] , identifier[values] keyword[in] identifier[data_store] . identifier[DB] . identifier[MultiResolvePrefix] ( identifier[to_read] , identifier[AFF4_PREFIXES] , identifier[timestamp] = identifier[self] . identifier[ParseAgeSpecification] ( identifier[age] ), identifier[limit] = keyword[None] ): identifier[values] . identifier[sort] ( identifier[key] = keyword[lambda] identifier[x] : identifier[x] [- literal[int] ], identifier[reverse] = keyword[True] ) keyword[yield] identifier[utils] . identifier[SmartUnicode] ( identifier[subject] ), identifier[values]
def GetAttributes(self, urns, age=NEWEST_TIME): """Retrieves all the attributes for all the urns.""" urns = set([utils.SmartUnicode(u) for u in urns]) to_read = {urn: self._MakeCacheInvariant(urn, age) for urn in urns} # Urns not present in the cache we need to get from the database. if to_read: for (subject, values) in data_store.DB.MultiResolvePrefix(to_read, AFF4_PREFIXES, timestamp=self.ParseAgeSpecification(age), limit=None): # Ensure the values are sorted. values.sort(key=lambda x: x[-1], reverse=True) yield (utils.SmartUnicode(subject), values) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
def register_agent(self, host, sweep_id=None, project_name=None): """Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep """ mutation = gql(''' mutation CreateAgent( $host: String! $projectName: String!, $entityName: String!, $sweep: String! ) { createAgent(input: { host: $host, projectName: $projectName, entityName: $entityName, sweep: $sweep, }) { agent { id } } } ''') if project_name is None: project_name = self.settings('project') # don't retry on validation errors def no_retry_400(e): if not isinstance(e, requests.HTTPError): return True if e.response.status_code != 400: return True body = json.loads(e.response.content) raise UsageError(body['errors'][0]['message']) response = self.gql(mutation, variable_values={ 'host': host, 'entityName': self.settings("entity"), 'projectName': project_name, 'sweep': sweep_id}, check_retry_fn=no_retry_400) return response['createAgent']['agent']
def function[register_agent, parameter[self, host, sweep_id, project_name]]: constant[Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep ] variable[mutation] assign[=] call[name[gql], parameter[constant[ mutation CreateAgent( $host: String! $projectName: String!, $entityName: String!, $sweep: String! ) { createAgent(input: { host: $host, projectName: $projectName, entityName: $entityName, sweep: $sweep, }) { agent { id } } } ]]] if compare[name[project_name] is constant[None]] begin[:] variable[project_name] assign[=] call[name[self].settings, parameter[constant[project]]] def function[no_retry_400, parameter[e]]: if <ast.UnaryOp object at 0x7da1b26ad000> begin[:] return[constant[True]] if compare[name[e].response.status_code not_equal[!=] constant[400]] begin[:] return[constant[True]] variable[body] assign[=] call[name[json].loads, parameter[name[e].response.content]] <ast.Raise object at 0x7da204564760> variable[response] assign[=] call[name[self].gql, parameter[name[mutation]]] return[call[call[name[response]][constant[createAgent]]][constant[agent]]]
keyword[def] identifier[register_agent] ( identifier[self] , identifier[host] , identifier[sweep_id] = keyword[None] , identifier[project_name] = keyword[None] ): literal[string] identifier[mutation] = identifier[gql] ( literal[string] ) keyword[if] identifier[project_name] keyword[is] keyword[None] : identifier[project_name] = identifier[self] . identifier[settings] ( literal[string] ) keyword[def] identifier[no_retry_400] ( identifier[e] ): keyword[if] keyword[not] identifier[isinstance] ( identifier[e] , identifier[requests] . identifier[HTTPError] ): keyword[return] keyword[True] keyword[if] identifier[e] . identifier[response] . identifier[status_code] != literal[int] : keyword[return] keyword[True] identifier[body] = identifier[json] . identifier[loads] ( identifier[e] . identifier[response] . identifier[content] ) keyword[raise] identifier[UsageError] ( identifier[body] [ literal[string] ][ literal[int] ][ literal[string] ]) identifier[response] = identifier[self] . identifier[gql] ( identifier[mutation] , identifier[variable_values] ={ literal[string] : identifier[host] , literal[string] : identifier[self] . identifier[settings] ( literal[string] ), literal[string] : identifier[project_name] , literal[string] : identifier[sweep_id] }, identifier[check_retry_fn] = identifier[no_retry_400] ) keyword[return] identifier[response] [ literal[string] ][ literal[string] ]
def register_agent(self, host, sweep_id=None, project_name=None): """Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep """ mutation = gql('\n mutation CreateAgent(\n $host: String!\n $projectName: String!,\n $entityName: String!,\n $sweep: String!\n ) {\n createAgent(input: {\n host: $host,\n projectName: $projectName,\n entityName: $entityName,\n sweep: $sweep,\n }) {\n agent {\n id\n }\n }\n }\n ') if project_name is None: project_name = self.settings('project') # depends on [control=['if'], data=['project_name']] # don't retry on validation errors def no_retry_400(e): if not isinstance(e, requests.HTTPError): return True # depends on [control=['if'], data=[]] if e.response.status_code != 400: return True # depends on [control=['if'], data=[]] body = json.loads(e.response.content) raise UsageError(body['errors'][0]['message']) response = self.gql(mutation, variable_values={'host': host, 'entityName': self.settings('entity'), 'projectName': project_name, 'sweep': sweep_id}, check_retry_fn=no_retry_400) return response['createAgent']['agent']
def make_view(robot): """ 为一个 BaseRoBot 生成 Flask view。 Usage :: from werobot import WeRoBot robot = WeRoBot(token='token') @robot.handler def hello(message): return 'Hello World!' from flask import Flask from werobot.contrib.flask import make_view app = Flask(__name__) app.add_url_rule(rule='/robot/', # WeRoBot 的绑定地址 endpoint='werobot', # Flask 的 endpoint view_func=make_view(robot), methods=['GET', 'POST']) :param robot: 一个 BaseRoBot 实例 :return: 一个标准的 Flask view """ def werobot_view(): timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') signature = request.args.get('signature', '') if not robot.check_signature( timestamp, nonce, signature, ): return robot.make_error_page(html.escape(request.url)), 403 if request.method == 'GET': return request.args['echostr'] message = robot.parse_message( request.data, timestamp=timestamp, nonce=nonce, msg_signature=request.args.get('msg_signature', '') ) response = make_response(robot.get_encrypted_reply(message)) response.headers['content_type'] = 'application/xml' return response return werobot_view
def function[make_view, parameter[robot]]: constant[ 为一个 BaseRoBot 生成 Flask view。 Usage :: from werobot import WeRoBot robot = WeRoBot(token='token') @robot.handler def hello(message): return 'Hello World!' from flask import Flask from werobot.contrib.flask import make_view app = Flask(__name__) app.add_url_rule(rule='/robot/', # WeRoBot 的绑定地址 endpoint='werobot', # Flask 的 endpoint view_func=make_view(robot), methods=['GET', 'POST']) :param robot: 一个 BaseRoBot 实例 :return: 一个标准的 Flask view ] def function[werobot_view, parameter[]]: variable[timestamp] assign[=] call[name[request].args.get, parameter[constant[timestamp], constant[]]] variable[nonce] assign[=] call[name[request].args.get, parameter[constant[nonce], constant[]]] variable[signature] assign[=] call[name[request].args.get, parameter[constant[signature], constant[]]] if <ast.UnaryOp object at 0x7da1b2189cf0> begin[:] return[tuple[[<ast.Call object at 0x7da1b21898d0>, <ast.Constant object at 0x7da1b2189480>]]] if compare[name[request].method equal[==] constant[GET]] begin[:] return[call[name[request].args][constant[echostr]]] variable[message] assign[=] call[name[robot].parse_message, parameter[name[request].data]] variable[response] assign[=] call[name[make_response], parameter[call[name[robot].get_encrypted_reply, parameter[name[message]]]]] call[name[response].headers][constant[content_type]] assign[=] constant[application/xml] return[name[response]] return[name[werobot_view]]
keyword[def] identifier[make_view] ( identifier[robot] ): literal[string] keyword[def] identifier[werobot_view] (): identifier[timestamp] = identifier[request] . identifier[args] . identifier[get] ( literal[string] , literal[string] ) identifier[nonce] = identifier[request] . identifier[args] . identifier[get] ( literal[string] , literal[string] ) identifier[signature] = identifier[request] . identifier[args] . identifier[get] ( literal[string] , literal[string] ) keyword[if] keyword[not] identifier[robot] . identifier[check_signature] ( identifier[timestamp] , identifier[nonce] , identifier[signature] , ): keyword[return] identifier[robot] . identifier[make_error_page] ( identifier[html] . identifier[escape] ( identifier[request] . identifier[url] )), literal[int] keyword[if] identifier[request] . identifier[method] == literal[string] : keyword[return] identifier[request] . identifier[args] [ literal[string] ] identifier[message] = identifier[robot] . identifier[parse_message] ( identifier[request] . identifier[data] , identifier[timestamp] = identifier[timestamp] , identifier[nonce] = identifier[nonce] , identifier[msg_signature] = identifier[request] . identifier[args] . identifier[get] ( literal[string] , literal[string] ) ) identifier[response] = identifier[make_response] ( identifier[robot] . identifier[get_encrypted_reply] ( identifier[message] )) identifier[response] . identifier[headers] [ literal[string] ]= literal[string] keyword[return] identifier[response] keyword[return] identifier[werobot_view]
def make_view(robot): """ 为一个 BaseRoBot 生成 Flask view。 Usage :: from werobot import WeRoBot robot = WeRoBot(token='token') @robot.handler def hello(message): return 'Hello World!' from flask import Flask from werobot.contrib.flask import make_view app = Flask(__name__) app.add_url_rule(rule='/robot/', # WeRoBot 的绑定地址 endpoint='werobot', # Flask 的 endpoint view_func=make_view(robot), methods=['GET', 'POST']) :param robot: 一个 BaseRoBot 实例 :return: 一个标准的 Flask view """ def werobot_view(): timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') signature = request.args.get('signature', '') if not robot.check_signature(timestamp, nonce, signature): return (robot.make_error_page(html.escape(request.url)), 403) # depends on [control=['if'], data=[]] if request.method == 'GET': return request.args['echostr'] # depends on [control=['if'], data=[]] message = robot.parse_message(request.data, timestamp=timestamp, nonce=nonce, msg_signature=request.args.get('msg_signature', '')) response = make_response(robot.get_encrypted_reply(message)) response.headers['content_type'] = 'application/xml' return response return werobot_view
def fixpairs(args): """ %prog fixpairs pairsfile sep sd Fix pairs library stats. This is sometime useful to modify library stats, for example, the separation between paired reads after importing the data. """ p = OptionParser(fixpairs.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) pairsfile, sep, sd = args newpairsfile = pairsfile.rsplit(".", 1)[0] + ".new.pairs" sep = int(sep) sd = int(sd) p = PairsFile(pairsfile) p.fixLibraryStats(sep, sd) p.write(newpairsfile)
def function[fixpairs, parameter[args]]: constant[ %prog fixpairs pairsfile sep sd Fix pairs library stats. This is sometime useful to modify library stats, for example, the separation between paired reads after importing the data. ] variable[p] assign[=] call[name[OptionParser], parameter[name[fixpairs].__doc__]] <ast.Tuple object at 0x7da1b09bd300> assign[=] call[name[p].parse_args, parameter[name[args]]] if compare[call[name[len], parameter[name[args]]] not_equal[!=] constant[3]] begin[:] call[name[sys].exit, parameter[<ast.UnaryOp object at 0x7da1b09bf4c0>]] <ast.Tuple object at 0x7da1b09bf670> assign[=] name[args] variable[newpairsfile] assign[=] binary_operation[call[call[name[pairsfile].rsplit, parameter[constant[.], constant[1]]]][constant[0]] + constant[.new.pairs]] variable[sep] assign[=] call[name[int], parameter[name[sep]]] variable[sd] assign[=] call[name[int], parameter[name[sd]]] variable[p] assign[=] call[name[PairsFile], parameter[name[pairsfile]]] call[name[p].fixLibraryStats, parameter[name[sep], name[sd]]] call[name[p].write, parameter[name[newpairsfile]]]
keyword[def] identifier[fixpairs] ( identifier[args] ): literal[string] identifier[p] = identifier[OptionParser] ( identifier[fixpairs] . identifier[__doc__] ) identifier[opts] , identifier[args] = identifier[p] . identifier[parse_args] ( identifier[args] ) keyword[if] identifier[len] ( identifier[args] )!= literal[int] : identifier[sys] . identifier[exit] ( keyword[not] identifier[p] . identifier[print_help] ()) identifier[pairsfile] , identifier[sep] , identifier[sd] = identifier[args] identifier[newpairsfile] = identifier[pairsfile] . identifier[rsplit] ( literal[string] , literal[int] )[ literal[int] ]+ literal[string] identifier[sep] = identifier[int] ( identifier[sep] ) identifier[sd] = identifier[int] ( identifier[sd] ) identifier[p] = identifier[PairsFile] ( identifier[pairsfile] ) identifier[p] . identifier[fixLibraryStats] ( identifier[sep] , identifier[sd] ) identifier[p] . identifier[write] ( identifier[newpairsfile] )
def fixpairs(args): """ %prog fixpairs pairsfile sep sd Fix pairs library stats. This is sometime useful to modify library stats, for example, the separation between paired reads after importing the data. """ p = OptionParser(fixpairs.__doc__) (opts, args) = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) # depends on [control=['if'], data=[]] (pairsfile, sep, sd) = args newpairsfile = pairsfile.rsplit('.', 1)[0] + '.new.pairs' sep = int(sep) sd = int(sd) p = PairsFile(pairsfile) p.fixLibraryStats(sep, sd) p.write(newpairsfile)
def slim_stem(token): """ A very simple stemmer, for entity of GO stemming. >>> token = 'interaction' >>> slim_stem(token) 'interact' """ target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment'] for sulfix in sorted(target_sulfixs, key=len, reverse=True): if token.endswith(sulfix): token = token[0:-len(sulfix)] break if token.endswith('ll'): token = token[:-1] return token
def function[slim_stem, parameter[token]]: constant[ A very simple stemmer, for entity of GO stemming. >>> token = 'interaction' >>> slim_stem(token) 'interact' ] variable[target_sulfixs] assign[=] list[[<ast.Constant object at 0x7da18eb57910>, <ast.Constant object at 0x7da18eb55e70>, <ast.Constant object at 0x7da18eb55a20>, <ast.Constant object at 0x7da18eb54370>, <ast.Constant object at 0x7da18eb579d0>, <ast.Constant object at 0x7da18eb57b80>, <ast.Constant object at 0x7da18eb56590>, <ast.Constant object at 0x7da18eb55f60>, <ast.Constant object at 0x7da18eb57bb0>, <ast.Constant object at 0x7da18eb57520>, <ast.Constant object at 0x7da18eb57970>, <ast.Constant object at 0x7da18eb55120>, <ast.Constant object at 0x7da18eb57d30>, <ast.Constant object at 0x7da18eb54820>, <ast.Constant object at 0x7da18eb560b0>]] for taget[name[sulfix]] in starred[call[name[sorted], parameter[name[target_sulfixs]]]] begin[:] if call[name[token].endswith, parameter[name[sulfix]]] begin[:] variable[token] assign[=] call[name[token]][<ast.Slice object at 0x7da18eb557b0>] break if call[name[token].endswith, parameter[constant[ll]]] begin[:] variable[token] assign[=] call[name[token]][<ast.Slice object at 0x7da18eb549d0>] return[name[token]]
keyword[def] identifier[slim_stem] ( identifier[token] ): literal[string] identifier[target_sulfixs] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ] keyword[for] identifier[sulfix] keyword[in] identifier[sorted] ( identifier[target_sulfixs] , identifier[key] = identifier[len] , identifier[reverse] = keyword[True] ): keyword[if] identifier[token] . identifier[endswith] ( identifier[sulfix] ): identifier[token] = identifier[token] [ literal[int] :- identifier[len] ( identifier[sulfix] )] keyword[break] keyword[if] identifier[token] . identifier[endswith] ( literal[string] ): identifier[token] = identifier[token] [:- literal[int] ] keyword[return] identifier[token]
def slim_stem(token): """ A very simple stemmer, for entity of GO stemming. >>> token = 'interaction' >>> slim_stem(token) 'interact' """ target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment'] for sulfix in sorted(target_sulfixs, key=len, reverse=True): if token.endswith(sulfix): token = token[0:-len(sulfix)] break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['sulfix']] if token.endswith('ll'): token = token[:-1] # depends on [control=['if'], data=[]] return token
def Wp(self): """Total energy in protons above 1.22 GeV threshold (erg). """ from scipy.integrate import quad Eth = 1.22e-3 with warnings.catch_warnings(): warnings.simplefilter("ignore") Wp = quad( lambda x: x * self._particle_distribution(x), Eth, np.Inf )[0] return (Wp * u.TeV).to("erg")
def function[Wp, parameter[self]]: constant[Total energy in protons above 1.22 GeV threshold (erg). ] from relative_module[scipy.integrate] import module[quad] variable[Eth] assign[=] constant[0.00122] with call[name[warnings].catch_warnings, parameter[]] begin[:] call[name[warnings].simplefilter, parameter[constant[ignore]]] variable[Wp] assign[=] call[call[name[quad], parameter[<ast.Lambda object at 0x7da1b0b95900>, name[Eth], name[np].Inf]]][constant[0]] return[call[binary_operation[name[Wp] * name[u].TeV].to, parameter[constant[erg]]]]
keyword[def] identifier[Wp] ( identifier[self] ): literal[string] keyword[from] identifier[scipy] . identifier[integrate] keyword[import] identifier[quad] identifier[Eth] = literal[int] keyword[with] identifier[warnings] . identifier[catch_warnings] (): identifier[warnings] . identifier[simplefilter] ( literal[string] ) identifier[Wp] = identifier[quad] ( keyword[lambda] identifier[x] : identifier[x] * identifier[self] . identifier[_particle_distribution] ( identifier[x] ), identifier[Eth] , identifier[np] . identifier[Inf] )[ literal[int] ] keyword[return] ( identifier[Wp] * identifier[u] . identifier[TeV] ). identifier[to] ( literal[string] )
def Wp(self): """Total energy in protons above 1.22 GeV threshold (erg). """ from scipy.integrate import quad Eth = 0.00122 with warnings.catch_warnings(): warnings.simplefilter('ignore') Wp = quad(lambda x: x * self._particle_distribution(x), Eth, np.Inf)[0] # depends on [control=['with'], data=[]] return (Wp * u.TeV).to('erg')
def consume(self, queue, consumer, consumer_tag='', no_local=False, no_ack=True, exclusive=False, nowait=True, ticket=None, cb=None, cancel_cb=None): '''Start a queue consumer. Accepts the following optional arg in addition to those of `BasicClass.consume()`: :param cancel_cb: a callable to be called when the broker cancels the consumer; e.g., when the consumer's queue is deleted. See www.rabbitmq.com/consumer-cancel.html. :type cancel_cb: None or callable with signature cancel_cb(consumer_tag) ''' # Register the consumer's broker-cancel callback entry if cancel_cb is not None: if not callable(cancel_cb): raise ValueError('cancel_cb is not callable: %r' % (cancel_cb,)) if not consumer_tag: consumer_tag = self._generate_consumer_tag() self._broker_cancel_cb_map[consumer_tag] = cancel_cb # Start consumer super(RabbitBasicClass, self).consume(queue, consumer, consumer_tag, no_local, no_ack, exclusive, nowait, ticket, cb)
def function[consume, parameter[self, queue, consumer, consumer_tag, no_local, no_ack, exclusive, nowait, ticket, cb, cancel_cb]]: constant[Start a queue consumer. Accepts the following optional arg in addition to those of `BasicClass.consume()`: :param cancel_cb: a callable to be called when the broker cancels the consumer; e.g., when the consumer's queue is deleted. See www.rabbitmq.com/consumer-cancel.html. :type cancel_cb: None or callable with signature cancel_cb(consumer_tag) ] if compare[name[cancel_cb] is_not constant[None]] begin[:] if <ast.UnaryOp object at 0x7da1b069c310> begin[:] <ast.Raise object at 0x7da1b06986a0> if <ast.UnaryOp object at 0x7da1b0698730> begin[:] variable[consumer_tag] assign[=] call[name[self]._generate_consumer_tag, parameter[]] call[name[self]._broker_cancel_cb_map][name[consumer_tag]] assign[=] name[cancel_cb] call[call[name[super], parameter[name[RabbitBasicClass], name[self]]].consume, parameter[name[queue], name[consumer], name[consumer_tag], name[no_local], name[no_ack], name[exclusive], name[nowait], name[ticket], name[cb]]]
keyword[def] identifier[consume] ( identifier[self] , identifier[queue] , identifier[consumer] , identifier[consumer_tag] = literal[string] , identifier[no_local] = keyword[False] , identifier[no_ack] = keyword[True] , identifier[exclusive] = keyword[False] , identifier[nowait] = keyword[True] , identifier[ticket] = keyword[None] , identifier[cb] = keyword[None] , identifier[cancel_cb] = keyword[None] ): literal[string] keyword[if] identifier[cancel_cb] keyword[is] keyword[not] keyword[None] : keyword[if] keyword[not] identifier[callable] ( identifier[cancel_cb] ): keyword[raise] identifier[ValueError] ( literal[string] %( identifier[cancel_cb] ,)) keyword[if] keyword[not] identifier[consumer_tag] : identifier[consumer_tag] = identifier[self] . identifier[_generate_consumer_tag] () identifier[self] . identifier[_broker_cancel_cb_map] [ identifier[consumer_tag] ]= identifier[cancel_cb] identifier[super] ( identifier[RabbitBasicClass] , identifier[self] ). identifier[consume] ( identifier[queue] , identifier[consumer] , identifier[consumer_tag] , identifier[no_local] , identifier[no_ack] , identifier[exclusive] , identifier[nowait] , identifier[ticket] , identifier[cb] )
def consume(self, queue, consumer, consumer_tag='', no_local=False, no_ack=True, exclusive=False, nowait=True, ticket=None, cb=None, cancel_cb=None): """Start a queue consumer. Accepts the following optional arg in addition to those of `BasicClass.consume()`: :param cancel_cb: a callable to be called when the broker cancels the consumer; e.g., when the consumer's queue is deleted. See www.rabbitmq.com/consumer-cancel.html. :type cancel_cb: None or callable with signature cancel_cb(consumer_tag) """ # Register the consumer's broker-cancel callback entry if cancel_cb is not None: if not callable(cancel_cb): raise ValueError('cancel_cb is not callable: %r' % (cancel_cb,)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['cancel_cb']] if not consumer_tag: consumer_tag = self._generate_consumer_tag() # depends on [control=['if'], data=[]] self._broker_cancel_cb_map[consumer_tag] = cancel_cb # Start consumer super(RabbitBasicClass, self).consume(queue, consumer, consumer_tag, no_local, no_ack, exclusive, nowait, ticket, cb)
def cluster_motifs(motifs, match="total", metric="wic", combine="mean", pval=True, threshold=0.95, trim_edges=False, edge_ic_cutoff=0.2, include_bg=True, progress=True, ncpus=None): """ Clusters a set of sequence motifs. Required arg 'motifs' is a file containing positional frequency matrices or an array with motifs. Optional args: 'match', 'metric' and 'combine' specify the method used to compare and score the motifs. By default the WIC score is used (metric='wic'), using the the score over the whole alignment (match='total'), with the total motif score calculated as the mean score of all positions (combine='mean'). 'match' can be either 'total' for the total alignment or 'subtotal' for the maximum scoring subsequence of the alignment. 'metric' can be any metric defined in MotifComparer, currently: 'pcc', 'ed', 'distance', 'wic' or 'chisq' 'combine' determines how the total score is calculated from the score of individual positions and can be either 'sum' or 'mean' 'pval' can be True or False and determines if the score should be converted to an empirical p-value 'threshold' determines the score (or p-value) cutoff If 'trim_edges' is set to True, all motif edges with an IC below 'edge_ic_cutoff' will be removed before clustering When computing the average of two motifs 'include_bg' determines if, at a position only present in one motif, the information in that motif should be kept, or if it should be averaged with background frequencies. Should probably be left set to True. """ # First read pfm or pfm formatted motiffile if type([]) != type(motifs): motifs = read_motifs(motifs, fmt="pwm") mc = MotifComparer() # Trim edges with low information content if trim_edges: for motif in motifs: motif.trim(edge_ic_cutoff) # Make a MotifTree node for every motif nodes = [MotifTree(m) for m in motifs] # Determine all pairwise scores and maxscore per motif scores = {} motif_nodes = dict([(n.motif.id,n) for n in nodes]) motifs = [n.motif for n in nodes] if progress: sys.stderr.write("Calculating initial scores\n") result = mc.get_all_scores(motifs, motifs, match, metric, combine, pval, parallel=True, ncpus=ncpus) for m1, other_motifs in result.items(): for m2, score in other_motifs.items(): if m1 == m2: if pval: motif_nodes[m1].maxscore = 1 - score[0] else: motif_nodes[m1].maxscore = score[0] else: if pval: score = [1 - score[0]] + score[1:] scores[(motif_nodes[m1],motif_nodes[m2])] = score cluster_nodes = [node for node in nodes] ave_count = 1 total = len(cluster_nodes) while len(cluster_nodes) > 1: l = sorted(scores.keys(), key=lambda x: scores[x][0]) i = -1 (n1, n2) = l[i] while n1 not in cluster_nodes or n2 not in cluster_nodes: i -= 1 (n1,n2) = l[i] if len(n1.motif) > 0 and len(n2.motif) > 0: (score, pos, orientation) = scores[(n1,n2)] ave_motif = n1.motif.average_motifs(n2.motif, pos, orientation, include_bg=include_bg) ave_motif.trim(edge_ic_cutoff) # Check if the motif is not empty if len(ave_motif) == 0: ave_motif = Motif([[0.25,0.25,0.25,0.25]]) ave_motif.id = "Average_%s" % ave_count ave_count += 1 new_node = MotifTree(ave_motif) if pval: new_node.maxscore = 1 - mc.compare_motifs(new_node.motif, new_node.motif, match, metric, combine, pval)[0] else: new_node.maxscore = mc.compare_motifs(new_node.motif, new_node.motif, match, metric, combine, pval)[0] new_node.mergescore = score #print "%s + %s = %s with score %s" % (n1.motif.id, n2.motif.id, ave_motif.id, score) n1.parent = new_node n2.parent = new_node new_node.left = n1 new_node.right = n2 cmp_nodes = dict([(node.motif, node) for node in nodes if not node.parent]) if progress: progress = (1 - len(cmp_nodes) / float(total)) * 100 sys.stderr.write('\rClustering [{0}{1}] {2}%'.format( '#' * (int(progress) // 10), " " * (10 - int(progress) // 10), int(progress))) result = mc.get_all_scores( [new_node.motif], list(cmp_nodes.keys()), match, metric, combine, pval, parallel=True) for motif, n in cmp_nodes.items(): x = result[new_node.motif.id][motif.id] if pval: x = [1 - x[0]] + x[1:] scores[(new_node, n)] = x nodes.append(new_node) cluster_nodes = [node for node in nodes if not node.parent] if progress: sys.stderr.write("\n") root = nodes[-1] for node in [node for node in nodes if not node.left]: node.parent.checkMerge(root, threshold) return root
def function[cluster_motifs, parameter[motifs, match, metric, combine, pval, threshold, trim_edges, edge_ic_cutoff, include_bg, progress, ncpus]]: constant[ Clusters a set of sequence motifs. Required arg 'motifs' is a file containing positional frequency matrices or an array with motifs. Optional args: 'match', 'metric' and 'combine' specify the method used to compare and score the motifs. By default the WIC score is used (metric='wic'), using the the score over the whole alignment (match='total'), with the total motif score calculated as the mean score of all positions (combine='mean'). 'match' can be either 'total' for the total alignment or 'subtotal' for the maximum scoring subsequence of the alignment. 'metric' can be any metric defined in MotifComparer, currently: 'pcc', 'ed', 'distance', 'wic' or 'chisq' 'combine' determines how the total score is calculated from the score of individual positions and can be either 'sum' or 'mean' 'pval' can be True or False and determines if the score should be converted to an empirical p-value 'threshold' determines the score (or p-value) cutoff If 'trim_edges' is set to True, all motif edges with an IC below 'edge_ic_cutoff' will be removed before clustering When computing the average of two motifs 'include_bg' determines if, at a position only present in one motif, the information in that motif should be kept, or if it should be averaged with background frequencies. Should probably be left set to True. ] if compare[call[name[type], parameter[list[[]]]] not_equal[!=] call[name[type], parameter[name[motifs]]]] begin[:] variable[motifs] assign[=] call[name[read_motifs], parameter[name[motifs]]] variable[mc] assign[=] call[name[MotifComparer], parameter[]] if name[trim_edges] begin[:] for taget[name[motif]] in starred[name[motifs]] begin[:] call[name[motif].trim, parameter[name[edge_ic_cutoff]]] variable[nodes] assign[=] <ast.ListComp object at 0x7da2054a4d60> variable[scores] assign[=] dictionary[[], []] variable[motif_nodes] assign[=] call[name[dict], parameter[<ast.ListComp object at 0x7da2054a49d0>]] variable[motifs] assign[=] <ast.ListComp object at 0x7da2054a6170> if name[progress] begin[:] call[name[sys].stderr.write, parameter[constant[Calculating initial scores ]]] variable[result] assign[=] call[name[mc].get_all_scores, parameter[name[motifs], name[motifs], name[match], name[metric], name[combine], name[pval]]] for taget[tuple[[<ast.Name object at 0x7da2054a4190>, <ast.Name object at 0x7da2054a5f90>]]] in starred[call[name[result].items, parameter[]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da2054a57b0>, <ast.Name object at 0x7da2054a53f0>]]] in starred[call[name[other_motifs].items, parameter[]]] begin[:] if compare[name[m1] equal[==] name[m2]] begin[:] if name[pval] begin[:] call[name[motif_nodes]][name[m1]].maxscore assign[=] binary_operation[constant[1] - call[name[score]][constant[0]]] variable[cluster_nodes] assign[=] <ast.ListComp object at 0x7da2054a50c0> variable[ave_count] assign[=] constant[1] variable[total] assign[=] call[name[len], parameter[name[cluster_nodes]]] while compare[call[name[len], parameter[name[cluster_nodes]]] greater[>] constant[1]] begin[:] variable[l] assign[=] call[name[sorted], parameter[call[name[scores].keys, parameter[]]]] variable[i] assign[=] <ast.UnaryOp object at 0x7da1b10b1720> <ast.Tuple object at 0x7da1b10b27a0> assign[=] call[name[l]][name[i]] while <ast.BoolOp object at 0x7da1b10b1ff0> begin[:] <ast.AugAssign object at 0x7da1b10b05e0> <ast.Tuple object at 0x7da1b10b2320> assign[=] call[name[l]][name[i]] if <ast.BoolOp object at 0x7da1b10b2290> begin[:] <ast.Tuple object at 0x7da1b10b14b0> assign[=] call[name[scores]][tuple[[<ast.Name object at 0x7da1b10b2080>, <ast.Name object at 0x7da1b10b1270>]]] variable[ave_motif] assign[=] call[name[n1].motif.average_motifs, parameter[name[n2].motif, name[pos], name[orientation]]] call[name[ave_motif].trim, parameter[name[edge_ic_cutoff]]] if compare[call[name[len], parameter[name[ave_motif]]] equal[==] constant[0]] begin[:] variable[ave_motif] assign[=] call[name[Motif], parameter[list[[<ast.List object at 0x7da1b10b2a10>]]]] name[ave_motif].id assign[=] binary_operation[constant[Average_%s] <ast.Mod object at 0x7da2590d6920> name[ave_count]] <ast.AugAssign object at 0x7da1b10b0220> variable[new_node] assign[=] call[name[MotifTree], parameter[name[ave_motif]]] if name[pval] begin[:] name[new_node].maxscore assign[=] binary_operation[constant[1] - call[call[name[mc].compare_motifs, parameter[name[new_node].motif, name[new_node].motif, name[match], name[metric], name[combine], name[pval]]]][constant[0]]] name[new_node].mergescore assign[=] name[score] name[n1].parent assign[=] name[new_node] name[n2].parent assign[=] name[new_node] name[new_node].left assign[=] name[n1] name[new_node].right assign[=] name[n2] variable[cmp_nodes] assign[=] call[name[dict], parameter[<ast.ListComp object at 0x7da1b10b1db0>]] if name[progress] begin[:] variable[progress] assign[=] binary_operation[binary_operation[constant[1] - binary_operation[call[name[len], parameter[name[cmp_nodes]]] / call[name[float], parameter[name[total]]]]] * constant[100]] call[name[sys].stderr.write, parameter[call[constant[ Clustering [{0}{1}] {2}%].format, parameter[binary_operation[constant[#] * binary_operation[call[name[int], parameter[name[progress]]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[10]]], binary_operation[constant[ ] * binary_operation[constant[10] - binary_operation[call[name[int], parameter[name[progress]]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[10]]]], call[name[int], parameter[name[progress]]]]]]] variable[result] assign[=] call[name[mc].get_all_scores, parameter[list[[<ast.Attribute object at 0x7da1b10a7310>]], call[name[list], parameter[call[name[cmp_nodes].keys, parameter[]]]], name[match], name[metric], name[combine], name[pval]]] for taget[tuple[[<ast.Name object at 0x7da1b10a6c20>, <ast.Name object at 0x7da1b10a77c0>]]] in starred[call[name[cmp_nodes].items, parameter[]]] begin[:] variable[x] assign[=] call[call[name[result]][name[new_node].motif.id]][name[motif].id] if name[pval] begin[:] variable[x] assign[=] binary_operation[list[[<ast.BinOp object at 0x7da1b10a50f0>]] + call[name[x]][<ast.Slice object at 0x7da1b10a57e0>]] call[name[scores]][tuple[[<ast.Name object at 0x7da1b10a6260>, <ast.Name object at 0x7da1b10a4f70>]]] assign[=] name[x] call[name[nodes].append, parameter[name[new_node]]] variable[cluster_nodes] assign[=] <ast.ListComp object at 0x7da1b10a4160> if name[progress] begin[:] call[name[sys].stderr.write, parameter[constant[ ]]] variable[root] assign[=] call[name[nodes]][<ast.UnaryOp object at 0x7da1b10a76a0>] for taget[name[node]] in starred[<ast.ListComp object at 0x7da1b10a4640>] begin[:] call[name[node].parent.checkMerge, parameter[name[root], name[threshold]]] return[name[root]]
keyword[def] identifier[cluster_motifs] ( identifier[motifs] , identifier[match] = literal[string] , identifier[metric] = literal[string] , identifier[combine] = literal[string] , identifier[pval] = keyword[True] , identifier[threshold] = literal[int] , identifier[trim_edges] = keyword[False] , identifier[edge_ic_cutoff] = literal[int] , identifier[include_bg] = keyword[True] , identifier[progress] = keyword[True] , identifier[ncpus] = keyword[None] ): literal[string] keyword[if] identifier[type] ([])!= identifier[type] ( identifier[motifs] ): identifier[motifs] = identifier[read_motifs] ( identifier[motifs] , identifier[fmt] = literal[string] ) identifier[mc] = identifier[MotifComparer] () keyword[if] identifier[trim_edges] : keyword[for] identifier[motif] keyword[in] identifier[motifs] : identifier[motif] . identifier[trim] ( identifier[edge_ic_cutoff] ) identifier[nodes] =[ identifier[MotifTree] ( identifier[m] ) keyword[for] identifier[m] keyword[in] identifier[motifs] ] identifier[scores] ={} identifier[motif_nodes] = identifier[dict] ([( identifier[n] . identifier[motif] . identifier[id] , identifier[n] ) keyword[for] identifier[n] keyword[in] identifier[nodes] ]) identifier[motifs] =[ identifier[n] . identifier[motif] keyword[for] identifier[n] keyword[in] identifier[nodes] ] keyword[if] identifier[progress] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[result] = identifier[mc] . identifier[get_all_scores] ( identifier[motifs] , identifier[motifs] , identifier[match] , identifier[metric] , identifier[combine] , identifier[pval] , identifier[parallel] = keyword[True] , identifier[ncpus] = identifier[ncpus] ) keyword[for] identifier[m1] , identifier[other_motifs] keyword[in] identifier[result] . identifier[items] (): keyword[for] identifier[m2] , identifier[score] keyword[in] identifier[other_motifs] . identifier[items] (): keyword[if] identifier[m1] == identifier[m2] : keyword[if] identifier[pval] : identifier[motif_nodes] [ identifier[m1] ]. identifier[maxscore] = literal[int] - identifier[score] [ literal[int] ] keyword[else] : identifier[motif_nodes] [ identifier[m1] ]. identifier[maxscore] = identifier[score] [ literal[int] ] keyword[else] : keyword[if] identifier[pval] : identifier[score] =[ literal[int] - identifier[score] [ literal[int] ]]+ identifier[score] [ literal[int] :] identifier[scores] [( identifier[motif_nodes] [ identifier[m1] ], identifier[motif_nodes] [ identifier[m2] ])]= identifier[score] identifier[cluster_nodes] =[ identifier[node] keyword[for] identifier[node] keyword[in] identifier[nodes] ] identifier[ave_count] = literal[int] identifier[total] = identifier[len] ( identifier[cluster_nodes] ) keyword[while] identifier[len] ( identifier[cluster_nodes] )> literal[int] : identifier[l] = identifier[sorted] ( identifier[scores] . identifier[keys] (), identifier[key] = keyword[lambda] identifier[x] : identifier[scores] [ identifier[x] ][ literal[int] ]) identifier[i] =- literal[int] ( identifier[n1] , identifier[n2] )= identifier[l] [ identifier[i] ] keyword[while] identifier[n1] keyword[not] keyword[in] identifier[cluster_nodes] keyword[or] identifier[n2] keyword[not] keyword[in] identifier[cluster_nodes] : identifier[i] -= literal[int] ( identifier[n1] , identifier[n2] )= identifier[l] [ identifier[i] ] keyword[if] identifier[len] ( identifier[n1] . identifier[motif] )> literal[int] keyword[and] identifier[len] ( identifier[n2] . identifier[motif] )> literal[int] : ( identifier[score] , identifier[pos] , identifier[orientation] )= identifier[scores] [( identifier[n1] , identifier[n2] )] identifier[ave_motif] = identifier[n1] . identifier[motif] . identifier[average_motifs] ( identifier[n2] . identifier[motif] , identifier[pos] , identifier[orientation] , identifier[include_bg] = identifier[include_bg] ) identifier[ave_motif] . identifier[trim] ( identifier[edge_ic_cutoff] ) keyword[if] identifier[len] ( identifier[ave_motif] )== literal[int] : identifier[ave_motif] = identifier[Motif] ([[ literal[int] , literal[int] , literal[int] , literal[int] ]]) identifier[ave_motif] . identifier[id] = literal[string] % identifier[ave_count] identifier[ave_count] += literal[int] identifier[new_node] = identifier[MotifTree] ( identifier[ave_motif] ) keyword[if] identifier[pval] : identifier[new_node] . identifier[maxscore] = literal[int] - identifier[mc] . identifier[compare_motifs] ( identifier[new_node] . identifier[motif] , identifier[new_node] . identifier[motif] , identifier[match] , identifier[metric] , identifier[combine] , identifier[pval] )[ literal[int] ] keyword[else] : identifier[new_node] . identifier[maxscore] = identifier[mc] . identifier[compare_motifs] ( identifier[new_node] . identifier[motif] , identifier[new_node] . identifier[motif] , identifier[match] , identifier[metric] , identifier[combine] , identifier[pval] )[ literal[int] ] identifier[new_node] . identifier[mergescore] = identifier[score] identifier[n1] . identifier[parent] = identifier[new_node] identifier[n2] . identifier[parent] = identifier[new_node] identifier[new_node] . identifier[left] = identifier[n1] identifier[new_node] . identifier[right] = identifier[n2] identifier[cmp_nodes] = identifier[dict] ([( identifier[node] . identifier[motif] , identifier[node] ) keyword[for] identifier[node] keyword[in] identifier[nodes] keyword[if] keyword[not] identifier[node] . identifier[parent] ]) keyword[if] identifier[progress] : identifier[progress] =( literal[int] - identifier[len] ( identifier[cmp_nodes] )/ identifier[float] ( identifier[total] ))* literal[int] identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] . identifier[format] ( literal[string] *( identifier[int] ( identifier[progress] )// literal[int] ), literal[string] *( literal[int] - identifier[int] ( identifier[progress] )// literal[int] ), identifier[int] ( identifier[progress] ))) identifier[result] = identifier[mc] . identifier[get_all_scores] ( [ identifier[new_node] . identifier[motif] ], identifier[list] ( identifier[cmp_nodes] . identifier[keys] ()), identifier[match] , identifier[metric] , identifier[combine] , identifier[pval] , identifier[parallel] = keyword[True] ) keyword[for] identifier[motif] , identifier[n] keyword[in] identifier[cmp_nodes] . identifier[items] (): identifier[x] = identifier[result] [ identifier[new_node] . identifier[motif] . identifier[id] ][ identifier[motif] . identifier[id] ] keyword[if] identifier[pval] : identifier[x] =[ literal[int] - identifier[x] [ literal[int] ]]+ identifier[x] [ literal[int] :] identifier[scores] [( identifier[new_node] , identifier[n] )]= identifier[x] identifier[nodes] . identifier[append] ( identifier[new_node] ) identifier[cluster_nodes] =[ identifier[node] keyword[for] identifier[node] keyword[in] identifier[nodes] keyword[if] keyword[not] identifier[node] . identifier[parent] ] keyword[if] identifier[progress] : identifier[sys] . identifier[stderr] . identifier[write] ( literal[string] ) identifier[root] = identifier[nodes] [- literal[int] ] keyword[for] identifier[node] keyword[in] [ identifier[node] keyword[for] identifier[node] keyword[in] identifier[nodes] keyword[if] keyword[not] identifier[node] . identifier[left] ]: identifier[node] . identifier[parent] . identifier[checkMerge] ( identifier[root] , identifier[threshold] ) keyword[return] identifier[root]
def cluster_motifs(motifs, match='total', metric='wic', combine='mean', pval=True, threshold=0.95, trim_edges=False, edge_ic_cutoff=0.2, include_bg=True, progress=True, ncpus=None): """ Clusters a set of sequence motifs. Required arg 'motifs' is a file containing positional frequency matrices or an array with motifs. Optional args: 'match', 'metric' and 'combine' specify the method used to compare and score the motifs. By default the WIC score is used (metric='wic'), using the the score over the whole alignment (match='total'), with the total motif score calculated as the mean score of all positions (combine='mean'). 'match' can be either 'total' for the total alignment or 'subtotal' for the maximum scoring subsequence of the alignment. 'metric' can be any metric defined in MotifComparer, currently: 'pcc', 'ed', 'distance', 'wic' or 'chisq' 'combine' determines how the total score is calculated from the score of individual positions and can be either 'sum' or 'mean' 'pval' can be True or False and determines if the score should be converted to an empirical p-value 'threshold' determines the score (or p-value) cutoff If 'trim_edges' is set to True, all motif edges with an IC below 'edge_ic_cutoff' will be removed before clustering When computing the average of two motifs 'include_bg' determines if, at a position only present in one motif, the information in that motif should be kept, or if it should be averaged with background frequencies. Should probably be left set to True. """ # First read pfm or pfm formatted motiffile if type([]) != type(motifs): motifs = read_motifs(motifs, fmt='pwm') # depends on [control=['if'], data=[]] mc = MotifComparer() # Trim edges with low information content if trim_edges: for motif in motifs: motif.trim(edge_ic_cutoff) # depends on [control=['for'], data=['motif']] # depends on [control=['if'], data=[]] # Make a MotifTree node for every motif nodes = [MotifTree(m) for m in motifs] # Determine all pairwise scores and maxscore per motif scores = {} motif_nodes = dict([(n.motif.id, n) for n in nodes]) motifs = [n.motif for n in nodes] if progress: sys.stderr.write('Calculating initial scores\n') # depends on [control=['if'], data=[]] result = mc.get_all_scores(motifs, motifs, match, metric, combine, pval, parallel=True, ncpus=ncpus) for (m1, other_motifs) in result.items(): for (m2, score) in other_motifs.items(): if m1 == m2: if pval: motif_nodes[m1].maxscore = 1 - score[0] # depends on [control=['if'], data=[]] else: motif_nodes[m1].maxscore = score[0] # depends on [control=['if'], data=['m1']] else: if pval: score = [1 - score[0]] + score[1:] # depends on [control=['if'], data=[]] scores[motif_nodes[m1], motif_nodes[m2]] = score # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] cluster_nodes = [node for node in nodes] ave_count = 1 total = len(cluster_nodes) while len(cluster_nodes) > 1: l = sorted(scores.keys(), key=lambda x: scores[x][0]) i = -1 (n1, n2) = l[i] while n1 not in cluster_nodes or n2 not in cluster_nodes: i -= 1 (n1, n2) = l[i] # depends on [control=['while'], data=[]] if len(n1.motif) > 0 and len(n2.motif) > 0: (score, pos, orientation) = scores[n1, n2] ave_motif = n1.motif.average_motifs(n2.motif, pos, orientation, include_bg=include_bg) ave_motif.trim(edge_ic_cutoff) # Check if the motif is not empty if len(ave_motif) == 0: ave_motif = Motif([[0.25, 0.25, 0.25, 0.25]]) # depends on [control=['if'], data=[]] ave_motif.id = 'Average_%s' % ave_count ave_count += 1 new_node = MotifTree(ave_motif) if pval: new_node.maxscore = 1 - mc.compare_motifs(new_node.motif, new_node.motif, match, metric, combine, pval)[0] # depends on [control=['if'], data=[]] else: new_node.maxscore = mc.compare_motifs(new_node.motif, new_node.motif, match, metric, combine, pval)[0] new_node.mergescore = score #print "%s + %s = %s with score %s" % (n1.motif.id, n2.motif.id, ave_motif.id, score) n1.parent = new_node n2.parent = new_node new_node.left = n1 new_node.right = n2 cmp_nodes = dict([(node.motif, node) for node in nodes if not node.parent]) if progress: progress = (1 - len(cmp_nodes) / float(total)) * 100 sys.stderr.write('\rClustering [{0}{1}] {2}%'.format('#' * (int(progress) // 10), ' ' * (10 - int(progress) // 10), int(progress))) # depends on [control=['if'], data=[]] result = mc.get_all_scores([new_node.motif], list(cmp_nodes.keys()), match, metric, combine, pval, parallel=True) for (motif, n) in cmp_nodes.items(): x = result[new_node.motif.id][motif.id] if pval: x = [1 - x[0]] + x[1:] # depends on [control=['if'], data=[]] scores[new_node, n] = x # depends on [control=['for'], data=[]] nodes.append(new_node) # depends on [control=['if'], data=[]] cluster_nodes = [node for node in nodes if not node.parent] # depends on [control=['while'], data=[]] if progress: sys.stderr.write('\n') # depends on [control=['if'], data=[]] root = nodes[-1] for node in [node for node in nodes if not node.left]: node.parent.checkMerge(root, threshold) # depends on [control=['for'], data=['node']] return root
def create_payload(self): """Wrap submitted data within an extra dict and rename ``path_``. For more information on wrapping submitted data, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. """ payload = super(Media, self).create_payload() if 'path_' in payload: payload['path'] = payload.pop('path_') return {u'medium': payload}
def function[create_payload, parameter[self]]: constant[Wrap submitted data within an extra dict and rename ``path_``. For more information on wrapping submitted data, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. ] variable[payload] assign[=] call[call[name[super], parameter[name[Media], name[self]]].create_payload, parameter[]] if compare[constant[path_] in name[payload]] begin[:] call[name[payload]][constant[path]] assign[=] call[name[payload].pop, parameter[constant[path_]]] return[dictionary[[<ast.Constant object at 0x7da18bcca560>], [<ast.Name object at 0x7da18bcc8ac0>]]]
keyword[def] identifier[create_payload] ( identifier[self] ): literal[string] identifier[payload] = identifier[super] ( identifier[Media] , identifier[self] ). identifier[create_payload] () keyword[if] literal[string] keyword[in] identifier[payload] : identifier[payload] [ literal[string] ]= identifier[payload] . identifier[pop] ( literal[string] ) keyword[return] { literal[string] : identifier[payload] }
def create_payload(self): """Wrap submitted data within an extra dict and rename ``path_``. For more information on wrapping submitted data, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. """ payload = super(Media, self).create_payload() if 'path_' in payload: payload['path'] = payload.pop('path_') # depends on [control=['if'], data=['payload']] return {u'medium': payload}
def re_enqueue(self, item): """Re-enqueue till reach max retries.""" if 'retries' in item: retries = item['retries'] if retries >= self.MAX_RETRIES: log.warn("Failed to execute {} after {} retries, give it " " up.".format(item['method'], retries)) else: retries += 1 item['retries'] = retries self._q.put_nowait(item) else: item['retries'] = 1 self._q.put_nowait(item)
def function[re_enqueue, parameter[self, item]]: constant[Re-enqueue till reach max retries.] if compare[constant[retries] in name[item]] begin[:] variable[retries] assign[=] call[name[item]][constant[retries]] if compare[name[retries] greater_or_equal[>=] name[self].MAX_RETRIES] begin[:] call[name[log].warn, parameter[call[constant[Failed to execute {} after {} retries, give it up.].format, parameter[call[name[item]][constant[method]], name[retries]]]]]
keyword[def] identifier[re_enqueue] ( identifier[self] , identifier[item] ): literal[string] keyword[if] literal[string] keyword[in] identifier[item] : identifier[retries] = identifier[item] [ literal[string] ] keyword[if] identifier[retries] >= identifier[self] . identifier[MAX_RETRIES] : identifier[log] . identifier[warn] ( literal[string] literal[string] . identifier[format] ( identifier[item] [ literal[string] ], identifier[retries] )) keyword[else] : identifier[retries] += literal[int] identifier[item] [ literal[string] ]= identifier[retries] identifier[self] . identifier[_q] . identifier[put_nowait] ( identifier[item] ) keyword[else] : identifier[item] [ literal[string] ]= literal[int] identifier[self] . identifier[_q] . identifier[put_nowait] ( identifier[item] )
def re_enqueue(self, item): """Re-enqueue till reach max retries.""" if 'retries' in item: retries = item['retries'] if retries >= self.MAX_RETRIES: log.warn('Failed to execute {} after {} retries, give it up.'.format(item['method'], retries)) # depends on [control=['if'], data=['retries']] else: retries += 1 item['retries'] = retries self._q.put_nowait(item) # depends on [control=['if'], data=['item']] else: item['retries'] = 1 self._q.put_nowait(item)