code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update(self, data): '''Updates object information with live data (if live data has different values to stored object information). Changes will be automatically applied, but not persisted in the database. Call `db.session.add(elb)` manually to commit the changes to the DB. A...
Updates object information with live data (if live data has different values to stored object information). Changes will be automatically applied, but not persisted in the database. Call `db.session.add(elb)` manually to commit the changes to the DB. Args: # data (:obj:) AWS...
def remove(self, env_path): """Remove metadata for a given virtualenv from cache.""" with filelock(self.lockpath): cache = self._read_cache() logger.debug("Removing virtualenv from cache: %s" % env_path) lines = [ line for line in cache ...
Remove metadata for a given virtualenv from cache.
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
Check if a data block has a valid soma Returns: CheckResult with result
def nodes(self) -> List[str]: """Return the list of nodes configured in the scenario's yaml. Should the scenario use version 1, we check if there is a 'setting'. If so, we derive the list of nodes from this dictionary, using its 'first', 'last' and 'template' keys. Should any of these k...
Return the list of nodes configured in the scenario's yaml. Should the scenario use version 1, we check if there is a 'setting'. If so, we derive the list of nodes from this dictionary, using its 'first', 'last' and 'template' keys. Should any of these keys be missing, we throw an appro...
def jsonld(client, datasets): """Format datasets as JSON-LD.""" from renku.models._json import dumps from renku.models._jsonld import asjsonld data = [ asjsonld( dataset, basedir=os.path.relpath( '.', start=str(dataset.__reference__.parent) ) ...
Format datasets as JSON-LD.
def get_buffer(self): """Get buffer which needs to be bulked to elasticsearch""" # Get sources for documents which are in Elasticsearch # and they are not in local buffer if self.doc_to_update: self.update_sources() ES_buffer = self.action_buffer self.clean_...
Get buffer which needs to be bulked to elasticsearch
def join(self): '''Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is ...
Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the...
def query(number, domains, resolver=None): """Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.']) """ if resolver is None: resolver = dns.resolver.get_default_resolver() for domain in domains: if isi...
Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])
def _sort_r(sorted, processed, key, deps, dependency_tree): """Recursive topological sort implementation.""" if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug('"%s" not found, ski...
Recursive topological sort implementation.
def from_shorthand(shorthand_string, slash=None): """Take a chord written in shorthand and return the notes in the chord. The function can recognize triads, sevenths, sixths, ninths, elevenths, thirteenths, slashed chords and a number of altered chords. The second argument should not be given and is o...
Take a chord written in shorthand and return the notes in the chord. The function can recognize triads, sevenths, sixths, ninths, elevenths, thirteenths, slashed chords and a number of altered chords. The second argument should not be given and is only used for a recursive call when a slashed chord or...
def _calculate_period(self, vals): ''' calculate the sampling period in seconds ''' if len(vals) < 4: return None if self.firmware['major'] < 16: return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6 else: return self._calculate...
calculate the sampling period in seconds
def set_label_elements(self, wanted_label_elements): """ Set one or more label elements based on at least one of the others """ if isinstance(wanted_label_elements, str): wanted_label_elements = [wanted_label_elements] # Figure out which desired label element...
Set one or more label elements based on at least one of the others
def keyPressEvent(self, event): """Override Qt method""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
Override Qt method
def from_curvilinear(cls, x, y, z, formatter=numpy_formatter): """Construct a contour generator from a curvilinear grid. Note ---- This is an alias for the default constructor. Parameters ---------- x : array_like x coordinates of each point in `z`. ...
Construct a contour generator from a curvilinear grid. Note ---- This is an alias for the default constructor. Parameters ---------- x : array_like x coordinates of each point in `z`. Must be the same size as `z`. y : array_like y coordi...
def token(self): """ get the token """ header = self.default_headers.get('Authorization', '') prefex = 'Bearer ' if header.startswith(prefex): token = header[len(prefex):] else: token = header return token
get the token
def monitorSearchJob(self): """ Parameters: ---------------------------------------------------------------------- retval: nothing """ assert self.__searchJob is not None jobID = self.__searchJob.getJobID() startTime = time.time() lastUpdateTime = datetime.now() # Moni...
Parameters: ---------------------------------------------------------------------- retval: nothing
def series_with_permutation(self, other): """Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels) "...
Compute the series product with another channel permutation circuit Args: other (CPermutation): Returns: Circuit: The composite permutation circuit (could also be the identity circuit for n channels)
def _calcDistance(self, inputPattern, distanceNorm=None): """Calculate the distances from inputPattern to all stored patterns. All distances are between 0.0 and 1.0 :param inputPattern The pattern from which distances to all other patterns are calculated :param distanceNorm Degree of the dista...
Calculate the distances from inputPattern to all stored patterns. All distances are between 0.0 and 1.0 :param inputPattern The pattern from which distances to all other patterns are calculated :param distanceNorm Degree of the distance norm
def build_data_set(self): "Construct a sequence of name/value pairs from controls" data = {} for field in self.fields: if field.name:# and field.enabled: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! val = field.get_value() if val is None: ...
Construct a sequence of name/value pairs from controls
def parse_if_range_header(value): """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7 """ if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(d...
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7
def cast_scalar_to_array(shape, value, dtype=None): """ create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with v...
create np.ndarray of specified shape and dtype, filled with values Parameters ---------- shape : tuple value : scalar value dtype : np.dtype, optional dtype to coerce Returns ------- ndarray of shape, filled with value, of specified / inferred dtype
def run_tasks(header, tasks): """Run a group of tasks with a header, footer and success/failure messages. Args: header: A message to print in the header bar before the tasks are run. tasks: A list of tuples containing a task title, a task, and a weight. If the tuple only contains tw...
Run a group of tasks with a header, footer and success/failure messages. Args: header: A message to print in the header bar before the tasks are run. tasks: A list of tuples containing a task title, a task, and a weight. If the tuple only contains two values, the weight is assumed to be...
def mouse_move(self, event): """ The following gets back coordinates of the mouse on the canvas. """ if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE): self.posX = event.xdata self.posY = event.ydata self.graphic_target(self.posX, self.po...
The following gets back coordinates of the mouse on the canvas.
def openstack_upgrade_available(package): """ Determines if an OpenStack upgrade is available from installation source, based on version of installed package. :param package: str: Name of installed package. :returns: bool: : Returns True if configured installation source offers ...
Determines if an OpenStack upgrade is available from installation source, based on version of installed package. :param package: str: Name of installed package. :returns: bool: : Returns True if configured installation source offers a newer version of package.
def sli_run(parameters=object(), fname='microcircuit.sli', verbosity='M_ERROR'): ''' Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli c...
Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli codes to be executed verbosity : 'str', nest verbosity flag
def decode_cf_datetime(num_dates, units, calendar=None, use_cftime=None): """Given an array of numeric dates in netCDF format, convert it into a numpy array of date time objects. For standard (Gregorian) calendars, this function uses vectorized operations, which makes it much faster than cftime.num2dat...
Given an array of numeric dates in netCDF format, convert it into a numpy array of date time objects. For standard (Gregorian) calendars, this function uses vectorized operations, which makes it much faster than cftime.num2date. In such a case, the returned array will be of type np.datetime64. Not...
def remove_site(name): ''' Delete a website from IIS. :param str name: The IIS site name. Usage: .. code-block:: yaml defaultwebsite-remove: win_iis.remove_site: - name: Default Web Site ''' ret = {'name': name, 'changes': {}, 'r...
Delete a website from IIS. :param str name: The IIS site name. Usage: .. code-block:: yaml defaultwebsite-remove: win_iis.remove_site: - name: Default Web Site
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int: """The maximum number of qubits to be acquainted with each other.""" if isinstance(obj, circuits.Circuit): if not is_acquaintance_strategy(obj): raise TypeError('not is_acquaintance_strategy(circuit)') ret...
The maximum number of qubits to be acquainted with each other.
def _split_keys_v1(joined): """ Split two keys out a string created by _join_keys_v1. """ left, _, right = joined.partition('::') return _decode_v1(left), _decode_v1(right)
Split two keys out a string created by _join_keys_v1.
def __construct_lda_model(self): """Method to create LDA model to procure list of topics from. We do that by first fetching the descriptions of repositories user has shown interest in. We tokenize the hence fetched descriptions to procure list of cleaned tokens by dropping all the stop ...
Method to create LDA model to procure list of topics from. We do that by first fetching the descriptions of repositories user has shown interest in. We tokenize the hence fetched descriptions to procure list of cleaned tokens by dropping all the stop words and language names from it. ...
def _read_mode_sec(self, size, kind): """Read options with security info. Positional arguments: size - int, length of option kind - int, 130 (SEC )/ 133 (ESEC) Returns: * dict -- extracted option with security info (E/SEC) Structure of these options...
Read options with security info. Positional arguments: size - int, length of option kind - int, 130 (SEC )/ 133 (ESEC) Returns: * dict -- extracted option with security info (E/SEC) Structure of these options: * [RFC 1108] Security (SEC) ...
def update(self, ip_address=values.unset, friendly_name=values.unset, cidr_prefix_length=values.unset): """ Update the IpAddressInstance :param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP addres...
Update the IpAddressInstance :param unicode ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param unicode friendly_name: A human readable descriptive text for this re...
def query_array(ncfile, name) -> numpy.ndarray: """Return the data of the variable with the given name from the given NetCDF file. The following example shows that |query_array| returns |nan| entries to represent missing values even when the respective NetCDF variable defines a different fill value...
Return the data of the variable with the given name from the given NetCDF file. The following example shows that |query_array| returns |nan| entries to represent missing values even when the respective NetCDF variable defines a different fill value: >>> from hydpy import TestIO >>> from hydpy....
def __generate_key(self, config): """ Generate the ssh key, and return the ssh config location """ cwd = config.get('ssh_path', self._install_directory()) if config.is_affirmative('create', default="yes"): if not os.path.exists(cwd): os.makedirs(cwd) ...
Generate the ssh key, and return the ssh config location
def _remote_chmod(self, paths, mode, sudoable=False): """ Issue an asynchronous set_file_mode() call for every path in `paths`, then format the resulting return value list with fake_shell(). """ LOG.debug('_remote_chmod(%r, mode=%r, sudoable=%r)', paths, mode, s...
Issue an asynchronous set_file_mode() call for every path in `paths`, then format the resulting return value list with fake_shell().
def html(text, lazy_images=False): """ To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the ...
To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the LazyImageExtension :return:
def t_whitespace_or_comment(self, s): r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)' if '#' in s: # We have a comment matches = re.match('(\s+)(.*[\n]?)', s) if matches and self.is_newline: self.handle_indent_dedent(matches.group(1)) s = matches...
r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)
def _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0): """ Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_...
Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_{jr}(\mathcal{R}_{k})_{rm} (\mathcal{R}_{l})_{nq} (\rho_0)_q where :math:`\mathcal{R}_{k}` is the ...
def logn_correlated_rate(parent_rate, branch_length, autocorrel_param, size=1): """ The log of the descendent rate, ln(Rd), is ~ N(mu, bl*ac), where the variance = bl*ac = branch_length * autocorrel_param, and mu is set so that E[Rd] = Rp: E[X] where ln(X) ~ N(mu, sigma^2) = exp(mu+(1/2)*sigma_sq) ...
The log of the descendent rate, ln(Rd), is ~ N(mu, bl*ac), where the variance = bl*ac = branch_length * autocorrel_param, and mu is set so that E[Rd] = Rp: E[X] where ln(X) ~ N(mu, sigma^2) = exp(mu+(1/2)*sigma_sq) so Rp = exp(mu+(1/2)*bl*ac), ln(Rp) = mu + (1/2)*bl*ac, ln(Rp) - (1/2)*bl*ac = mu...
def QA_fetch_lhb(date, db=DATABASE): '获取某一天龙虎榜数据' try: collections = db.lhb return pd.DataFrame([item for item in collections.find( {'date': date}, {"_id": 0})]).set_index('code', drop=False).sort_index() except Exception as e: raise e
获取某一天龙虎榜数据
def remove_bucket_list_item(self, id, collection, item): """ Removes an item from the bucket list Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. item: the bucket list item to remove Returns: ...
Removes an item from the bucket list Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. item: the bucket list item to remove Returns: The mongodb result
def move_item_into_viewport(self, item): """Causes the `item` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item` is not a `StateView`, the parental `StateView` is moved into the viewport. :param Sta...
Causes the `item` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item` is not a `StateView`, the parental `StateView` is moved into the viewport. :param StateView | ConnectionView | PortView item: The item to...
def evaluate_postfix(tokens): """ Given a list of evaluatable tokens in postfix format, calculate a solution. """ stack = [] for token in tokens: total = None if is_int(token) or is_float(token) or is_constant(token): stack.append(token) elif is_unary(token)...
Given a list of evaluatable tokens in postfix format, calculate a solution.
def insert_device_filter(self, position, filter_p): """Inserts the given USB device to the specified position in the list of filters. Positions are numbered starting from 0. If the specified position is equal to or greater than the number of elements in the list, the fil...
Inserts the given USB device to the specified position in the list of filters. Positions are numbered starting from 0. If the specified position is equal to or greater than the number of elements in the list, the filter is added to the end of the collection. ...
def align(args): """ %prog align database.fasta read1.fq read2.fq Wrapper for `gsnap` single-end or paired-end, depending on the number of args. """ from jcvi.formats.fastq import guessoffset p = OptionParser(align.__doc__) p.add_option("--rnaseq", default=False, action="store_true", ...
%prog align database.fasta read1.fq read2.fq Wrapper for `gsnap` single-end or paired-end, depending on the number of args.
def is_url(): """ Validates that a fields value is a valid URL. """ # Stolen from Django regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost......
Validates that a fields value is a valid URL.
def omim(context, api_key, institute): """ Update the automate generated omim gene panel in the database. """ LOG.info("Running scout update omim") adapter = context.obj['adapter'] api_key = api_key or context.obj.get('omim_api_key') if not api_key: LOG.warning("Please provide a...
Update the automate generated omim gene panel in the database.
def email(self, comment, content_object, request): """ Overwritten for a better email notification. """ if not self.email_notification: return send_comment_posted(comment, request)
Overwritten for a better email notification.
def non_decreasing(values): """True if values are not decreasing.""" return all(x <= y for x, y in zip(values, values[1:]))
True if values are not decreasing.
def _convert_to_hashable(data, types=True): r""" Converts `data` into a hashable byte representation if an appropriate hashing function is known. Args: data (object): ordered data with structure types (bool): include type prefixes in the hash Returns: tuple(bytes, bytes): p...
r""" Converts `data` into a hashable byte representation if an appropriate hashing function is known. Args: data (object): ordered data with structure types (bool): include type prefixes in the hash Returns: tuple(bytes, bytes): prefix, hashable: a prefix hinting th...
def match(self, context, line): """Match code lines prefixed with a variety of keywords.""" return line.kind == 'code' and line.partitioned[0] in self._both
Match code lines prefixed with a variety of keywords.
def flush(self, meta=None): '''Flush all model keys from the database''' pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern('%s*' % pattern)
Flush all model keys from the database
def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: # Wait a while for all running greenlets to exit, and ...
Wait for transfer to exit, raising errors as necessary.
def r_passage(self, objectId, subreference, lang=None): """ Retrieve the text of the passage :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :param subreference: Reference identifier :type...
Retrieve the text of the passage :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :param subreference: Reference identifier :type subreference: str :return: Template, collections metadata a...
def register_annotype_converter(cls, types, is_array=False, is_mapping=False): # type: (Union[Sequence[type], type], bool, bool) -> Any """Register this class as a converter for Anno instances""" if not isinstance(types, Sequence): types = [types] ...
Register this class as a converter for Anno instances
def norm(self): """ Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2 """ tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2 return tmp**0.5
Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2
def get_redirect_url(self, url, encrypt_code, card_id): """ 获取卡券跳转外链 """ from wechatpy.utils import WeChatSigner code = self.decrypt_code(encrypt_code) signer = WeChatSigner() signer.add_data(self.secret) signer.add_data(code) signer.add_data(car...
获取卡券跳转外链
def write_back_register(self, reg, val): """ Sync register state from Manticore -> Unicorn""" if self.write_backs_disabled: return if issymbolic(val): logger.warning("Skipping Symbolic write-back") return if reg in self.flag_registers: self...
Sync register state from Manticore -> Unicorn
def filter(args): """ %prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features """ p = OptionParser(filter.__...
%prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features
def apply_injectables(self, targets): """Given an iterable of `Target` instances, apply their transitive injectables.""" target_types = {type(t) for t in targets} target_subsystem_deps = {s for s in itertools.chain(*(t.subsystems() for t in target_types))} for subsystem in target_subsystem_deps: #...
Given an iterable of `Target` instances, apply their transitive injectables.
def apply_clicked(self, button): """Triggered when the Apply button in the source editor is clicked. """ if isinstance(self.model.state, LibraryState): logger.warning("It is not allowed to modify libraries.") self.view.set_text("") return # Ugly work...
Triggered when the Apply button in the source editor is clicked.
def storage_expansion(network, basemap=True, scaling=1, filename=None): """ Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from pow...
Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, fi...
def getGerritChanges(props): """ Get the gerrit changes This method could be overridden if really needed to accommodate for other custom steps method for fetching gerrit changes. :param props: an IProperty :return: (optionally via deferred) a list of dictionary...
Get the gerrit changes This method could be overridden if really needed to accommodate for other custom steps method for fetching gerrit changes. :param props: an IProperty :return: (optionally via deferred) a list of dictionary with at list change_id, ...
def find_by_id(self, repoid): """ Returns the repo with the specified <repoid> """ for row in self.jsondata: if repoid == row["repoid"]: return self._infofromdict(row)
Returns the repo with the specified <repoid>
def emd2(a, b, M, processes=multiprocessing.cpu_count(), numItermax=100000, log=False, return_matrix=False): """Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma...
Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed i...
def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug ...
Get the template which is at the given name
def spi_ss_polarity(self, polarity): """Change the ouput polarity on the SS line. Please note, that this only affects the master functions. """ ret = api.py_aa_spi_master_ss_polarity(self.handle, polarity) _raise_error_if_negative(ret)
Change the ouput polarity on the SS line. Please note, that this only affects the master functions.
def validate_email(self, email): """ Validate if email exists and requires a verification. `validate_email` will set a `user` attribute on the instance allowing the view to send an email confirmation. """ try: self.user = User.objects.get_by_natural_key(email...
Validate if email exists and requires a verification. `validate_email` will set a `user` attribute on the instance allowing the view to send an email confirmation.
def get_capability_report(self, raw=True, cb=None): """ This method retrieves the Firmata capability report :param raw: If True, it either stores or provides the callback with a report as list. If False, prints a formatted report to the console :...
This method retrieves the Firmata capability report :param raw: If True, it either stores or provides the callback with a report as list. If False, prints a formatted report to the console :param cb: Optional callback reference to receive a raw report :...
def parse_requestline(s): """ http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5 >>> parse_requestline('GET / HTTP/1.0') ('GET', '/', '1.0') >>> parse_requestline('post /testurl htTP/1.1') ('POST', '/testurl', '1.1') >>> parse_requestline('Im not a RequestLine') Traceback (most ...
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5 >>> parse_requestline('GET / HTTP/1.0') ('GET', '/', '1.0') >>> parse_requestline('post /testurl htTP/1.1') ('POST', '/testurl', '1.1') >>> parse_requestline('Im not a RequestLine') Traceback (most recent call last): ... Val...
def hash(self): """The hash value of the current revision""" if 'digest' not in self._p4dict: self._p4dict = self._connection.run(['fstat', '-m', '1', '-Ol', self.depotFile])[0] return self._p4dict['digest']
The hash value of the current revision
def styleInheritedFromParent(node, style): """ Returns the value of 'style' that is inherited from the parents of the passed-in node Warning: This method only considers presentation attributes and inline styles, any style sheets are ignored! """ parentNode = node.parentNode # retu...
Returns the value of 'style' that is inherited from the parents of the passed-in node Warning: This method only considers presentation attributes and inline styles, any style sheets are ignored!
def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False): """Sends scheduled messages. :param int, None priority: number to limit sending message by this priority. :param bool ignore_unknown_messengers: to silence UnknownMessengerError :param bool ...
Sends scheduled messages. :param int, None priority: number to limit sending message by this priority. :param bool ignore_unknown_messengers: to silence UnknownMessengerError :param bool ignore_unknown_message_types: to silence UnknownMessageTypeError :raises UnknownMessengerError: :raises UnknownM...
def _update_dPrxy(self): """Update `dPrxy`.""" super(ExpCM_fitprefs, self)._update_dPrxy() if 'zeta' in self.freeparams: tildeFrxyQxy = self.tildeFrxy * self.Qxy j = 0 zetaxterm = scipy.ndarray((self.nsites, N_CODON, N_CODON), dtype='float') zetay...
Update `dPrxy`.
def load_config(self, config): """Load the outputs section of the configuration file.""" # Limit the number of processes to display in the WebUI if config is not None and config.has_section('outputs'): logger.debug('Read number of processes to display in the WebUI') n = c...
Load the outputs section of the configuration file.
def depends_on(self, *keys): ''' Decorator that marks the wrapped as depending on specified provider keys. :param keys: Provider keys to mark as dependencies for wrapped :type keys: tuple :return: decorator :rtype: decorator ''' def decorator(wrapped): ...
Decorator that marks the wrapped as depending on specified provider keys. :param keys: Provider keys to mark as dependencies for wrapped :type keys: tuple :return: decorator :rtype: decorator
def swpool(agent, nnames, lenvals, names): """ Add a name to the list of agents to notify whenever a member of a list of kernel variables is updated. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/swpool_c.html :param agent: The name of an agent to be notified after updates. :type age...
Add a name to the list of agents to notify whenever a member of a list of kernel variables is updated. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/swpool_c.html :param agent: The name of an agent to be notified after updates. :type agent: str :param nnames: The number of variables to a...
def get_number_of_app_ports(app): """ Get the number of ports for the given app JSON. This roughly follows the logic in marathon-lb for finding app IPs/ports, although we are only interested in the quantity of ports an app should have and don't consider the specific IPs/ports of individual tasks: ...
Get the number of ports for the given app JSON. This roughly follows the logic in marathon-lb for finding app IPs/ports, although we are only interested in the quantity of ports an app should have and don't consider the specific IPs/ports of individual tasks: https://github.com/mesosphere/marathon-lb/bl...
def get_port_mappings(self, port=None): """ Get list of port mappings between container and host. The format of dicts is: {"HostIp": XX, "HostPort": YY}; When port is None - return all port mappings. The container needs to be running, otherwise this returns an empty list. ...
Get list of port mappings between container and host. The format of dicts is: {"HostIp": XX, "HostPort": YY}; When port is None - return all port mappings. The container needs to be running, otherwise this returns an empty list. :param port: int or None, container port :re...
def main(): """Main script handler. Returns: int: 0 for success, >1 error code """ logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s') try: cli() return 0 except LocationsError as error: print(error) return 2 except RuntimeError as er...
Main script handler. Returns: int: 0 for success, >1 error code
def drop(self, relation): """Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param...
Drop the named relation and cascade it appropriately to all dependent relations. Because dbt proactively does many `drop relation if exist ... cascade` that are noops, nonexistent relation drops cause a debug log and no other actions. :param str schema: The schema of the relati...
def from_outcars(cls, outcars, structures, **kwargs): """ Initializes an NEBAnalysis from Outcar and Structure objects. Use the static constructors, e.g., :class:`from_dir` instead if you prefer to have these automatically generated from a directory of NEB calculations. ...
Initializes an NEBAnalysis from Outcar and Structure objects. Use the static constructors, e.g., :class:`from_dir` instead if you prefer to have these automatically generated from a directory of NEB calculations. Args: outcars ([Outcar]): List of Outcar objects. Note that th...
def getItemWidth(self) -> int: """ Only for transactions derived from HArray :return: width of item in original array """ if not isinstance(self.dtype, HArray): raise TypeError() return (self.bitAddrEnd - self.bitAddr) // self.itemCnt
Only for transactions derived from HArray :return: width of item in original array
def get_settings(self): """Returns a mapping of UID -> setting """ settings = self.context.getAnalysisServicesSettings() mapping = dict(map(lambda s: (s.get("uid"), s), settings)) return mapping
Returns a mapping of UID -> setting
def console_load_asc(con: tcod.console.Console, filename: str) -> bool: """Update a console from a non-delimited ASCII `.asc` file.""" return bool( lib.TCOD_console_load_asc(_console(con), filename.encode("utf-8")) )
Update a console from a non-delimited ASCII `.asc` file.
def instance_config_path(cls, project, instance_config): """Return a fully-qualified instance_config string.""" return google.api_core.path_template.expand( "projects/{project}/instanceConfigs/{instance_config}", project=project, instance_config=instance_config, ...
Return a fully-qualified instance_config string.
def find(cls, *args, **kwargs): """ Returns all document dicts that pass the filter """ return list(cls.collection.find(*args, **kwargs))
Returns all document dicts that pass the filter
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order...
Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc.
def delete(self, tag, ref): """Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member wit...
Delete from the vgroup the member identified by its tag and reference number. Args:: tag tag of the member to delete ref reference number of the member to delete Returns:: None Only the link of the member with the vgroup is deleted. The me...
def _leaf_list_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle leaf-list statement.""" node = LeafListNode() node.type = DataType._resolve_type( stmt.find1("type", required=True), sctx) self._handle_child(node, stmt, sctx)
Handle leaf-list statement.
def _get_opt(config, key, option, opt_type): """Get an option from a configparser with the given type.""" for opt_key in [option, option.replace('-', '_')]: if not config.has_option(key, opt_key): continue if opt_type == bool: return config.getbool(key, opt_key) ...
Get an option from a configparser with the given type.
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``. """ for d in dict_list: ...
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a blank string, convert it to ``None``.
def add_raw(self, raw): """ Adds row aggregation state at the query :param raw: list of raw stages or a dict of raw stage :return: The current object """ if type(raw) == list: self._q += raw if type(raw) == dict: self._q.append(raw) ...
Adds row aggregation state at the query :param raw: list of raw stages or a dict of raw stage :return: The current object
def load_jws_from_request(req): """ This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from....
This function performs almost entirely bitjws authentication tasks. If valid bitjws message and signature headers are found, then the request will be assigned 'jws_header' and 'jws_payload' attributes. :param req: The flask request to load the jwt claim set from.
def add(self, docs, boost=None, fieldUpdates=None, commit=None, softCommit=False, commitWithin=None, waitFlush=None, waitSearcher=None, overwrite=None, handler='update'): """ Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field...
Adds or updates documents. Requires ``docs``, which is a list of dictionaries. Each key is the field name and each value is the value to index. Optionally accepts ``commit``. Default is ``None``. None signals to use default Optionally accepts ``softCommit``. Default is ``False``. ...
def get_reservations(self, sessionid, timeout=None): """Returns a list of location IDs and names.""" url = "{}{}".format(BASE_URL, "/reservations/") cookies = dict(sessionid=sessionid) try: resp = requests.get(url, timeout=timeout, cookies=cookies) except resp.except...
Returns a list of location IDs and names.
def between(self, other_user_id): """Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool """ params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.get(self.url, params=p...
Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool
def _EnvOpen(var, mode): """Open a file descriptor identified by an environment variable.""" value = os.getenv(var) if value is None: raise ValueError("%s is not set" % var) fd = int(value) # If running on Windows, convert the file handle to a C file descriptor; see: # https://groups.google.com/forum/...
Open a file descriptor identified by an environment variable.
def get_account_policy(region=None, key=None, keyid=None, profile=None): ''' Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy ''' conn = _get_conn(region=region, key=key, keyid=keyid, pr...
Get account policy for the AWS account. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.get_account_policy
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn): """ Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like enti...
Group a list of request payloads by topic+partition and send them to the leader broker for that partition using the supplied encode/decode functions Arguments: payloads: list of object-like entities with a topic (str) and partition (int) attribute; payloads with duplicate t...