code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def decluster(self, trig_int, timing='detect', metric='avg_cor'): """ De-cluster a Party of detections by enforcing a detection separation. De-clustering occurs between events detected by different (or the same) templates. If multiple detections occur within trig_int then the pr...
De-cluster a Party of detections by enforcing a detection separation. De-clustering occurs between events detected by different (or the same) templates. If multiple detections occur within trig_int then the preferred detection will be determined by the metric argument. This can be eithe...
def check_user_can_comment(recID, client_ip_address, uid=-1): """ Check if a user hasn't already commented within the last seconds time limit: CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS :param recID: record id :param client_ip_address: IP => use: str(req.remote_ip) :param uid: user id, ...
Check if a user hasn't already commented within the last seconds time limit: CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS :param recID: record id :param client_ip_address: IP => use: str(req.remote_ip) :param uid: user id, as given by invenio.legacy.webuser.getUid(req)
def getValue(self, row): 'Memoize calcValue with key id(row)' if self._cachedValues is None: return self.calcValue(row) k = id(row) if k in self._cachedValues: return self._cachedValues[k] ret = self.calcValue(row) self._cachedValues[k] = ret ...
Memoize calcValue with key id(row)
def _assert_executable_regions_match(workflow_enabled_regions, workflow_spec): """ Check if the global workflow regions and the regions of stages (apps) match. If the workflow contains any applets, the workflow can be currently enabled in only one region - the region in which the applets are stored. ...
Check if the global workflow regions and the regions of stages (apps) match. If the workflow contains any applets, the workflow can be currently enabled in only one region - the region in which the applets are stored.
def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() # Calculate q.w = wPart * np.cos(vecNorm) q.x ...
Returns the exponent of the quaternion. (not tested)
def decode(self, X, lengths=None, algorithm=None): """Find most likely state sequence corresponding to ``X``. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequenc...
Find most likely state sequence corresponding to ``X``. Parameters ---------- X : array-like, shape (n_samples, n_features) Feature matrix of individual samples. lengths : array-like of integers, shape (n_sequences, ), optional Lengths of the individual sequence...
def findUnique(self, tableClass, comparison=None, default=_noItem): """ Find an Item in the database which should be unique. If it is found, return it. If it is not found, return 'default' if it was passed, otherwise raise L{errors.ItemNotFound}. If more than one item is found...
Find an Item in the database which should be unique. If it is found, return it. If it is not found, return 'default' if it was passed, otherwise raise L{errors.ItemNotFound}. If more than one item is found, raise L{errors.DuplicateUniqueItem}. @param comparison: implementor of L{iaxi...
def filesystem_from_config_dict(config_fs): """ Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error. """ if "module" not in config_fs: print("Key 'module' should be defined for the fil...
Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error.
def parent(self): """return the parent URL, with params, query, and fragment in place""" path = '/'.join(self.path.split('/')[:-1]) s = path.strip('/').split(':') if len(s)==2 and s[1]=='': return None else: return self.__class__(self, path=path)
return the parent URL, with params, query, and fragment in place
def send(self, msg): """Send the given message. """ with self._pub_lock: self.publish.send_string(msg) return self
Send the given message.
def edit(dataset_uri): """Default editor updating of readme content. """ try: dataset = dtoolcore.ProtoDataSet.from_uri( uri=dataset_uri, config_path=CONFIG_PATH ) except dtoolcore.DtoolCoreTypeError: dataset = dtoolcore.DataSet.from_uri( uri=d...
Default editor updating of readme content.
def start(self, *args, **kwargs): """ Start to read the stream(s). """ queue = Queue() stdout_reader, stderr_reader = \ self._create_readers(queue, *args, **kwargs) self.thread = threading.Thread(target=self._read, args=...
Start to read the stream(s).
def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) : """returns in, out, or both edges linked to self belonging the collection 'edges'. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects""" try : return ...
returns in, out, or both edges linked to self belonging the collection 'edges'. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects
def get_transaction(self, transaction_id): """Returns a Transaction object from the block store by its id. Params: transaction_id (str): The header_signature of the desired txn Returns: Transaction: The specified transaction Raises: ValueError: The ...
Returns a Transaction object from the block store by its id. Params: transaction_id (str): The header_signature of the desired txn Returns: Transaction: The specified transaction Raises: ValueError: The transaction is not in the block store
def get_subpackages_names(dir_): """Figures out the names of the subpackages of a package Args: dir_: (str) path to package directory Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package """ def is_package(d): d = os.path.join(di...
Figures out the names of the subpackages of a package Args: dir_: (str) path to package directory Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package
def brackets_insanity_check(p_string): """ This function performs a check for different number of '(' and ')' characters, which indicates that some forks are poorly constructed. Parameters ---------- p_string: str String with the definition of the pipeline, e.g.:: 'process...
This function performs a check for different number of '(' and ')' characters, which indicates that some forks are poorly constructed. Parameters ---------- p_string: str String with the definition of the pipeline, e.g.:: 'processA processB processC(ProcessD | ProcessE)'
def unravel_staff(staff_data): """Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to ...
Unravels staff role dictionary into flat list of staff members with ``role`` set as an attribute. Args: staff_data(dict): Data return from py:method::get_staff Returns: list: Flat list of staff members with ``role`` set to role type (i.e. course_admin, ...
def url_encode_stream(obj, stream=None, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&'): """Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. .. versionadded:: 0.8 ...
Like :meth:`url_encode` but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. .. versionadded:: 0.8 :param obj: the object to encode into a query string. :param stream: a stream to write the encoded object into or `None` if ...
def get_ribo_counts(ribo_fileobj, transcript_name, read_lengths, read_offsets): """For each mapped read of the given transcript in the BAM file (pysam AlignmentFile object), return the position (+1) and the corresponding frame (1, 2 or 3) to which it aligns. Keyword arguments: ribo_fileobj -- file ...
For each mapped read of the given transcript in the BAM file (pysam AlignmentFile object), return the position (+1) and the corresponding frame (1, 2 or 3) to which it aligns. Keyword arguments: ribo_fileobj -- file object - BAM file opened using pysam AlignmentFile transcript_name -- Name of trans...
def comp_meta(file_bef, file_aft, mode="pfail"): """Compare chunk meta, mode=[pfail, power, reboot]""" if env(): cij.err("cij.nvme.comp_meta: Invalid NVMe ENV.") return 1 nvme = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED) num_chk = int(nvme["LNVM_TOTAL_CHUNKS"]) meta_bef = cij.bin...
Compare chunk meta, mode=[pfail, power, reboot]
def registerAccountResponse(self, person, vendorSpecific=None): """CNIdentity.registerAccount(session, person) → Subject https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.registerAccount. Args: person: vendorSpecific: ...
CNIdentity.registerAccount(session, person) → Subject https://releases.dataone.org/online/api- documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.registerAccount. Args: person: vendorSpecific: Returns:
def return_cursor(self, dataout, sx, sy, frame, wcs, key, strval=''): """ writes the cursor position to dataout. input: dataout: the output stream sx: x coordinate sy: y coordinate wcs: nonzero if we want WCS translation ...
writes the cursor position to dataout. input: dataout: the output stream sx: x coordinate sy: y coordinate wcs: nonzero if we want WCS translation frame: frame buffer index key: keystroke used as trigge...
def stream_stats(self): """ Display basic statistics of callback execution: ideal period between callbacks, average measured period between callbacks, and average time spent in the callback. """ Tp = self.frame_length/float(self.fs)*1000 print('D...
Display basic statistics of callback execution: ideal period between callbacks, average measured period between callbacks, and average time spent in the callback.
def field_pklist_to_json(self, model, pks): """Convert a list of primary keys to a JSON dict. This uses the same format as cached_queryset_to_json """ app_label = model._meta.app_label model_name = model._meta.model_name return { 'app': app_label, ...
Convert a list of primary keys to a JSON dict. This uses the same format as cached_queryset_to_json
def build_structure(self, component, runnable, structure): """ Adds structure to a runnable component based on the structure specifications in the component model. @param component: Component model containing structure specifications. @type component: lems.model.component.FatCom...
Adds structure to a runnable component based on the structure specifications in the component model. @param component: Component model containing structure specifications. @type component: lems.model.component.FatComponent @param runnable: Runnable component to which structure is to be...
def open_sensor( self, input_source: str, output_dest: Optional[str] = None, extra_cmd: Optional[str] = None, ) -> Coroutine: """Open FFmpeg process for read autio stream. Return a coroutine. """ command = ["-vn", "-filter:a", "silencedetect=n={}dB:d=...
Open FFmpeg process for read autio stream. Return a coroutine.
def parse_config_file(path: str, final: bool = True) -> None: """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final)
Parses global options from a config file. See `OptionParser.parse_config_file`.
def makeSer(segID, N, CA, C, O, geo): '''Creates a Serine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_OG_length=geo.CB_OG_length CA_CB_OG_angle=geo.CA_CB_OG_angle N_CA_CB_OG_diangle=geo.N_CA_CB_OG_diangle ...
Creates a Serine residue
def from_settings(cls, settings=None, storage=None): """Create from settings. Parameters ---------- settings : `dict`, optional Settings (default: None). storage : `type`, optional Storage class (default: cls.DEFAULT_STORAGE) Returns ----...
Create from settings. Parameters ---------- settings : `dict`, optional Settings (default: None). storage : `type`, optional Storage class (default: cls.DEFAULT_STORAGE) Returns ------- `markovchain.Markov`
def nucleotide_range(self): '''Returns the nucleotide (start, end) positions inclusive of this variant. start==end if it's an amino acid variant, otherwise start+2==end''' if self.variant_type == 'p': return 3 * self.position, 3 * self.position + 2 else: return...
Returns the nucleotide (start, end) positions inclusive of this variant. start==end if it's an amino acid variant, otherwise start+2==end
def QA_fetch_future_min( code, start, end, format='numpy', frequence='1min', collections=DATABASE.future_min): '获取股票分钟线' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: frequence = '5min' elif frequence in ['15m...
获取股票分钟线
def _default_child_lookup(self, name): """ Return an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the children found having the given name :type name: ``str`` :param name: the name of the children (e.g. PID) :return: an instance of :class:`Ele...
Return an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the children found having the given name :type name: ``str`` :param name: the name of the children (e.g. PID) :return: an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the result...
def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'....
Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr.
def add_lnTo(self, x, y): """Return a newly created `a:lnTo` subtree with end point *(x, y)*. The new `a:lnTo` element is appended to this `a:path` element. """ lnTo = self._add_lnTo() pt = lnTo._add_pt() pt.x, pt.y = x, y return lnTo
Return a newly created `a:lnTo` subtree with end point *(x, y)*. The new `a:lnTo` element is appended to this `a:path` element.
def robotics_arg_parser(): """ Create an argparse.ArgumentParser for run_mujoco.py. """ parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='FetchReach-v0') parser.add_argument('--seed', help='RNG seed', type=int, default=None) parser.add_argument('--n...
Create an argparse.ArgumentParser for run_mujoco.py.
def _set_clear_mpls_ldp_statistics(self, v, load=False): """ Setter method for clear_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_statistics (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_clear_mpls_ldp_statistics is considered a...
Setter method for clear_mpls_ldp_statistics, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_ldp_statistics (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_clear_mpls_ldp_statistics is considered as a private method. Backends looking to populate this variable sh...
def _recv_robust(self, sock, size): """ Receive size from sock, and retry if the recv() call was interrupted. (this is only required for python2 compatability) """ while True: try: return sock.recv(size) except socket.error as e: ...
Receive size from sock, and retry if the recv() call was interrupted. (this is only required for python2 compatability)
def info(self, set_info=None, followlinks=True): """ info: backend info about self (probably not implemented for all backends. The result will be backend specific). @param set_info: If not None, this data will be set on self. @param followlinks: If True, symlinks will be f...
info: backend info about self (probably not implemented for all backends. The result will be backend specific). @param set_info: If not None, this data will be set on self. @param followlinks: If True, symlinks will be followed. If False, the info of the symlink itself will be...
def chassis(self): """Get list of chassis known to test session.""" self._check_session() status, data = self._rest.get_request('chassis') return data
Get list of chassis known to test session.
def norm_l1(x, axis=None): r"""Compute the :math:`\ell_1` norm .. math:: \| \mathbf{x} \|_1 = \sum_i | x_i | where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`. Parameters ---------- x : array_like Input array :math:`\mathbf{x}` axis : `None` or int or tuple o...
r"""Compute the :math:`\ell_1` norm .. math:: \| \mathbf{x} \|_1 = \sum_i | x_i | where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`. Parameters ---------- x : array_like Input array :math:`\mathbf{x}` axis : `None` or int or tuple of ints, optional (default None)...
def __lock_location(self) -> None: """ Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer. """ if not self._is_active: if ...
Attempts to lock the location used by this writer. Will raise an error if the location is already locked by another writer. Will do nothing if the location is already locked by this writer.
def start_stack(self, stack): """启动服务组 启动服务组中的所有停止状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息 ...
启动服务组 启动服务组中的所有停止状态的服务。 Args: - stack: 服务所属的服务组名称 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def friendly_type_name(raw_type: typing.Type) -> str: """ Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string """ try: return _TRANSLATE_TYPE[raw_type] except KeyError: LOGGER.error('unmanaged value type: %s', raw...
Returns a user-friendly type name :param raw_type: raw type (str, int, ...) :return: user friendly type as string
def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None): """ - Parse HTML and get miniDOM - Extract CSS informations, add default CSS, parse CSS - Handle the document DOM itself and build reportlab story - Return Context object """ global CSSAttrCache C...
- Parse HTML and get miniDOM - Extract CSS informations, add default CSS, parse CSS - Handle the document DOM itself and build reportlab story - Return Context object
def set_range(self, minimum, maximum): """ Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)...
Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)
def write_comment(fh, comment): """ Writes a comment to the file in Java properties format. Newlines in the comment text are automatically turned into a continuation of the comment by adding a "#" to the beginning of each line. :param fh: a writable file-like object :param comment: comment strin...
Writes a comment to the file in Java properties format. Newlines in the comment text are automatically turned into a continuation of the comment by adding a "#" to the beginning of each line. :param fh: a writable file-like object :param comment: comment string to write
def forward_backward(self, data_batch): """A convenient function that calls both ``forward`` and ``backward``.""" self.forward(data_batch, is_train=True) self.backward()
A convenient function that calls both ``forward`` and ``backward``.
def get_build_configuration_set_raw(id=None, name=None): """ Get a specific BuildConfigurationSet by name or ID """ found_id = common.set_id(pnc_api.build_group_configs, id, name) response = utils.checked_api_call(pnc_api.build_group_configs, 'get_specific', id=found_id) if response: ret...
Get a specific BuildConfigurationSet by name or ID
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of BinaryComposition via the visitor pattern.""" new_left = self.left.visit_and_update(visitor_fn) new_right = self.right.visit_and_update(visitor_fn) if new_left is not self.left or new_right is not self.r...
Create an updated version (if needed) of BinaryComposition via the visitor pattern.
def hr(color): """ Colored horizontal rule printer/logger factory. The resulting function prints an entire terminal row with the given symbol repeated. It's a terminal version of the HTML ``<hr/>``. """ logger = log(color) return lambda symbol: logger(symbol * terminal_size.usable_width)
Colored horizontal rule printer/logger factory. The resulting function prints an entire terminal row with the given symbol repeated. It's a terminal version of the HTML ``<hr/>``.
async def revoke_cred(self, rr_id: str, cr_id) -> int: """ Revoke credential that input revocation registry identifier and credential revocation identifier specify. Return (epoch seconds) time of revocation. Raise AbsentTails if no tails file is available for input revocation r...
Revoke credential that input revocation registry identifier and credential revocation identifier specify. Return (epoch seconds) time of revocation. Raise AbsentTails if no tails file is available for input revocation registry identifier. Raise WalletState for closed wallet. Ra...
def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8): """Concordance index for right-censored data The concordance index is defined as the proportion of all comparable pairs in which the predictions and outcomes are concordant. Samples are comparable if for at least one...
Concordance index for right-censored data The concordance index is defined as the proportion of all comparable pairs in which the predictions and outcomes are concordant. Samples are comparable if for at least one of them an event occurred. If the estimated risk is larger for the sample with a higher ...
def run(self): """Launch filtering, sorting and paging to output results.""" query = self.query # count before filtering self.cardinality = query.add_columns(self.columns[0].sqla_expr).count() self._set_column_filter_expressions() self._set_global_filter_expression() ...
Launch filtering, sorting and paging to output results.
def walk_trie(dicts, w, q, A): """ Helper function for traversing the word trie. It simultaneously keeps track of the active Automaton state, producing the intersection of the given Automaton and the trie (which is equivalent to a DFA). Once an invalid "terminating" state is reached, the children n...
Helper function for traversing the word trie. It simultaneously keeps track of the active Automaton state, producing the intersection of the given Automaton and the trie (which is equivalent to a DFA). Once an invalid "terminating" state is reached, the children nodes are immediately dismissed from the...
def diagonal_neural_gpu(inputs, hparams, name=None): """Improved Neural GPU as in https://arxiv.org/abs/1702.08727.""" with tf.variable_scope(name, "diagonal_neural_gpu"): def step(state_tup, inp): """Single step of the improved Neural GPU.""" state, _ = state_tup x = state for layer in...
Improved Neural GPU as in https://arxiv.org/abs/1702.08727.
def alias_proficiency(self, proficiency_id, alias_id): """Adds an ``Id`` to a ``Proficiency`` for the purpose of creating compatibility. The primary ``Id`` of the ``Proficiency`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a ...
Adds an ``Id`` to a ``Proficiency`` for the purpose of creating compatibility. The primary ``Id`` of the ``Proficiency`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another proficiency, it is reassigned to the gi...
def read(self, n=-1): """Read up to n items (bytes/chars) from the lob and return them. If n is -1 then all available data is returned. Might trigger further loading of data from the database if the number of items requested for reading is larger than what is currently buffered. ...
Read up to n items (bytes/chars) from the lob and return them. If n is -1 then all available data is returned. Might trigger further loading of data from the database if the number of items requested for reading is larger than what is currently buffered.
def init_log_config(handler=None): """Set up the application logging (not to be confused with check loggers). """ for applog in lognames.values(): # propagate except for root app logger 'linkcheck' propagate = (applog != LOG_ROOT) configdict['loggers'][applog] = dict(level='INFO', pr...
Set up the application logging (not to be confused with check loggers).
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computatio...
def add(self, name, value): """ Append a value to multiple value parameter. """ clone = self._clone() clone._qsl = [p for p in self._qsl if not(p[0] == name and p[1] == value)] clone._qsl.append((name, value,)) return clone
Append a value to multiple value parameter.
def save(self): """ save or update this cluster in Ariane Server :return: """ LOGGER.debug("Cluster.save") post_payload = {} consolidated_containers_id = [] if self.id is not None: post_payload['clusterID'] = self.id if self.name is n...
save or update this cluster in Ariane Server :return:
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: smart_class_parameters /api/puppetclasses/:puppetclass_id/smart_class_parameters Otherwise, call ``super``. """ i...
Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: smart_class_parameters /api/puppetclasses/:puppetclass_id/smart_class_parameters Otherwise, call ``super``.
def _make_version(major, minor, micro, releaselevel, serial): """Create a readable version string from version_info tuple components.""" assert releaselevel in ['alpha', 'beta', 'candidate', 'final'] version = "%d.%d" % (major, minor) if micro: version += ".%d" % (micro,) if releaselevel != ...
Create a readable version string from version_info tuple components.
def handleDetailDblClick( self, item ): """ Handles when a detail item is double clicked on. :param item | <QTreeWidgetItem> """ if ( isinstance(item, XOrbRecordItem) ): self.emitRecordDoubleClicked(item.record())
Handles when a detail item is double clicked on. :param item | <QTreeWidgetItem>
def is_hermitian( matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool: """Determines if a matrix is approximately Hermitian. A matrix is Hermitian if it's square and equal to its adjoint. Args: matrix: The matrix to check. rtol: The per-ma...
Determines if a matrix is approximately Hermitian. A matrix is Hermitian if it's square and equal to its adjoint. Args: matrix: The matrix to check. rtol: The per-matrix-entry relative tolerance on equality. atol: The per-matrix-entry absolute tolerance on equality. Returns: ...
def update_refs(self, ref_updates, repository_id, project=None, project_id=None): """UpdateRefs. Creating, updating, or deleting refs(branches). :param [GitRefUpdate] ref_updates: List of ref updates to attempt to perform :param str repository_id: The name or ID of the repository. ...
UpdateRefs. Creating, updating, or deleting refs(branches). :param [GitRefUpdate] ref_updates: List of ref updates to attempt to perform :param str repository_id: The name or ID of the repository. :param str project: Project ID or project name :param str project_id: ID or name of...
def start(self): """Start the job. This will begin pulling tasks from the taskmaster and executing them, and return when there are no more tasks. If a task fails to execute (i.e. execute() raises an exception), then the job will stop.""" while True: task = se...
Start the job. This will begin pulling tasks from the taskmaster and executing them, and return when there are no more tasks. If a task fails to execute (i.e. execute() raises an exception), then the job will stop.
def _prt_line_detail(self, prt, line, lnum=""): """Print each field and its value.""" data = zip(self.flds, line.split('\t')) txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)] prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt)))
Print each field and its value.
def consume_keys_asynchronous_processes(self): """ Work through the keys to look up asynchronously using multiple processes """ print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n") jobs = multiprocessing.cpu_count()*4 if (multiproc...
Work through the keys to look up asynchronously using multiple processes
def SetAlpha(self, alpha): ''' Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: ''' self._AlphaChannel = alpha * 255 if self._AlphaChannel is not None: self.MasterFrame.SetTransparent(self._AlphaCh...
Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return:
def is_valid_address(self, *args, **kwargs): """ check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool] ...
check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool]
def inter(a, b): """ Intersect two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inter_c.html :param a: First input set. :type a: spiceypy.utils.support_types.SpiceCell :param b: Second input set. :type b: spiceypy.utils.support_types.Sp...
Intersect two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inter_c.html :param a: First input set. :type a: spiceypy.utils.support_types.SpiceCell :param b: Second input set. :type b: spiceypy.utils.support_types.SpiceCell :return: Intersec...
def output(self, out_file): """Write the converted entries to out_file""" self.out_file = out_file out_file.write('event: ns : Nanoseconds\n') out_file.write('events: ns\n') self._output_summary() for entry in sorted(self.entries, key=_entry_sort_key): self._o...
Write the converted entries to out_file
def get_runs(project_name): """ Returns a dict of runs present in project. :return: dict -> {<int_keys>: <project_name>} """ conn, c = open_data_base_connection() try: c.execute("""SELECT run_name FROM {}""".format(project_name + "_run_table")) run_names = np.array(c.fetchall())....
Returns a dict of runs present in project. :return: dict -> {<int_keys>: <project_name>}
def _set_suppress_arp(self, v, load=False): """ Setter method for suppress_arp, mapped from YANG variable /bridge_domain/suppress_arp (container) If this variable is read-only (config: false) in the source YANG file, then _set_suppress_arp is considered as a private method. Backends looking to popul...
Setter method for suppress_arp, mapped from YANG variable /bridge_domain/suppress_arp (container) If this variable is read-only (config: false) in the source YANG file, then _set_suppress_arp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._...
def _dos2unix_cygwin(self, file_path): """ Use cygwin to convert file to unix format """ dos2unix_cmd = \ [os.path.join(self._cygwin_bin_location, "dos2unix.exe"), self._get_cygwin_path(file_path)] process = Popen(dos2unix_cmd, std...
Use cygwin to convert file to unix format
def _push_to_list(lst, func_name, char, line, offset, first_arg_pos, first_item, in_list_literal, lead_spaces, options=None): """ _push_to_list(lst : [str], func_name : str, char : str, line : int, offset : int, first_arg_pos :int , first_item : int, in_li...
_push_to_list(lst : [str], func_name : str, char : str, line : int, offset : int, first_arg_pos :int , first_item : int, in_list_literal : bool, lead_spaces : int, options : str) Called when an opening bracket is encountered. A hash containing the necessary data ...
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset o...
Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples
def instructions(self): """ Retrieve the instructions for the rule. """ if self._instructions is None: # Compile the rule into an Instructions instance; we do # this lazily to amortize the cost of the compilation, # then cache that result for efficien...
Retrieve the instructions for the rule.
def checkAndCreate(self, key, payload, hostgroupConf, hostgroupParent, puppetClassesId): """ Function checkAndCreate check And Create procedure for an hostgroup - check the hostgroup is not existing - create the hostgro...
Function checkAndCreate check And Create procedure for an hostgroup - check the hostgroup is not existing - create the hostgroup - Add puppet classes from puppetClassesId - Add params from hostgroupConf @param key: The hostgroup name or ID @param payload: The des...
def text(self,txt): """ Print Utf8 encoded alpha-numeric text """ if not txt: return try: txt = txt.decode('utf-8') except: try: txt = txt.decode('utf-16') except: pass self.extra_chars = 0 ...
Print Utf8 encoded alpha-numeric text
def batch_iterable(l, n): ''' Chunks iterable into n sized batches Solution from: http://stackoverflow.com/questions/1915170/split-a-generator-iterable-every-n-items-in-python-splitevery''' i = iter(l) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
Chunks iterable into n sized batches Solution from: http://stackoverflow.com/questions/1915170/split-a-generator-iterable-every-n-items-in-python-splitevery
def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) # If the filename a...
Returns a filename that's free on the target storage system, and available for new content to be written to.
def create_user_pool(PoolName=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, AliasAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfiguration=None, Sms...
Creates a new Amazon Cognito user pool and sets the password policy for the pool. See also: AWS API Documentation :example: response = client.create_user_pool( PoolName='string', Policies={ 'PasswordPolicy': { 'MinimumLength': 123, 'RequireUp...
def read_mol2(self, path, columns=None): """Reads Mol2 files (unzipped or gzipped) from local drive Note that if your mol2 file contains more than one molecule, only the first molecule is loaded into the DataFrame Attributes ---------- path : str Path to the...
Reads Mol2 files (unzipped or gzipped) from local drive Note that if your mol2 file contains more than one molecule, only the first molecule is loaded into the DataFrame Attributes ---------- path : str Path to the Mol2 file in .mol2 format or gzipped format (.mol2....
def resetVector(x1, x2): """ Copies the contents of vector x1 into vector x2. @param x1 (array) binary vector to be copied @param x2 (array) binary vector where x1 is copied """ size = len(x1) for i in range(size): x2[i] = x1[i]
Copies the contents of vector x1 into vector x2. @param x1 (array) binary vector to be copied @param x2 (array) binary vector where x1 is copied
def prepare_rows(table): """ Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]] """ num_columns = max(len(row) for row in...
Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]]
def valuegetter(*fieldspecs, **kwargs): """ Modelled after `operator.itemgetter`. Takes a variable number of specs and returns a function, which applied to any `pymarc.Record` returns the matching values. Specs are in the form `field` or `field.subfield`, e.g. `020` or `020.9`. Example: ...
Modelled after `operator.itemgetter`. Takes a variable number of specs and returns a function, which applied to any `pymarc.Record` returns the matching values. Specs are in the form `field` or `field.subfield`, e.g. `020` or `020.9`. Example: >>> from marcx import Record, valuegetter >>>...
def get_org(self, organization_name=''): """ Retrieves an organization via given org name. If given empty string, prompts user for an org name. """ self.organization_name = organization_name if(organization_name == ''): self.organization_name = raw_input('Orga...
Retrieves an organization via given org name. If given empty string, prompts user for an org name.
def stream(command, stdin=None, env=os.environ, timeout=None): """ Yields a generator of a command's output. For line oriented commands only. Args: command (str or list): a command without pipes. If it's not a list, ``shlex.split`` is applied. stdin (file like object): stream to...
Yields a generator of a command's output. For line oriented commands only. Args: command (str or list): a command without pipes. If it's not a list, ``shlex.split`` is applied. stdin (file like object): stream to use as the command's standard input. env (dict): The environment i...
def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} if 'final' in _dict or 'final_results' in _dict: args['final_results'] = _dict.get('final') or _dict.get( 'final_results') else: raise V...
Initialize a SpeechRecognitionResult object from a json dictionary.
def refkeys(self,fields): "returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet." # todo doc: better explanation of what refkeys are and how fields plays in dd=collections.defaultdict(list) if any(f not in self.REFKEYS for f in fields): raise ValueError(fields,'not all...
returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet.
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen...
Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int...
def to_result(self): """Convert to the Linter.run return value""" text = [self.text] if self.note: text.append(self.note) return { 'lnum': self.line_num, 'col': self.column, 'text': ' - '.join(text), 'type': self.types.get(self...
Convert to the Linter.run return value
def get_item_list_by_name(self, item_list_name, category='own'): """ Retrieve an item list from the server as an ItemList object :type item_list_name: String :param item_list_name: name of the item list to retrieve :type category: String :param category: the category of lists to...
Retrieve an item list from the server as an ItemList object :type item_list_name: String :param item_list_name: name of the item list to retrieve :type category: String :param category: the category of lists to fetch. At the time of writing, supported values are "own" and "s...
def trim_docstring(docstring): """Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed. """ if not doc...
Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed.
def _getFirstOnBit(self, input): """ Return the bit offset of the first bit to be set in the encoder output. For periodic encoders, this can be a negative number when the encoded output wraps around. """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: if input < self.m...
Return the bit offset of the first bit to be set in the encoder output. For periodic encoders, this can be a negative number when the encoded output wraps around.
def missing_datetimes(self, finite_datetimes): """ Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow. """ return [d ...
Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow.
def make_ranges(self, file_url): """ Divides file_url size into an array of ranges to be downloaded by workers. :param: file_url: ProjectFileUrl: file url to download :return: [(int,int)]: array of (start, end) tuples """ size = file_url.size bytes_per_chunk = sel...
Divides file_url size into an array of ranges to be downloaded by workers. :param: file_url: ProjectFileUrl: file url to download :return: [(int,int)]: array of (start, end) tuples
def standardDeviation2d(img, ksize=5, blurred=None): ''' calculate the spatial resolved standard deviation for a given 2d array ksize -> kernel size blurred(optional) -> with same ksize gaussian filtered image setting this parameter reduces processing time ...
calculate the spatial resolved standard deviation for a given 2d array ksize -> kernel size blurred(optional) -> with same ksize gaussian filtered image setting this parameter reduces processing time