code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def load(fp: Union[TextIO, str], load_module: types.ModuleType, **kwargs): """ Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: js...
Convert a file name or file-like object containing stringified JSON into a JSGObject :param fp: file-like object to deserialize :param load_module: module that contains declarations for types :param kwargs: arguments see: json.load for details :return: JSGObject representing the json string
def reassign_proficiency_to_objective_bank(self, objective_id, from_objective_bank_id, to_objective_bank_id): """Moves an ``Objective`` from one ``ObjectiveBank`` to another. Mappings to other ``ObjectiveBanks`` are unaffected. arg: objective_id (osid.id.Id): the ``Id`` of the ...
Moves an ``Objective`` from one ``ObjectiveBank`` to another. Mappings to other ``ObjectiveBanks`` are unaffected. arg: objective_id (osid.id.Id): the ``Id`` of the ``Objective`` arg: from_objective_bank_id (osid.id.Id): the ``Id`` of the current ``Objecti...
def map(cls, x, palette, limits, na_value=None): """ Map values to a discrete palette Parameters ---------- palette : callable ``f(x)`` palette to use x : array_like Continuous values to scale na_value : object Value to use for...
Map values to a discrete palette Parameters ---------- palette : callable ``f(x)`` palette to use x : array_like Continuous values to scale na_value : object Value to use for missing values. Returns ------- out : array...
def _add_spin_magnitudes(self, structure): """ Replaces Spin.up/Spin.down with spin magnitudes specified by mag_species_spin. :param structure: :return: """ for idx, site in enumerate(structure): if getattr(site.specie, '_properties', None): ...
Replaces Spin.up/Spin.down with spin magnitudes specified by mag_species_spin. :param structure: :return:
def _updateConstructorAndMembers(self): """We overwrite constructor and accessors every time because the constructor might have to consume all members even if their decorator is below the "synthesizeConstructor" decorator and it also might need to update the getters and setters because the naming convention has...
We overwrite constructor and accessors every time because the constructor might have to consume all members even if their decorator is below the "synthesizeConstructor" decorator and it also might need to update the getters and setters because the naming convention has changed.
def space_new(args): """ Create a new workspace. """ r = fapi.create_workspace(args.project, args.workspace, args.authdomain, dict()) fapi._check_response_code(r, 201) if fcconfig.verbosity: eprint(r.content) return 0
Create a new workspace.
def _set_cfm_detail(self, v, load=False): """ Setter method for cfm_detail, mapped from YANG variable /cfm_state/cfm_detail (container) If this variable is read-only (config: false) in the source YANG file, then _set_cfm_detail is considered as a private method. Backends looking to populate this var...
Setter method for cfm_detail, mapped from YANG variable /cfm_state/cfm_detail (container) If this variable is read-only (config: false) in the source YANG file, then _set_cfm_detail is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cfm_de...
def fire(self, exclude=None, delay=True): """Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to s...
Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accident...
def from_conll(this_class, stream): """Construct a Sentence. stream is an iterable over strings where each string is a line in CoNLL-X format. If there are multiple sentences in this stream, we only return the first one.""" stream = iter(stream) sentence = this_class() fo...
Construct a Sentence. stream is an iterable over strings where each string is a line in CoNLL-X format. If there are multiple sentences in this stream, we only return the first one.
def await_transform_exists(cli, transform_path, does_exist=DEFAULT_TRANSFORM_EXISTS, timeout_seconds=DEFAULT_TIMEOUT_SECONDS): """ Waits for a single transform to exist based on does_exist. :param cli: :param transform_path: :param does_exist: Whether or not to await for exist state (True | False) ...
Waits for a single transform to exist based on does_exist. :param cli: :param transform_path: :param does_exist: Whether or not to await for exist state (True | False) :param timeout_seconds: How long until this returns with failure :return: bool
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
Find the end of the region started with start and end markers
def days_to_liquidate_positions(positions, market_data, max_bar_consumption=0.2, capital_base=1e6, mean_volume_window=5): """ Compute the number of days that would have been required to fully liquidate each posit...
Compute the number of days that would have been required to fully liquidate each position on each day based on the trailing n day mean daily bar volume and a limit on the proportion of a daily bar that we are allowed to consume. This analysis uses portfolio allocations and a provided capital base r...
def writeCmdMsg(self, msg): """ Internal method to set the command result string. Args: msg (str): Message built during command. """ ekm_log("(writeCmdMsg | " + self.getContext() + ") " + msg) self.m_command_msg = msg
Internal method to set the command result string. Args: msg (str): Message built during command.
def listify(val, return_type=tuple): """ Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c'] """ # TODO: flatlistify((1, 2, 3...
Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c']
def original_query_sequence_length(self): """Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int """ if not self.is_aligned() or not self....
Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int
def quote_by_instruments(cls, client, ids): """ create instrument urls, fetch, return results """ base_url = "https://api.robinhood.com/instruments" id_urls = ["{}/{}/".format(base_url, _id) for _id in ids] return cls.quotes_by_instrument_urls(client, id_urls)
create instrument urls, fetch, return results
def user_absent(name, channel=14, **kwargs): ''' Remove user Delete all user (uid) records having the matching name. name string name of user to delete channel channel to remove user access from defaults to 14 for auto. kwargs - api_host=localhost - api_user=ad...
Remove user Delete all user (uid) records having the matching name. name string name of user to delete channel channel to remove user access from defaults to 14 for auto. kwargs - api_host=localhost - api_user=admin - api_pass= - api_port=623 - ...
def show_lowstate(**kwargs): ''' List out the low data that will be applied to this minion CLI Example: .. code-block:: bash salt '*' state.show_lowstate ''' __opts__['grains'] = __grains__ opts = salt.utils.state.get_sls_opts(__opts__, **kwargs) st_ = salt.client.ssh.state.SS...
List out the low data that will be applied to this minion CLI Example: .. code-block:: bash salt '*' state.show_lowstate
def _mirror_penalized(self, f_values, idx): """obsolete and subject to removal (TODO), return modified f-values such that for each mirror one becomes worst. This function is useless when selective mirroring is applied with no more than (lambda-mu)/2 solutions. Mirrors are leadi...
obsolete and subject to removal (TODO), return modified f-values such that for each mirror one becomes worst. This function is useless when selective mirroring is applied with no more than (lambda-mu)/2 solutions. Mirrors are leading and trailing values in ``f_values``.
def file_like(name): """A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier. """ return (os.path.exists(name) or os.path.dirname(name) or name.endswith('.py') or not ident_re.match(o...
A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier.
def confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False): """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. .. versionadded:: 4.0 ...
Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. .. versionadded:: 4.0 Added the `err` parameter. :param text: the question to ask. :param default: the default for the prom...
def get_vulnerability( source, sink, triggers, lattice, cfg, interactive, blackbox_mapping ): """Get vulnerability between source and sink if it exists. Uses triggers to find sanitisers. Note: When a secondary node is in_constraint with the sink but not the source...
Get vulnerability between source and sink if it exists. Uses triggers to find sanitisers. Note: When a secondary node is in_constraint with the sink but not the source, the secondary is a save_N_LHS node made in process_function in expr_visitor. Args: source(TriggerNod...
def _init_trace_logging(self, app): """ Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension. """ enabled = not app.config.get(CONF_...
Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is set in the Flask config. Args: app (flask.Flask). the Flask application for which to initialize the extension.
def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On m...
Verifies that the specified host is known by the specified user On many systems, specifically those running with openssh 4 or older, the ``enc`` option must be set, only openssh 5 and above can detect the key type. name The name of the remote host (e.g. "github.com") Note that only a s...
def get_subdomain_DID_info(fqn, db_path=None, zonefiles_dir=None): """ Get a subdomain's DID info. Return None if not found """ opts = get_blockstack_opts() if not is_subdomains_enabled(opts): log.warn("Subdomain support is disabled") return None if db_path is None: ...
Get a subdomain's DID info. Return None if not found
def predict(self, data): """ Predict a new data set based on an estimated model. Parameters ---------- data : pandas.DataFrame Data to use for prediction. Must contain all the columns referenced by the right-hand side of the `model_expression`. R...
Predict a new data set based on an estimated model. Parameters ---------- data : pandas.DataFrame Data to use for prediction. Must contain all the columns referenced by the right-hand side of the `model_expression`. Returns ------- result : panda...
def _copy_from(self, rhs): """Copy all data from rhs into this instance, handles usage count""" self._manager = rhs._manager self._rlist = type(rhs._rlist)(rhs._rlist) self._region = rhs._region self._ofs = rhs._ofs self._size = rhs._size for region in self._rlis...
Copy all data from rhs into this instance, handles usage count
def OnCellFontSize(self, event): """Cell font size event handler""" with undo.group(_("Font size")): self.grid.actions.set_attr("pointsize", event.size) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell font size event handler
def transpose_list(list_of_dicts): """Transpose a list of dicts to a dict of lists :param list_of_dicts: to transpose, as in the output from a parse call :return: Dict of lists """ res = {} for d in list_of_dicts: for k, v in d.items(): if k in res: res[k].ap...
Transpose a list of dicts to a dict of lists :param list_of_dicts: to transpose, as in the output from a parse call :return: Dict of lists
def run(cmd, *args, **kwargs): """Echo a command before running it. Defaults to repo as cwd""" log.info('> ' + list2cmdline(cmd)) kwargs.setdefault('cwd', here) kwargs.setdefault('shell', sys.platform == 'win32') if not isinstance(cmd, list): cmd = cmd.split() return check_call(cmd, *ar...
Echo a command before running it. Defaults to repo as cwd
def _sig(self, name, dtype=BIT, defVal=None): """ Create signal in this unit """ if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() container = dtype.fromPy(None) for f in dtype.fields: if ...
Create signal in this unit
def run(data, samples, force, ipyclient): """ Check all samples requested have been clustered (state=6), make output directory, then create the requested outfiles. Excluded samples are already removed from samples. """ ## prepare dirs data.dirs.outfiles = os.path.join(data.dirs.project, dat...
Check all samples requested have been clustered (state=6), make output directory, then create the requested outfiles. Excluded samples are already removed from samples.
def convert_bam_to_bed(in_bam, out_file): """Convert BAM to bed file using BEDTools. """ with file_transaction(out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: subprocess.check_call(["bamToBed", "-i", in_bam, "-tag", "NM"], stdout=out...
Convert BAM to bed file using BEDTools.
def read(self, size=None): """Read a length of bytes. Return empty on EOF. If 'size' is omitted, return whole file. """ if size is not None: return self.__sf.read(size) block_size = self.__class__.__block_size b = bytearray() received_bytes = 0 ...
Read a length of bytes. Return empty on EOF. If 'size' is omitted, return whole file.
def probability_density(self, X): """Compute density function for given copula family. Args: X: `np.ndarray` Returns: np.array: probability density """ self.check_fit() U, V = self.split_matrix(X) if self.theta == 0: return ...
Compute density function for given copula family. Args: X: `np.ndarray` Returns: np.array: probability density
def _request_prepare(self, three_pc_key: Tuple[int, int], recipients: List[str] = None, stash_data: Optional[Tuple[str, str, str]] = None) -> bool: """ Request preprepare """ if recipients is None: recipients = self.node.nodes...
Request preprepare
def hide_file(path): """ Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text. """ __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes....
Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text.
def ServiceWorker_startWorker(self, scopeURL): """ Function path: ServiceWorker.startWorker Domain: ServiceWorker Method name: startWorker Parameters: Required arguments: 'scopeURL' (type: string) -> No description No return value. """ assert isinstance(scopeURL, (str,) ), "Argu...
Function path: ServiceWorker.startWorker Domain: ServiceWorker Method name: startWorker Parameters: Required arguments: 'scopeURL' (type: string) -> No description No return value.
def leagues(self, year=2019): """Return all leagues in dict {id0: league0, id1: league1}. :params year: Year. """ if year not in self._leagues: self._leagues[year] = leagues(year) return self._leagues[year]
Return all leagues in dict {id0: league0, id1: league1}. :params year: Year.
def minimal_selector(self, complete_selector): """Returns the minimal selector that uniquely matches `complete_selector`. Args: complete_selector: A complete selector stored in the map. Returns: A partial selector that unambiguously matches `complete_selector`. Raises: KeyError: If ...
Returns the minimal selector that uniquely matches `complete_selector`. Args: complete_selector: A complete selector stored in the map. Returns: A partial selector that unambiguously matches `complete_selector`. Raises: KeyError: If `complete_selector` is not in the map.
def get_annotation_urls_and_checksums(species, release=None, ftp=None): """Get FTP URLs and checksums for Ensembl genome annotations. Parameters ---------- species : str or list of str The species or list of species for which to get genome annotations (e.g., "Homo_sapiens"). rel...
Get FTP URLs and checksums for Ensembl genome annotations. Parameters ---------- species : str or list of str The species or list of species for which to get genome annotations (e.g., "Homo_sapiens"). release : int, optional The release number to look up. If `None`, use late...
def list_categories(self, package_keyname, **kwargs): """List the categories for the given package. :param str package_keyname: The package for which to get the categories. :returns: List of categories associated with the package """ get_kwargs = {} get_kwargs['mask'] = ...
List the categories for the given package. :param str package_keyname: The package for which to get the categories. :returns: List of categories associated with the package
def log_estimator_evaluation_result(self, eval_results): """Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. A...
Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. Args: eval_results: dict, the result of evaluate() from a e...
def read(self, *args, **kwargs): """Reads the node as a file """ with self.open('r') as f: return f.read(*args, **kwargs)
Reads the node as a file
def load_df_state(path_csv: Path)->pd.DataFrame: '''load `df_state` from `path_csv` Parameters ---------- path_csv : Path path to the csv file that stores `df_state` produced by a supy run Returns ------- pd.DataFrame `df_state` produced by a supy run ''' df_state ...
load `df_state` from `path_csv` Parameters ---------- path_csv : Path path to the csv file that stores `df_state` produced by a supy run Returns ------- pd.DataFrame `df_state` produced by a supy run
def impact_path(self, value): """Setter to impact path. :param value: The impact path. :type value: str """ self._impact_path = value if value is None: self.action_show_report.setEnabled(False) self.action_show_log.setEnabled(False) se...
Setter to impact path. :param value: The impact path. :type value: str
def parse_words(self): """Parse TextGrid word intervals. This method parses the word intervals in a TextGrid to extract each word and each word's start and end times in the audio recording. For each word, it instantiates the class Word(), with the word and its start and ...
Parse TextGrid word intervals. This method parses the word intervals in a TextGrid to extract each word and each word's start and end times in the audio recording. For each word, it instantiates the class Word(), with the word and its start and end times as attributes of that cl...
def get_power_state(self, userid): """Get power status of a z/VM instance.""" LOG.debug('Querying power stat of %s' % userid) requestData = "PowerVM " + userid + " status" action = "query power state of '%s'" % userid with zvmutils.log_and_reraise_smt_request_failed(action): ...
Get power status of a z/VM instance.
def output_file(self): """ If only one output file return it. Otherwise raise an exception. """ out_files = self.output_files if len(out_files) != 1: err_msg = "output_file property is only valid if there is a single" err_msg += " output file. Here there a...
If only one output file return it. Otherwise raise an exception.
def _get_substitute_element(head, elt, ps): '''if elt matches a member of the head substitutionGroup, return the GED typecode. head -- ElementDeclaration typecode, elt -- the DOM element being parsed ps -- ParsedSoap Instance ''' if not isinstance(head, ElementDeclaration): return...
if elt matches a member of the head substitutionGroup, return the GED typecode. head -- ElementDeclaration typecode, elt -- the DOM element being parsed ps -- ParsedSoap Instance
def setTimer(self, timeout, description=None): """ Sets a timer. :param description: :param timeout: timeout in seconds :return: the timerId """ self.timerId += 1 timer = Timer(timeout, self.__timeoutHandler, (self.timerId, description)) timer.sta...
Sets a timer. :param description: :param timeout: timeout in seconds :return: the timerId
def get_activity_query_session(self): """Gets the ``OsidSession`` associated with the activity query service. return: (osid.learning.ActivityQuerySession) - a ``ActivityQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports...
Gets the ``OsidSession`` associated with the activity query service. return: (osid.learning.ActivityQuerySession) - a ``ActivityQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_activity_query()`` is ``false`` ...
def _combine(self, x, y): """Combines two constraints, raising an error if they are not compatible.""" if x is None or y is None: return x or y if x != y: raise ValueError('Incompatible set of constraints provided.') return x
Combines two constraints, raising an error if they are not compatible.
def validate_password_confirmation(self, value): """ password_confirmation check """ if value != self.initial_data['password']: raise serializers.ValidationError(_('Password confirmation mismatch')) return value
password_confirmation check
def greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd): r"""Calculate Green's function for TM and TE. This is a modified version of empymod.kernel.greenfct(). See the original version for more information. """ # GTM/GTE have shape (frequency, offset, lambda). # gamTM/gamT...
r"""Calculate Green's function for TM and TE. This is a modified version of empymod.kernel.greenfct(). See the original version for more information.
def graphcut_subprocesses(graphcut_function, graphcut_arguments, processes = None): """ Executes multiple graph cuts in parallel. This can result in a significant speed-up. Parameters ---------- graphcut_function : function The graph cut to use (e.g. `graphcut_stawiaski`). graph...
Executes multiple graph cuts in parallel. This can result in a significant speed-up. Parameters ---------- graphcut_function : function The graph cut to use (e.g. `graphcut_stawiaski`). graphcut_arguments : tuple List of arguments to pass to the respective subprocesses resp. the...
def update_scale(self, overflow): """dynamically update loss scale""" iter_since_rescale = self._num_steps - self._last_rescale_iter if overflow: self._last_overflow_iter = self._num_steps self._overflows_since_rescale += 1 percentage = self._overflows_since_r...
dynamically update loss scale
def category(self, categories): """Add categories assigned to this message :rtype: list(Category) """ if isinstance(categories, list): for c in categories: self.add_category(c) else: self.add_category(categories)
Add categories assigned to this message :rtype: list(Category)
def _find_package(self, root_package): """Finds package name of file :param root_package: root package :return: package name """ package = self.path.replace(root_package, "") if package.endswith(".py"): package = package[:-3] package = package.repla...
Finds package name of file :param root_package: root package :return: package name
def compile_rcc(self, namespace, unknown): """Compile qt resource files :param namespace: namespace containing arguments from the launch parser :type namespace: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None ...
Compile qt resource files :param namespace: namespace containing arguments from the launch parser :type namespace: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: None
def set_level(self, level): """ A method to set all column values to one of the levels. :param str level: The level at which the column will be set (a string) :returns: H2OFrame with entries set to the desired level. """ return H2OFrame._expr(expr=ExprNode("setLevel", s...
A method to set all column values to one of the levels. :param str level: The level at which the column will be set (a string) :returns: H2OFrame with entries set to the desired level.
def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], ...
flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10...
def _place_ticks_vertical(self): """Display the ticks for a vertical slider.""" for tick, label in zip(self.ticks, self.ticklabels): y = self.convert_to_pixels(tick) label.place_configure(y=y)
Display the ticks for a vertical slider.
def hdrval(cls): """Construct dictionary mapping display column title to IterationStats entries. """ hdrmap = {'Itn': 'Iter'} hdrmap.update(cls.hdrval_objfun) hdrmap.update({'r': 'PrimalRsdl', 's': 'DualRsdl', u('ρ'): 'Rho'}) return hdrmap
Construct dictionary mapping display column title to IterationStats entries.
def engine_from_environment() -> Engine: """Returns an Engine instance configured using environment variables. If the environment variables are set, but incorrect, an authentication failure will occur when attempting to run jobs on the engine. Required Environment Variables: QUANTUM_ENGINE_PRO...
Returns an Engine instance configured using environment variables. If the environment variables are set, but incorrect, an authentication failure will occur when attempting to run jobs on the engine. Required Environment Variables: QUANTUM_ENGINE_PROJECT: The name of a google cloud project, with t...
def reduce_hierarchy(x, depth): """Reduce the hierarchy (depth by `|`) string to the specified level""" _x = x.split('|') depth = len(_x) + depth - 1 if depth < 0 else depth return '|'.join(_x[0:(depth + 1)])
Reduce the hierarchy (depth by `|`) string to the specified level
def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None raw_order_list = rsp_pb.s2c.orderList order_list = [OrderListQuery.parse_order(rsp_pb, order) for order in raw_order_list] ...
Convert from PLS response to user response
def append_item(self, item): """ Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added. """ did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: sel...
Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added.
def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. """ if self._globalInhibition or self._inhibitionRadius > self._numInputs: self._updateMinDutyCyclesGlobal() ...
Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted.
def getAssociation(self, assoc_handle, dumb, checkExpiration=True): """Get the association with the specified handle. @type assoc_handle: str @param dumb: Is this association used with dumb mode? @type dumb: bool @returns: the association, or None if no valid association with ...
Get the association with the specified handle. @type assoc_handle: str @param dumb: Is this association used with dumb mode? @type dumb: bool @returns: the association, or None if no valid association with that handle was found. @returntype: L{openid.association.As...
def get_urls(self): """ Returns a list of urls including all NestedSimpleRouter urls """ ret = super(SimpleRouter, self).get_urls() for router in self.nested_routers: ret.extend(router.get_urls()) return ret
Returns a list of urls including all NestedSimpleRouter urls
def generate_obj(self): """Generates the secret object, respecting existing information and user specified options""" secret_obj = {} if self.existing: secret_obj = deepcopy(self.existing) for key in self.keys: key_name = key['name'] if self.e...
Generates the secret object, respecting existing information and user specified options
def decrypt(receiver_prvhex: str, msg: bytes) -> bytes: """ Decrypt with eth private key Parameters ---------- receiver_pubhex: str Receiver's ethereum private key hex string msg: bytes Data to decrypt Returns ------- bytes Plain text """ pubkey = ms...
Decrypt with eth private key Parameters ---------- receiver_pubhex: str Receiver's ethereum private key hex string msg: bytes Data to decrypt Returns ------- bytes Plain text
def get_constant_state(self): """Read state that was written in "first_part" mode. Returns: a structure """ ret = self.constant_states[self.next_constant_state] self.next_constant_state += 1 return ret
Read state that was written in "first_part" mode. Returns: a structure
def _extract_number_of_taxa(self): """ sets `self.number_taxa` to the number of taxa as string """ n_taxa = dict() for i in self.seq_records: if i.gene_code not in n_taxa: n_taxa[i.gene_code] = 0 n_taxa[i.gene_code] += 1 number_taxa...
sets `self.number_taxa` to the number of taxa as string
def cur_space(self, name=None): """Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. """ if name is None: ...
Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned.
def app_restart(name, profile, **kwargs): """ Restart application. Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially. It can be used to quickly change application profile. """ ctx = Context(**kwargs) ctx.execute_action('app:restart', **{ 'node': ct...
Restart application. Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially. It can be used to quickly change application profile.
def put(self): """Re-import all templates, overwriting any local changes made""" try: _import_templates(force=True) return self.make_response('Imported templates') except: self.log.exception('Failed importing templates') return self.make_response('...
Re-import all templates, overwriting any local changes made
def axis_angle(self): """:obj:`numpy.ndarray` of float: The axis-angle representation for the rotation. """ qw, qx, qy, qz = self.quaternion theta = 2 * np.arccos(qw) omega = np.array([1,0,0]) if theta > 0: rx = qx / np.sqrt(1.0 - qw**2) ry = qy / ...
:obj:`numpy.ndarray` of float: The axis-angle representation for the rotation.
def extract_interesting_date_ranges(returns): """ Extracts returns based on interesting events. See gen_date_range_interesting. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. R...
Extracts returns based on interesting events. See gen_date_range_interesting. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. Returns ------- ranges : OrderedDict Date r...
def get(self, endpoint='', url='', params=None, use_api_key=False): """Perform a get for a json API endpoint. :param string endpoint: Target endpoint. (Optional). :param string url: Override the endpoint and provide the full url (eg for pagination). (Optional). :param dict params: Provi...
Perform a get for a json API endpoint. :param string endpoint: Target endpoint. (Optional). :param string url: Override the endpoint and provide the full url (eg for pagination). (Optional). :param dict params: Provide parameters to pass to the request. (Optional). :return: Response jso...
def read_zipfile(self, encoding='utf8'): """ READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING """ from zipfile import ZipFile with ZipFile(self.abspath) as zipped: for num, zip_name in enumerate(zipped.namelist()): return zi...
READ FIRST FILE IN ZIP FILE :param encoding: :return: STRING
def report_many(self, event_list, metadata=None, block=None): """ Reports all the given events to Alooma by formatting them properly and placing them in the buffer to be sent by the Sender instance :param event_list: A list of dicts / strings representing events :param metadata: ...
Reports all the given events to Alooma by formatting them properly and placing them in the buffer to be sent by the Sender instance :param event_list: A list of dicts / strings representing events :param metadata: (Optional) A dict with extra metadata to be attached to t...
def _f_gene(sid, prefix="G_"): """Clips gene prefix from id.""" sid = sid.replace(SBML_DOT, ".") return _clip(sid, prefix)
Clips gene prefix from id.
def _recurse(data, obj): """Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those. """ content = _ContentManager() for child in obj.get_children(): # Some patches are Spines, too; skip those entirely. # S...
Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those.
def patch_api_service(self, name, body, **kwargs): # noqa: E501 """patch_api_service # noqa: E501 partially update the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
patch_api_service # noqa: E501 partially update the specified APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_api_service(name, body, async_req=True) >>> re...
def mixin_function_or_method(target, routine, name=None, isbound=False): """Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a ...
Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a bound method to target.
def set_tag(self, ip_dest, next_hop, **kwargs): """Set the tag value for the specified route Args: ip_dest (string): The ip address of the destination in the form of A.B.C.D/E next_hop (string): The next hop interface or ip address **kwargs['next_hop_...
Set the tag value for the specified route Args: ip_dest (string): The ip address of the destination in the form of A.B.C.D/E next_hop (string): The next hop interface or ip address **kwargs['next_hop_ip'] (string): The next hop address on dest...
def get_submissions(self, url): """ Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned. url: A url that requests for submissions should be sent to. """ response = self.client.get(url, params={'limit': self.opti...
Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned. url: A url that requests for submissions should be sent to.
def distortImage(self, image): ''' opposite of 'correct' ''' image = imread(image) (imgHeight, imgWidth) = image.shape[:2] mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight) return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, ...
opposite of 'correct'
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[Optional[Value], "DataNode"]: """Return entry value addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node. """ try: retur...
Return entry value addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
def untag(name, tag_name): """ Remove the given tag from the given metric. Return True if the metric was tagged, False otherwise """ with LOCK: by_tag = TAGS.get(tag_name, None) if not by_tag: return False try: by_tag.remove(name) # remov...
Remove the given tag from the given metric. Return True if the metric was tagged, False otherwise
def _compute_subplot_domains(widths, spacing): """ Compute normalized domain tuples for a list of widths and a subplot spacing value Parameters ---------- widths: list of float List of the desired withs of each subplot. The length of this list is also the specification of the nu...
Compute normalized domain tuples for a list of widths and a subplot spacing value Parameters ---------- widths: list of float List of the desired withs of each subplot. The length of this list is also the specification of the number of desired subplots spacing: float Spacing...
def indication(self, pdu): """Send a message.""" if _debug: Node._debug("indication(%s) %r", self.name, pdu) # make sure we're connected if not self.lan: raise ConfigurationError("unbound node") # if the pduSource is unset, fill in our address, otherwise # l...
Send a message.
def add(self, child): """ Adds a typed child object to the component type. @param child: Child object to be added. """ if isinstance(child, FatComponent): self.add_child_component(child) else: Fat.add(self, child)
Adds a typed child object to the component type. @param child: Child object to be added.
def gene_filter(self, query, mongo_query): """ Adds gene-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: mongo_que...
Adds gene-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: mongo_query(dict): returned object contains gene and panel-relat...
def start(self): """Start listening from stream""" if self.stream is None: from pyaudio import PyAudio, paInt16 self.pa = PyAudio() self.stream = self.pa.open( 16000, 1, paInt16, True, frames_per_buffer=self.chunk_size ) self._wrap...
Start listening from stream
def about_axis(cls, center, angle, axis, invert=False): """Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- Whe...
Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- When True, an inversion rotation is constructed ...
def par_y1step(i): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}_{1,G_i}`, one of the disjoint problems of optimizing :math:`\mathbf{y}_1`. Parameters ---------- i : int Index of grouping to update """ global mp_Y1 grpind = slice(mp_grp[i], mp_grp[i+1]) ...
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}_{1,G_i}`, one of the disjoint problems of optimizing :math:`\mathbf{y}_1`. Parameters ---------- i : int Index of grouping to update
def pot_for_component(pot, q, component=1, reverse=False): """ q for secondaries should already be flipped (via q_for_component) """ # currently only used by legacy wrapper: consider moving/removing if component==1: return pot elif component==2: if reverse: return pot...
q for secondaries should already be flipped (via q_for_component)