code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
Processes a request_token request and returns the request token on success.
async def send_chat_action(self, chat_id: typing.Union[base.Integer, base.String], action: base.String) -> base.Boolean: """ Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less ...
Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). We only recommend using this method when a response from the bot will take ...
def proximal_convex_conj_l2(space, lam=1, g=None): r"""Proximal operator factory of the convex conj of the l2-norm/distance. Function for the proximal operator of the convex conjugate of the functional F where F is the l2-norm (or distance to g, if given):: F(x) = lam ||x - g||_2 with x and ...
r"""Proximal operator factory of the convex conj of the l2-norm/distance. Function for the proximal operator of the convex conjugate of the functional F where F is the l2-norm (or distance to g, if given):: F(x) = lam ||x - g||_2 with x and g elements in ``space``, scaling factor lam, and given ...
def resolve_profile(name, include_expired=False, include_name_record=False, hostport=None, proxy=None): """ Resolve a name to its profile. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4....
Resolve a name to its profile. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4. fetch and authenticate the JWT at each URL (abort if there are none) 5. extract the profile JSON and return tha...
def nolist(self, account): # pragma: no cover """ Remove an other account from any list of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=[], account=self)
Remove an other account from any list of this account
def is_file(cls, file): '''Return whether the file is likely CSS.''' peeked_data = wpull.string.printable_bytes( wpull.util.peek_file(file)).lower() if b'<html' in peeked_data: return VeryFalse if re.search(br'@import |color:|background[a-z-]*:|font[a-z-]*:', ...
Return whether the file is likely CSS.
def _derive_stereographic(): """Compute the formulae to cut-and-paste into the routine below.""" from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z') # The angles we'll need to rotate through. around_z = atan2(x_c, y_c) aroun...
Compute the formulae to cut-and-paste into the routine below.
def _read_regex(ctx: ReaderContext) -> Pattern: """Read a regex reader macro from the input stream.""" s = _read_str(ctx, allow_arbitrary_escapes=True) try: return langutil.regex_from_str(s) except re.error: raise SyntaxError(f"Unrecognized regex pattern syntax: {s}")
Read a regex reader macro from the input stream.
def process_request(self, num_pending, ports, request_blocking=False): '''port is the open port at the worker, num_pending is the num_pending of stack. A non-zero num_pending means that the worker is pending on something while looking for new job, so the worker should not be killed. ''' ...
port is the open port at the worker, num_pending is the num_pending of stack. A non-zero num_pending means that the worker is pending on something while looking for new job, so the worker should not be killed.
def invokeRunnable(self): """ Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction. """ runnable = self.runnable if runnable is None: self.deleteFromStore() else: try: self.runni...
Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction.
def gene_counts(self): """ Returns number of elements overlapping each gene name. Expects the derived class (VariantCollection or EffectCollection) to have an implementation of groupby_gene_name. """ return { gene_name: len(group) for (gene_name, g...
Returns number of elements overlapping each gene name. Expects the derived class (VariantCollection or EffectCollection) to have an implementation of groupby_gene_name.
def on_start(self): """Runs when the actor is started and schedules a status update """ logger.info('StatusReporter started.') # if configured not to report status then return immediately if self.config['status_update_interval'] == 0: logger.info('StatusReporter disab...
Runs when the actor is started and schedules a status update
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx): """Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python. """ import scipy.linalg.lapack ...
Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python.
def stop_archive(self, archive_id): """ Stops an OpenTok archive that is being recorded. Archives automatically stop recording after 90 minutes or when all clients have disconnected from the session being archived. @param [String] archive_id The archive ID of the archive you wa...
Stops an OpenTok archive that is being recorded. Archives automatically stop recording after 90 minutes or when all clients have disconnected from the session being archived. @param [String] archive_id The archive ID of the archive you want to stop recording. :rtype: The Archive objec...
def get(self, sid): """ Constructs a ReservationContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext """ return ReservationCo...
Constructs a ReservationContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext :rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationContext
def _controller(self): """Return the server controller.""" def server_controller(cmd_id, cmd_body, _): """Server controler.""" if not self.init_logginig: # the reason put the codes here is because we cannot get # kvstore.rank earlier ...
Return the server controller.
def to_json(self): """Convert the Design Day to a dictionary.""" return { 'location': self.location.to_json(), 'design_days': [des_d.to_json() for des_d in self.design_days] }
Convert the Design Day to a dictionary.
def run_parse(self): """Parse one or more log files""" # Data set already has source file names from load_inputs parsedset = {} parsedset['data_set'] = [] for log in self.input_files: parsemodule = self.parse_modules[self.args.parser] try: ...
Parse one or more log files
def _load_cpp4(self, filename): """Initializes Grid from a CCP4 file.""" ccp4 = CCP4.CCP4() ccp4.read(filename) grid, edges = ccp4.histogramdd() self.__init__(grid=grid, edges=edges, metadata=self.metadata)
Initializes Grid from a CCP4 file.
def compute_region_border(start, end): """ given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance ...
given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance has boolean properties "top", "bottom", "left", and...
def gene_names(self): """ Return names of all genes which overlap this variant. Calling this method is significantly cheaper than calling `Variant.genes()`, which has to issue many more queries to construct each Gene object. """ return self.ensembl.gene_names_at_locus( ...
Return names of all genes which overlap this variant. Calling this method is significantly cheaper than calling `Variant.genes()`, which has to issue many more queries to construct each Gene object.
def ldr(scatterer, h_pol=True): """ Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR. """ Z = scatterer.get_Z() if h_pol: r...
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR.
def downloaded(name, version=None, pkgs=None, fromrepo=None, ignore_epoch=None, **kwargs): ''' .. versionadded:: 2017.7.0 Ensure that the package is downloaded, and that it is the correct version (if specified). Currently s...
.. versionadded:: 2017.7.0 Ensure that the package is downloaded, and that it is the correct version (if specified). Currently supported for the following pkg providers: :mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>` :param str name: The name of the package to...
def canonicalize(message): """ Function to convert an email Message to standard format string :param message: email.Message to be converted to standard string :return: the standard representation of the email message in bytes """ if message.is_multipart() \ or message.get('Content-...
Function to convert an email Message to standard format string :param message: email.Message to be converted to standard string :return: the standard representation of the email message in bytes
def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ if not klass.swagger_types: return data kwargs = {} for attr, attr_ty...
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
def get_billing_report(self, month, **kwargs): # noqa: E501 """Get billing report. # noqa: E501 Fetch the billing report generated for the currently authenticated commercial non-subtenant account. Billing reports for subtenant accounts are included in their aggregator's billing report response. **Ex...
Get billing report. # noqa: E501 Fetch the billing report generated for the currently authenticated commercial non-subtenant account. Billing reports for subtenant accounts are included in their aggregator's billing report response. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v3/b...
def total(self): ''' Returns sum of all counts in all features that are multisets. ''' feats = imap(lambda name: self[name], self._counters()) return sum(chain(*map(lambda mset: map(abs, mset.values()), feats)))
Returns sum of all counts in all features that are multisets.
def execute_prepared_cql3_query(self, itemId, values, consistency): """ Parameters: - itemId - values - consistency """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_execute_prepared_cql3_query(itemId, values, consistency) return d
Parameters: - itemId - values - consistency
def a_stays_connected(ctx): """Stay connected.""" ctx.ctrl.connected = True ctx.device.connected = False return True
Stay connected.
def exit(self, status=EXIT_OK, message=None): """ Terminate the script. """ if not self.parser: self.parser = argparse.ArgumentParser() if self.msg_on_error_only: # if msg_on_error_only is True if status != EXIT_OK: # if we have...
Terminate the script.
def load(self, filepath): """Import '[Term]' entries from an .obo file.""" for attributeLines in oboTermParser(filepath): oboTerm = _attributeLinesToDict(attributeLines) if oboTerm['id'] not in self.oboTerms: self.oboTerms[oboTerm['id']] = oboTerm ...
Import '[Term]' entries from an .obo file.
def unionByName(self, other): """ Returns a new :class:`DataFrame` containing union of rows in this and another frame. This is different from both `UNION ALL` and `UNION DISTINCT` in SQL. To do a SQL-style set union (that does deduplication of elements), use this function followed by :func:`dis...
Returns a new :class:`DataFrame` containing union of rows in this and another frame. This is different from both `UNION ALL` and `UNION DISTINCT` in SQL. To do a SQL-style set union (that does deduplication of elements), use this function followed by :func:`distinct`. The difference between th...
def process_event(self, c): """Returns a message from tick() to be displayed if game is over""" if c == "": sys.exit() elif c in key_directions: self.move_entity(self.player, *vscale(self.player.speed, key_directions[c])) else: return "try arrow keys,...
Returns a message from tick() to be displayed if game is over
def _establish_tunnel(self, connection, address): '''Establish a TCP tunnel. Coroutine. ''' host = '[{}]'.format(address[0]) if ':' in address[0] else address[0] port = address[1] request = RawRequest('CONNECT', '{0}:{1}'.format(host, port)) self.add_auth_header...
Establish a TCP tunnel. Coroutine.
def to_type(self, tokens): """Convert [Token,...] to [Class(...), ] useful for base classes. For example, code like class Foo : public Bar<x, y> { ... }; the "Bar<x, y>" portion gets converted to an AST. Returns: [Class(...), ...] """ result = [] name_...
Convert [Token,...] to [Class(...), ] useful for base classes. For example, code like class Foo : public Bar<x, y> { ... }; the "Bar<x, y>" portion gets converted to an AST. Returns: [Class(...), ...]
def get_vexrc(options, environ): """Get a representation of the contents of the config file. :returns: a Vexrc instance. """ # Complain if user specified nonexistent file with --config. # But we don't want to complain just because ~/.vexrc doesn't exist. if options.config and not os.pat...
Get a representation of the contents of the config file. :returns: a Vexrc instance.
def set_mode(self, mode): """ :Parameters: `mode` : *(int)* New mode, must be one of: - `StreamTokenizer.STRICT_MIN_LENGTH` - `StreamTokenizer.DROP_TRAILING_SILENCE` - `StreamTokenizer.STRICT_MIN_LENGTH | StreamTokenizer.DROP_TRAILING_...
:Parameters: `mode` : *(int)* New mode, must be one of: - `StreamTokenizer.STRICT_MIN_LENGTH` - `StreamTokenizer.DROP_TRAILING_SILENCE` - `StreamTokenizer.STRICT_MIN_LENGTH | StreamTokenizer.DROP_TRAILING_SILENCE` - `0` See `Stre...
def fromBban(bban): """ Convert the passed BBAN to an IBAN for this country specification. Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. This method implements the preferred algorithm described in ...
Convert the passed BBAN to an IBAN for this country specification. Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>. This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/Int...
def _run_cmd_line_code(self): """Run code or file specified at the command-line""" if self.code_to_run: line = self.code_to_run try: self.log.info("Running code given at command line (c=): %s" % line) self.shell.run_ce...
Run code or file specified at the command-line
def to_routing_header(params): """Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string. """ if sys.version_info[0] < 3...
Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]): A dictionary containing the request parameters used for routing. Returns: str: The routing header string.
def add_file_arg(self, filename): """ Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument. """ self.__arguments.append(...
Add a file argument to the executable. Arguments are appended after any options and their order is guaranteed. Also adds the file name to the list of required input data for this job. @param filename: file to add as argument.
def get_vnetwork_vms_input_last_rcvd_instance(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_vms = ET.Element("get_vnetwork_vms") config = get_vnetwork_vms input = ET.SubElement(get_vnetwork_vms, "input") last_rcvd_instance ...
Auto Generated Code
def check_prompt_code(response): """ Sometimes there is an additional numerical code on the response page that needs to be selected on the prompt from a list of multiple choice. Print it if it's there. """ num_code = response.find("div", {"jsname": "EKvSSd"}) if num_code:...
Sometimes there is an additional numerical code on the response page that needs to be selected on the prompt from a list of multiple choice. Print it if it's there.
def _generate_null_hocr(output_hocr, output_sidecar, image): """Produce a .hocr file that reports no text detected on a page that is the same size as the input image.""" from PIL import Image im = Image.open(image) w, h = im.size with open(output_hocr, 'w', encoding="utf-8") as f: f.wr...
Produce a .hocr file that reports no text detected on a page that is the same size as the input image.
def get_activity_photos(self, activity_id, size=None, only_instagram=False): """ Gets the photos from an activity. http://strava.github.io/api/v3/photos/ :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param size: the requested size o...
Gets the photos from an activity. http://strava.github.io/api/v3/photos/ :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param size: the requested size of the activity's photos. URLs for the photos will be returned that best match ...
def transfer_owner(self, new_owner: Address) -> TxReceipt: """ Transfers ownership of this registry instance to the given ``new_owner``. Only the ``owner`` is allowed to transfer ownership. * Parameters: * ``new_owner``: The address of the new owner. """ tx_h...
Transfers ownership of this registry instance to the given ``new_owner``. Only the ``owner`` is allowed to transfer ownership. * Parameters: * ``new_owner``: The address of the new owner.
def readline(self): """Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. """ b = super(PtyProcessUnicode, self).readline() return self.decoder.decode(b, final=False)
Read one line from the pseudoterminal, and return it as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed.
def _set_source(self, v, load=False): """ Setter method for source, mapped from YANG variable /acl_mirror/source (list) If this variable is read-only (config: false) in the source YANG file, then _set_source is considered as a private method. Backends looking to populate this variable should do ...
Setter method for source, mapped from YANG variable /acl_mirror/source (list) If this variable is read-only (config: false) in the source YANG file, then _set_source is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_source() directly.
def _refresh_resource_index(self, resource): """Refresh index for given resource. :param resource: resource name """ if self._resource_config(resource, 'FORCE_REFRESH', True): self.elastic(resource).indices.refresh(self._resource_index(resource))
Refresh index for given resource. :param resource: resource name
def load_code(self): """ Returns a Python code object like xdis.unmarshal.load_code(), but in we decrypt the data in self.bufstr. That is: * calculate the TEA key, * decrypt self.bufstr * create and return a Python code-object """ a = self.load_int() b = self.load_int() ...
Returns a Python code object like xdis.unmarshal.load_code(), but in we decrypt the data in self.bufstr. That is: * calculate the TEA key, * decrypt self.bufstr * create and return a Python code-object
async def main(): """Run.""" async with ClientSession() as websession: try: client = Client(websession) await client.load_local('<IP ADDRESS>', '<PASSWORD>', websession) for controller in client.controllers.values(): print('CLIENT INFORMATION') ...
Run.
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The o...
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately ...
def export_pages(root_page, export_unpublished=False): """ Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some...
Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures th...
def _calculate_mapping_reads(items, work_dir, input_backs=None): """Calculate read counts from samtools idxstats for each sample. Optionally moves over pre-calculated mapping counts from a background file. """ out_file = os.path.join(work_dir, "mapping_reads.txt") if not utils.file_exists(out_file)...
Calculate read counts from samtools idxstats for each sample. Optionally moves over pre-calculated mapping counts from a background file.
def rebuild(self, recreate=True, force=False, **kwargs): "Recreate (if needed) the wx_obj and apply new properties" # detect if this involves a spec that needs to recreate the wx_obj: needs_rebuild = any([isinstance(spec, (StyleSpec, InitSpec)) for spec_name, sp...
Recreate (if needed) the wx_obj and apply new properties
def compare_version(version1, version2): """ Compares two versions. """ def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return (normalize(version1) > normalize(version2))-(normalize(version1) < normalize(version2))
Compares two versions.
def write_antenna(page, args, seg_plot=None, grid=False, ipn=False): """ Write antenna factors to merkup.page object page and generate John's detector response plot. """ from pylal import antenna page.h3() page.add('Antenna factors and sky locations') page.h3.close() th = [] t...
Write antenna factors to merkup.page object page and generate John's detector response plot.
def cleanPolyline(elem, options): """ Scour the polyline points attribute """ pts = parseListOfPoints(elem.getAttribute('points')) elem.setAttribute('points', scourCoordinates(pts, options, True))
Scour the polyline points attribute
def backfill_previous_messages(self, reverse=False, limit=10): """Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (...
Backfill handling of previous messages. Args: reverse (bool): When false messages will be backfilled in their original order (old to new), otherwise the order will be reversed (new to old). limit (int): Number of messages to go back.
def callable_name(callable_obj): """ Attempt to return a meaningful name identifying a callable or generator """ try: if (isinstance(callable_obj, type) and issubclass(callable_obj, param.ParameterizedFunction)): return callable_obj.__name__ elif (isinstance(calla...
Attempt to return a meaningful name identifying a callable or generator
def add_hook(self, name, func): ''' Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Exec...
Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of i...
def _handle_pong(self, ts, *args, **kwargs): """ Handles pong messages; resets the self.ping_timer variable and logs info message. :param ts: timestamp, declares when data was received by the client :return: """ log.info("BitfinexWSS.ping(): Ping received! (%ss)",...
Handles pong messages; resets the self.ping_timer variable and logs info message. :param ts: timestamp, declares when data was received by the client :return:
def filter_by(self, values, exclude=False): """ Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it...
Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- ...
def get_keywords_from_text(text_lines, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False,...
Extract keywords from the list of strings. :param text_lines: list of strings (will be normalized before being joined into one string) :param taxonomy_name: string, name of the taxonomy_name :param output_mode: string - text|html|marcxml|raw :param output_limit: int :param spires: boolean, ...
def matchPatterns(patterns, keys): """ Returns a subset of the keys that match any of the given patterns :param patterns: (list) regular expressions to match :param keys: (list) keys to search for matches """ results = [] if patterns: for pattern in patterns: prog = re.compile(pattern) fo...
Returns a subset of the keys that match any of the given patterns :param patterns: (list) regular expressions to match :param keys: (list) keys to search for matches
def removeChild(self, child): ''' removeChild - Remove a child tag, if present. @param child <AdvancedTag> - The child to remove @return - The child [with parentNode cleared] if removed, otherwise None. NOTE: This removes a tag. If removing a text b...
removeChild - Remove a child tag, if present. @param child <AdvancedTag> - The child to remove @return - The child [with parentNode cleared] if removed, otherwise None. NOTE: This removes a tag. If removing a text block, use #removeText function. If y...
def subdivide(self): r"""Split the curve :math:`B(s)` into a left and right half. Takes the interval :math:`\left[0, 1\right]` and splits the curve into :math:`B_1 = B\left(\left[0, \frac{1}{2}\right]\right)` and :math:`B_2 = B\left(\left[\frac{1}{2}, 1\right]\right)`. In order ...
r"""Split the curve :math:`B(s)` into a left and right half. Takes the interval :math:`\left[0, 1\right]` and splits the curve into :math:`B_1 = B\left(\left[0, \frac{1}{2}\right]\right)` and :math:`B_2 = B\left(\left[\frac{1}{2}, 1\right]\right)`. In order to do this, also reparameteri...
def status_set(workload_state, message): """Set the workload state with a message Use status-set to set the workload state with a message which is visible to the user via juju status. If the status-set command is not found then assume this is juju < 1.23 and juju-log the message unstead. workload_...
Set the workload state with a message Use status-set to set the workload state with a message which is visible to the user via juju status. If the status-set command is not found then assume this is juju < 1.23 and juju-log the message unstead. workload_state -- valid juju workload state. message ...
def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Takes the inverse sin of a vertex, Arcsin(vertex) :param input_vertex: the vertex """ return Double(context.jvm_view().ArcSinVertex, label, cast_to_double_vertex(input_vertex))
Takes the inverse sin of a vertex, Arcsin(vertex) :param input_vertex: the vertex
def simplify(self): """Return a simplified expression.""" node = self.node.simplify() if node is self.node: return self else: return _expr(node)
Return a simplified expression.
def do_gate_matrix(self, matrix: np.ndarray, qubits: Sequence[int]) -> 'AbstractQuantumSimulator': """ Apply an arbitrary unitary; not necessarily a named gate. :param matrix: The unitary matrix to apply. No checks are done :param qubits: A list of qubits to apply...
Apply an arbitrary unitary; not necessarily a named gate. :param matrix: The unitary matrix to apply. No checks are done :param qubits: A list of qubits to apply the unitary to. :return: ``self`` to support method chaining.
def strlify(a): ''' Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so...
Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so it's safer to just strl...
def _lval_add_towards_polarity(x, polarity): """Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity. """ if x < 0: if polarity < 0: return Lval('toinf'...
Compute the appropriate Lval "kind" for the limit of value `x` towards `polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and the infinity direction of polarity.
def yield_sorted_by_type(*typelist): """ a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types wi...
a useful decorator for the collect_impl method of SuperChange subclasses. Caches the yielded changes, and re-emits them collected by their type. The order of the types can be specified by listing the types as arguments to this decorator. Unlisted types will be yielded last in no guaranteed order. G...
def _initiate_resumable_upload(self, stream, metadata, num_retries): """Initiate a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retr...
Initiate a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retries: int :param num_retries: Number of upload retries. (Deprecated: This...
def make_decoder(activation, latent_size, output_shape, base_depth): """Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: de...
Creates the decoder function. Args: activation: Activation function in hidden layers. latent_size: Dimensionality of the encoding. output_shape: The output image shape. base_depth: Smallest depth for a layer. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distri...
def options(self): ''' Small method to return headers of an OPTIONS request to self.uri Args: None Return: (dict) response headers from OPTIONS request ''' # http request response = self.repo.api.http_request('OPTIONS', self.uri) return response.headers
Small method to return headers of an OPTIONS request to self.uri Args: None Return: (dict) response headers from OPTIONS request
def decode_packet(data): """decode the data, return some kind of PDU.""" if _debug: decode_packet._debug("decode_packet %r", data) # empty strings are some other kind of pcap content if not data: return None # assume it is ethernet for now d = decode_ethernet(data) pduSource = Addr...
decode the data, return some kind of PDU.
def get_time_interval(time1, time2): '''get the interval of two times''' try: #convert time to timestamp time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S')) time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S')) seconds = (datetime.datetime.fromtimestamp(time2)...
get the interval of two times
def submatrix(dmat, indices_col, n_neighbors): """Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consist...
Return a submatrix given an orginal matrix and the indices to keep. Parameters ---------- mat: array, shape (n_samples, n_samples) Original matrix. indices_col: array, shape (n_samples, n_neighbors) Indices to keep. Each row consists of the indices of the columns. n_neighbors: int...
def _gte(field, value, document): """ Returns True if the value of a document field is greater than or equal to a given value """ try: return document.get(field, None) >= value except TypeError: # pragma: no cover Python < 3.0 return False
Returns True if the value of a document field is greater than or equal to a given value
def _init_args(self): """Get enrichment arg parser.""" #pylint: disable=invalid-name p = argparse.ArgumentParser(__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) p.add_argument('filenames', type=str, nargs=3, he...
Get enrichment arg parser.
def run(self): """Invoke the function repeatedly on a timer.""" ret = eventlet.spawn(self.context(self.func)) eventlet.sleep(self.seconds) try: ret.wait() except Exception: # pylint: disable=broad-except traceback.print_exc() self.thread = eventle...
Invoke the function repeatedly on a timer.
def filter_with_schema(self, model=None, context=None): """ Perform model filtering with schema """ if model is None or self.schema is None: return self._schema.filter( model=model, context=context if self.use_context else None )
Perform model filtering with schema
def list_all_by_reqvip(self, id_vip, pagination): """ List All Pools To Populate Datatable :param pagination: Object Pagination :return: Following dictionary:{ "total" : < total >, "pool...
List All Pools To Populate Datatable :param pagination: Object Pagination :return: Following dictionary:{ "total" : < total >, "pools" :[{ "id": < id > ...
def setup_logging(): """Called when __name__ == '__main__' below. Sets up logging library. All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages. """ fmt = 'DBG<0>%(pathname)s:%(lineno)d %(funcName)s: %(message)s' handler_stderr = logging.StreamH...
Called when __name__ == '__main__' below. Sets up logging library. All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
def _padleft(width, s, has_invisible=True): """Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True """ iwidth = width + len(s) - len(_strip_invisible(s)) if has_invisible else width fmt = "{0:>%ds}" % iwidth return fmt.format(s)
Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True
def global_defaults(): """ Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtr...
Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtrees controlling behavior of ``run``...
def reward(self, action=None): """ Reward function for the task. The dense reward has three components. Reaching: in [0, 1], to encourage the arm to reach the cube Grasping: in {0, 0.25}, non-zero if arm is grasping the cube Lifting: in {0, 1}, non-zero if a...
Reward function for the task. The dense reward has three components. Reaching: in [0, 1], to encourage the arm to reach the cube Grasping: in {0, 0.25}, non-zero if arm is grasping the cube Lifting: in {0, 1}, non-zero if arm has lifted the cube The sparse reward o...
def SendVoicemail(self, Username): """Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet. """ if self._Api.protocol >= 6: self._DoComm...
Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet.
def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): """Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrume...
Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>...
def read(self, to_read, timeout_ms): """Reads data from this file. in to_read of type int Number of bytes to read. in timeout_ms of type int Timeout (in ms) to wait for the operation to complete. Pass 0 for an infinite timeout. return data of type s...
Reads data from this file. in to_read of type int Number of bytes to read. in timeout_ms of type int Timeout (in ms) to wait for the operation to complete. Pass 0 for an infinite timeout. return data of type str Array of data read. rais...
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_in...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one ...
def sleep_and_retry(func): ''' Return a wrapped function that rescues rate limit exceptions, sleeping the current thread until rate limit resets. :param function func: The function to decorate. :return: Decorated function. :rtype: function ''' @wraps(func) def wrapper(*args, **kargs...
Return a wrapped function that rescues rate limit exceptions, sleeping the current thread until rate limit resets. :param function func: The function to decorate. :return: Decorated function. :rtype: function
def filter_and_transform_data(df, settings): ''' Perform filtering on the data based on arguments set on commandline - use aligned length or sequenced length (bam mode only) - hide outliers from length plots* - hide reads longer than maxlength or shorter than minlength from length plots* - filte...
Perform filtering on the data based on arguments set on commandline - use aligned length or sequenced length (bam mode only) - hide outliers from length plots* - hide reads longer than maxlength or shorter than minlength from length plots* - filter reads with a quality below minqual - use log10 scal...
def MatrixSolve(a, rhs, adj): """ Matrix solve op. """ return np.linalg.solve(a if not adj else _adjoint(a), rhs),
Matrix solve op.
def validate(self, collection: BioCCollection): """Validate a single collection.""" for document in collection.documents: self.validate_doc(document)
Validate a single collection.
def _timeout_handler(self, signum, frame): """ internal timeout handler """ msgfmt = 'plugin timed out after {0} seconds' self.exit(code=self._timeout_code, message=msgfmt.format(self._timeout_delay))
internal timeout handler
def write(self, data): """Sends some data to the client.""" # I don't want to add a separate 'Client disconnected' logic for sending. # Therefore I just ignore any writes after the first error - the server # won't send that much data anyway. Afterwards the read will detect the # ...
Sends some data to the client.
def _read_configuration(config_filename): """ Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser) """ config = ConfigParser() config.read(config_filename) ...
Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser)