code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def metric(self, name, filter_=None, description=""): """Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the ...
Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the entries tracked by the metric. If not ...
def connect_edges(graph): """ Given a Graph element containing abstract edges compute edge segments directly connecting the source and target nodes. This operation just uses internal HoloViews operations and will be a lot slower than the pandas equivalent. """ paths = [] for start, end ...
Given a Graph element containing abstract edges compute edge segments directly connecting the source and target nodes. This operation just uses internal HoloViews operations and will be a lot slower than the pandas equivalent.
def recognize_using_websocket(self, audio, content_type, recognize_callback, model=None, language_customization_id=None, ...
Sends audio for speech recognition using web sockets. :param AudioSource audio: The audio to transcribe in the format specified by the `Content-Type` header. :param str content_type: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg...
def delete(self, *objects, **kwargs): ''' This method offers the ability to delete multiple entities in a single round trip to Redis (assuming your models are all stored on the same server). You can call:: session.delete(obj) session.delete(obj1, obj2, ...) ...
This method offers the ability to delete multiple entities in a single round trip to Redis (assuming your models are all stored on the same server). You can call:: session.delete(obj) session.delete(obj1, obj2, ...) session.delete([obj1, obj2, ...]) The key...
def zrange(key, start, stop, host=None, port=None, db=None, password=None): ''' Get a range of values from a sorted set in Redis by index CLI Example: .. code-block:: bash salt '*' redis.zrange foo_sorted 0 10 ''' server = _connect(host, port, db, password) return server.zrange(ke...
Get a range of values from a sorted set in Redis by index CLI Example: .. code-block:: bash salt '*' redis.zrange foo_sorted 0 10
def write_table(table, target, tablename=None, ilwdchar_compat=None, **kwargs): """Write a `~astropy.table.Table` to file in LIGO_LW XML format This method will attempt to write in the new `ligo.lw` format (if ``ilwdchar_compat`` is ``None`` or ``False``), but will fall back to the olde...
Write a `~astropy.table.Table` to file in LIGO_LW XML format This method will attempt to write in the new `ligo.lw` format (if ``ilwdchar_compat`` is ``None`` or ``False``), but will fall back to the older `glue.ligolw` (in that order) if that fails (if ``ilwdchar_compat`` is ``None`` or ``True``).
def load_build_config(self, config=None): '''load a google compute config, meaning that we have the following cases: 1. the user has not provided a config file directly, we look in env. 2. the environment is not set, so we use a reasonable default 3. if the final string is not found as a file,...
load a google compute config, meaning that we have the following cases: 1. the user has not provided a config file directly, we look in env. 2. the environment is not set, so we use a reasonable default 3. if the final string is not found as a file, we look for it in library 4. we load the ...
def hpx_to_coords(h, shape): """ Generate an N x D list of pixel center coordinates where N is the number of pixels and D is the dimensionality of the map.""" x, z = hpx_to_axes(h, shape) x = np.sqrt(x[0:-1] * x[1:]) z = z[:-1] + 0.5 x = np.ravel(np.ones(shape) * x[:, np.newaxis]) z = np....
Generate an N x D list of pixel center coordinates where N is the number of pixels and D is the dimensionality of the map.
def weld_align(df_index_arrays, df_index_weld_types, series_index_arrays, series_index_weld_types, series_data, series_weld_type): """Returns the data from the Series aligned to the DataFrame index. Parameters ---------- df_index_arrays : list of (numpy.ndarray or WeldObje...
Returns the data from the Series aligned to the DataFrame index. Parameters ---------- df_index_arrays : list of (numpy.ndarray or WeldObject) The index columns as a list. df_index_weld_types : list of WeldType series_index_arrays : numpy.ndarray or WeldObject The index of the Serie...
def can(ability, add_headers=None): """Test whether an ability is allowed.""" client = ClientMixin(api_key=None) try: client.request('GET', endpoint='abilities/%s' % ability, add_headers=add_headers) return True except Exception: pass return False
Test whether an ability is allowed.
def sendMessage(self, exchange, routing_key, message, properties=None, UUID=None): """ With this function, you can send message to `exchange`. Args: exchange (str): name of exchange you want to message to be delivered routi...
With this function, you can send message to `exchange`. Args: exchange (str): name of exchange you want to message to be delivered routing_key (str): which routing key to use in headers of message message (str): body of message propert...
def update(context, id, etag, name, password, email, fullname, team_id, active): """update(context, id, etag, name, password, email, fullname, team_id, active) Update a user. >>> dcictl user-update [OPTIONS] :param string id: ID of the user to update [required] :param str...
update(context, id, etag, name, password, email, fullname, team_id, active) Update a user. >>> dcictl user-update [OPTIONS] :param string id: ID of the user to update [required] :param string etag: Entity tag of the user resource [required] :param string name: Name of the user :...
def get_vars_in_expression(source): '''Get list of variable names in a python expression.''' import compiler from compiler.ast import Node ## # @brief Internal recursive function. # @param node An AST parse Node. # @param var_list Input list of variables. # @return An updated list of v...
Get list of variable names in a python expression.
def get_time(self): """ :return: Steam aligned timestamp :rtype: int """ if (self.steam_time_offset is None or (self.align_time_every and (time() - self._offset_last_check) > self.align_time_every) ): self.steam_time_offset = get_time_offset() ...
:return: Steam aligned timestamp :rtype: int
def uncomment(comment): """ Converts the comment node received to a non-commented element, in place, and will return the new node. This may fail, primarily due to special characters within the comment that the xml parser is unable to handle. If it fails, this method will log an error and return...
Converts the comment node received to a non-commented element, in place, and will return the new node. This may fail, primarily due to special characters within the comment that the xml parser is unable to handle. If it fails, this method will log an error and return None
def save_default_values(self): """Save InaSAFE default values.""" for parameter_container in self.default_value_parameter_containers: parameters = parameter_container.get_parameters() for parameter in parameters: set_inasafe_default_value_qsetting( ...
Save InaSAFE default values.
def transacted(func): """ Return a callable which will invoke C{func} in a transaction using the C{store} attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. The attributes of the returned callable will resemble...
Return a callable which will invoke C{func} in a transaction using the C{store} attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. The attributes of the returned callable will resemble those of C{func} as closely a...
def save(self, *args, **kwargs): """creates the slug, queues up for indexing and saves the instance :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.content.Content` """ if not self.slug: self.slug = slugify(self.build...
creates the slug, queues up for indexing and saves the instance :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.content.Content`
def remove(self, id): """Remove a object by id Args: id (int): Object's id should be deleted Returns: len(int): affected rows """ before_len = len(self.model.db) self.model.db = [t for t in self.model.db if t["id"] != id] if...
Remove a object by id Args: id (int): Object's id should be deleted Returns: len(int): affected rows
async def get_data(self): """Retrieve the data.""" try: with async_timeout.timeout(5, loop=self._loop): response = await self._session.get( '{}/{}/'.format(self.url, self.sensor_id)) _LOGGER.debug( "Response from luftdaten.info...
Retrieve the data.
def _serve_forever_wrapper(self, _srv, poll_interval=0.1): """ Wrapper for the server created for a SSH forward """ self.logger.info('Opening tunnel: {0} <> {1}'.format( address_to_str(_srv.local_address), address_to_str(_srv.remote_address)) ) _sr...
Wrapper for the server created for a SSH forward
def bifurcation_partitions(neurites, neurite_type=NeuriteType.all): '''Partition at bifurcation points of a collection of neurites''' return map(_bifurcationfunc.bifurcation_partition, iter_sections(neurites, iterator_type=Tree.ibifurcation_point, ...
Partition at bifurcation points of a collection of neurites
def encode_multiple_layers(out, features_by_layer, zoom): """ features_by_layer should be a dict: layer_name -> feature tuples """ precision = precision_for_zoom(zoom) geojson = {} for layer_name, features in features_by_layer.items(): fs = create_layer_feature_collection(features, preci...
features_by_layer should be a dict: layer_name -> feature tuples
def create_el(name, text=None, attrib=None): """Create element with given attributes and set element.text property to given text value (if text is not None) :param name: element name :type name: str :param text: text node value :type text: str :param attrib: attributes :type attrib: dic...
Create element with given attributes and set element.text property to given text value (if text is not None) :param name: element name :type name: str :param text: text node value :type text: str :param attrib: attributes :type attrib: dict :returns: xml element :rtype: Element
def _parse_log_statement(options): ''' Parses a log path. ''' for i in options: if _is_reference(i): _add_reference(i, _current_statement) elif _is_junction(i): _add_junction(i) elif _is_inline_definition(i): _add_inline_definition(i, _current_...
Parses a log path.
def join_left(self, right_table=None, fields=None, condition=None, join_type='LEFT JOIN', schema=None, left_table=None, extract_fields=True, prefix_fields=False, field_prefix=None, allow_duplicates=False): """ Wrapper for ``self.join`` with a default join of 'LEFT JOI...
Wrapper for ``self.join`` with a default join of 'LEFT JOIN' :type right_table: str or dict or :class:`Table <querybuilder.tables.Table>` :param right_table: The table being joined with. This can be a string of the table name, a dict of {'alias': table}, or a ``Table`` instance :ty...
def create(self, cid, configData): """ Create a new named (cid) configuration from a parameter dictionary (config_data). """ configArgs = {'configId': cid, 'params': configData, 'force': True} cid = self.server.call('post', "/config/create", configArgs, forceText=True, headers=Te...
Create a new named (cid) configuration from a parameter dictionary (config_data).
def configure(self, cnf=None, **kw): """ Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option. """ if cnf == 'drag_cols': ...
Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option.
def apply_slippage_penalty(returns, txn_daily, simulate_starting_capital, backtest_starting_capital, impact=0.1): """ Applies quadratic volumeshare slippage model to daily returns based on the proportion of the observed historical daily bar dollar volume consumed by the strate...
Applies quadratic volumeshare slippage model to daily returns based on the proportion of the observed historical daily bar dollar volume consumed by the strategy's trades. Scales the size of trades based on the ratio of the starting capital we wish to test to the starting capital of the passed backtest ...
def _get_sorter(subpath='', **defaults): """Return function to generate specific subreddit Submission listings.""" @restrict_access(scope='read') def _sorted(self, *args, **kwargs): """Return a get_content generator for some RedditContentObject type. The additional parameters are passed dir...
Return function to generate specific subreddit Submission listings.
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_a...
Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created.
def list(self, teamId=None, rType=None, maxResults=C.MAX_RESULT_DEFAULT, limit=C.ALL): """ rType can be DIRECT or GROUP """ queryParams = {'teamId': teamId, 'type': rType, 'max': maxResults} queryParams = self.clean_query_Dict(queryParams) ret = self.send_request(C.GET, s...
rType can be DIRECT or GROUP
async def cancel_scheduled_messages(self, *sequence_numbers): """Cancel one or more messages that have previsouly been scheduled and are still pending. :param sequence_numbers: The seqeuence numbers of the scheduled messages. :type sequence_numbers: int Example: .. literali...
Cancel one or more messages that have previsouly been scheduled and are still pending. :param sequence_numbers: The seqeuence numbers of the scheduled messages. :type sequence_numbers: int Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py ...
def patch(self, deviceId): """ Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometer...
Updates the device with the given data. Supports a json payload like { fs: newFs samplesPerBatch: samplesPerBatch gyroEnabled: true gyroSensitivity: 500 accelerometerEnabled: true accelerometerSensitivity: 2 } A heartbeat is...
def zrevrank(self, name, value): """ Returns the ranking in reverse order for the member :param name: str the name of the redis key :param member: str """ with self.pipe as pipe: return pipe.zrevrank(self.redis_key(name), ...
Returns the ranking in reverse order for the member :param name: str the name of the redis key :param member: str
def dump_to_store(self, store, **kwargs): """Store dataset contents to a backends.*DataStore object.""" from ..backends.api import dump_to_store # TODO: rename and/or cleanup this method to make it more consistent # with to_netcdf() return dump_to_store(self, store, **kwargs)
Store dataset contents to a backends.*DataStore object.
def add_resource(self, format, resource, locale, domain=None): """ Adds a resource @type format: str @param format: Name of the loader (@see add_loader) @type resource: str @param resource: The resource name @type locale: str @type domain: str @...
Adds a resource @type format: str @param format: Name of the loader (@see add_loader) @type resource: str @param resource: The resource name @type locale: str @type domain: str @raises: ValueError If the locale contains invalid characters @return:
def _kbstr_to_cimval(key, val): """ Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it. """ if val[0] == '"' and val[-1] == '"': # A double quoted key value. This could be any of these CIM types: # *...
Convert a keybinding value string as found in a WBEM URI into a CIM object or CIM data type, and return it.
def tokhex(length=10, urlsafe=False): """ Return a random string in hexadecimal """ if urlsafe is True: return secrets.token_urlsafe(length) return secrets.token_hex(length)
Return a random string in hexadecimal
def absent(name, auth=None, **kwargs): ''' Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from ''' rule_id = kwargs['rule_id'] ret = {'n...
Ensure a security group rule does not exist name name or id of the security group rule to delete rule_id uuid of the rule to delete project_id id of project to delete rule from
def to_signed_str(self, private, public, passphrase=None): ''' Returns a signed version of the invoice. @param private:file Private key file-like object @param public:file Public key file-like object @param passphrase:str Private key passphrase if any. @return: str ...
Returns a signed version of the invoice. @param private:file Private key file-like object @param public:file Public key file-like object @param passphrase:str Private key passphrase if any. @return: str
def brkl2d(arr,interval): ''' arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"] >>> brkl2d(arr,5) [{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}] ''' lngth = arr.__len__() brkseqs = elel.init_range(0,lngth,interval) l = elel.broken...
arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"] >>> brkl2d(arr,5) [{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}]
def preferred_ip(vm_, ips): ''' Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'. ''' proto = config.get_cloud_config_value( 'protocol', vm_, __opts__, default='ipv4', search_global=False ) family = socket.AF_INET if proto == 'ipv6': family = socket....
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
def translate_update(blob): "converts JSON parse output to self-aware objects" # note below: v will be int or null return {translate_key(k):parse_serialdiff(v) for k,v in blob.items()}
converts JSON parse output to self-aware objects
def _path(self, key): """ Get the full path for the given cache key. :param key: The cache key :type key: str :rtype: str """ hash_type, parts_count = self._HASHES[self._hash_type] h = hash_type(encode(key)).hexdigest() parts = [h[i:i+2] for i i...
Get the full path for the given cache key. :param key: The cache key :type key: str :rtype: str
def update(self): """ Updates information about the NepDate """ functions.check_valid_bs_range(self) # Here's a trick to find the gregorian date: # We find the number of days from earliest nepali date to the current # day. We then add the number of days to the earliest english da...
Updates information about the NepDate
def send(self, msg): """ Send a message to the node on which this replica resides. :param msg: the message to send """ logger.debug("{}'s elector sending {}".format(self.name, msg)) self.outBox.append(msg)
Send a message to the node on which this replica resides. :param msg: the message to send
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): """Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_ro...
Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs...
def render_embed_js(self, js_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return ( b'<script type="text/javascript">\n//<!...
Default method used to render the final embedded js for the rendered webpage. Override this method in a sub-classed controller to change the output.
def get_configured_consensus_module(block_id, state_view): """Returns the consensus_module based on the consensus module set by the "sawtooth_settings" transaction family. Args: block_id (str): the block id associated with the current state_view state_view (:obj:`StateVi...
Returns the consensus_module based on the consensus module set by the "sawtooth_settings" transaction family. Args: block_id (str): the block id associated with the current state_view state_view (:obj:`StateView`): the current state view to use for setting values...
def unregister_callback(self, type_, from_, *, wildcard_resource=True): """ Unregister a callback function. :param type_: Stanza type to listen for, or :data:`None` for a wildcard match. :param from_: Sender to listen for, or :data:`None...
Unregister a callback function. :param type_: Stanza type to listen for, or :data:`None` for a wildcard match. :param from_: Sender to listen for, or :data:`None` for a full wildcard match. :type from_: :class:`aioxmpp.JID` or :data:`None` :pa...
def encode_kv_node(keypath, child_node_hash): """ Serializes a key/value node """ if keypath is None or keypath == b'': raise ValidationError("Key path can not be empty") validate_is_bytes(keypath) validate_is_bytes(child_node_hash) validate_length(child_node_hash, 32) return KV_...
Serializes a key/value node
def system_monitor_SFM_threshold_marginal_threshold(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") SFM = ET.SubElement(system_monitor, "SFM") ...
Auto Generated Code
def read_cs_raw_symmetrized_tensors(self): """ Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in the order of atoms. """ header_pattern = r"\s+-{50,}\s+" \ r"\s+Absolute Chemical Shift tensors\s+...
Parse the matrix form of NMR tensor before corrected to table. Returns: nsymmetrized tensors list in the order of atoms.
def start(self): """Starts watching the path and running the test jobs.""" assert not self.watching def selector(evt): if evt.is_directory: return False path = evt.path if path in self._last_fnames: # Detected a "killing cycle" return False for pattern in self.skip_p...
Starts watching the path and running the test jobs.
def f16(op): """ Returns a floating point operand converted to 32 bits unsigned int. Negative numbers are returned in 2 complement. The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part) """ op = float(op) negative = op < 0 if negative: op = -op ...
Returns a floating point operand converted to 32 bits unsigned int. Negative numbers are returned in 2 complement. The result is returned in a tuple (DE, HL) => High16 (Int part), Low16 (Decimal part)
def SetAttributes(self, urn, attributes, to_delete, add_child_index=True, mutation_pool=None): """Sets the attributes in the data store.""" attributes[AFF4Object.SchemaCls.LAST] = [ rdfvalue.RDFDatetime....
Sets the attributes in the data store.
def _untracked_custom_unit_found(name, root=None): ''' If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False. ''' system = _root('/etc/systemd/system', root) unit_path = os.path.join(system, _canonical_unit_name(name)) ...
If the passed service name is not available, but a unit file exist in /etc/systemd/system, return True. Otherwise, return False.
def make_witness_input(outpoint, sequence): ''' Outpoint, int -> TxIn ''' if 'decred' in riemann.get_current_network_name(): return tx.DecredTxIn( outpoint=outpoint, sequence=utils.i2le_padded(sequence, 4)) return tx.TxIn(outpoint=outpoint, stack_sc...
Outpoint, int -> TxIn
def _make_context_immutable(context): """Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType....
Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType. Otherwise, return as-is.
def to_coords(self): """ Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y) """ data = self.native first_byte = data[0:1] # Uncompressed if first_byte ==...
Returns the X and Y coordinates for this EC point, as native Python integers :return: A 2-element tuple containing integers (X, Y)
def xpath(C, node, path, namespaces=None, extensions=None, smart_strings=True, **args): """shortcut to Element.xpath()""" return node.xpath( path, namespaces=namespaces or C.NS, extensions=extensions, smart_strings=smart_strings, **args ...
shortcut to Element.xpath()
def get_repr(self, obj, referent=None): """Return an HTML tree block describing the given object.""" objtype = type(obj) typename = str(objtype.__module__) + "." + objtype.__name__ prettytype = typename.replace("__builtin__.", "") name = getattr(obj, "__name__", "") if n...
Return an HTML tree block describing the given object.
def one_hot_encoding(labels, num_classes, scope=None): """Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels. """ with tf.name_scope(scope, '...
Transform numeric labels into onehot_labels. Args: labels: [batch_size] target labels. num_classes: total number of classes. scope: Optional scope for name_scope. Returns: one hot encoding of the labels.
def compare_table_cols(a, b): """ Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise. """ return cmp(sorted((col.Name, col.Type) for col in a.getElementsByTagName(ligolw.Column.tagName)), sorted((col.Name, col.Type) for col in...
Return False if the two tables a and b have the same columns (ignoring order) according to LIGO LW name conventions, return True otherwise.
def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): """Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field:...
Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field: Replace message field if True. Merge message field if False. replace_repeated_field: Replace repeated field...
def print_evaluation(period=1, show_stdv=True): """Create a callback that prints the evaluation results. Parameters ---------- period : int, optional (default=1) The period to print the evaluation results. show_stdv : bool, optional (default=True) Whether to show stdv (if provided)....
Create a callback that prints the evaluation results. Parameters ---------- period : int, optional (default=1) The period to print the evaluation results. show_stdv : bool, optional (default=True) Whether to show stdv (if provided). Returns ------- callback : function ...
def random_draw(self, size=None): """Draw random samples of the hyperparameters. The outputs of the two priors are stacked vertically. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only o...
Draw random samples of the hyperparameters. The outputs of the two priors are stacked vertically. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is...
def clipping_params(ts, capacity=100): """Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacit...
Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacity (float): Total "funds" or "energy" available...
def _to_span(x, idx=0): """Convert a Candidate, Mention, or Span to a span.""" if isinstance(x, Candidate): return x[idx].context elif isinstance(x, Mention): return x.context elif isinstance(x, TemporarySpanMention): return x else: raise ValueError(f"{type(x)} is an ...
Convert a Candidate, Mention, or Span to a span.
def parse_host(entity, default_port=DEFAULT_PORT): """Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP...
Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP address. - `default_port`: The port number to use...
def _fake_openqueryinstances(self, namespace, **params): # pylint: disable=invalid-name """ Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenQueryInstances` with data from the instance repository. """ self._validate_namespace(namespace) ...
Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenQueryInstances` with data from the instance repository.
def init(app_id, app_key=None, master_key=None, hook_key=None): """ๅˆๅง‹ๅŒ– LeanCloud ็š„ AppId / AppKey / MasterKey :type app_id: string_types :param app_id: ๅบ”็”จ็š„ Application ID :type app_key: None or string_types :param app_key: ๅบ”็”จ็š„ Application Key :type master_key: None or string_types :param ma...
ๅˆๅง‹ๅŒ– LeanCloud ็š„ AppId / AppKey / MasterKey :type app_id: string_types :param app_id: ๅบ”็”จ็š„ Application ID :type app_key: None or string_types :param app_key: ๅบ”็”จ็š„ Application Key :type master_key: None or string_types :param master_key: ๅบ”็”จ็š„ Master Key :param hook_key: application's hook key ...
def get_tower_results(iterator, optimizer, dropout_rates): r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers. ''' # To calculate the mean of the losses ...
r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers.
def ct_bytes_compare(a, b): """ Constant-time string compare. http://codahale.com/a-lesson-in-timing-attacks/ """ if not isinstance(a, bytes): a = a.decode('utf8') if not isinstance(b, bytes): b = b.decode('utf8') if len(a) != len(b): return False result = 0 ...
Constant-time string compare. http://codahale.com/a-lesson-in-timing-attacks/
def getBranch(self, name, **context): """Return a branch of this tree where the 'name' OID may reside""" for keyLen in self._vars.getKeysLens(): subName = name[:keyLen] if subName in self._vars: return self._vars[subName] raise error.NoSuchObjectError(nam...
Return a branch of this tree where the 'name' OID may reside
def extract_named_group(text, named_group, matchers, return_presence=False): ''' Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is ...
Return ``named_group`` match from ``text`` reached by using a matcher from ``matchers``. It also supports matching without a ``named_group`` in a matcher, which sets ``presence=True``. ``presence`` is only returned if ``return_presence=True``.
def entry_set(self, predicate=None): """ Returns a list clone of the mappings contained in this map. **Warning: The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param predicate: (Predicate), predicate for the map to filt...
Returns a list clone of the mappings contained in this map. **Warning: The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param predicate: (Predicate), predicate for the map to filter entries (optional). :return: (Sequence), the l...
def vprjp(vin, plane): """ Project a vector onto a specified plane, orthogonally. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjp_c.html :param vin: The projected vector. :type vin: 3-Element Array of floats :param plane: Plane containing vin. :type plane: spiceypy.utils.su...
Project a vector onto a specified plane, orthogonally. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjp_c.html :param vin: The projected vector. :type vin: 3-Element Array of floats :param plane: Plane containing vin. :type plane: spiceypy.utils.support_types.Plane :return: Vect...
def _drawBackground(self, scene, painter, rect): """ Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF> """ rect = scene.sceneRect() ...
Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF>
def get_resource(self): """Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be ...
Gets the ``Resource`` for this authorization. return: (osid.resource.Resource) - the ``Resource`` raise: IllegalState - ``has_resource()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
def score_hist(df, columns=None, groupby=None, threshold=0.7, stacked=True, bins=20, percent=True, alpha=0.33, show=True, block=False, save=False): """Plot multiple histograms on one plot, typically of "score" values between 0 and 1 Typically the groupby or columns of the dataframe are the classi...
Plot multiple histograms on one plot, typically of "score" values between 0 and 1 Typically the groupby or columns of the dataframe are the classification categories (0, .5, 1) And the values are scores between 0 and 1.
def NonNegIntStringToInt(int_string, problems=None): """Convert an non-negative integer string to an int or raise an exception""" # Will raise TypeError unless a string match = re.match(r"^(?:0|[1-9]\d*)$", int_string) # Will raise ValueError if the string can't be parsed parsed_value = int(int_string) if ...
Convert an non-negative integer string to an int or raise an exception
def get_status(address=None): """ Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running' """ address = address or (config.dbserver.host, DBSERVER_PORT) return 'running' if socket_ready(address) else 'not-running'
Check if the DbServer is up. :param address: pair (hostname, port) :returns: 'running' or 'not-running'
def delete_network_postcommit(self, context): """Delete the network from CVX""" network = context.current log_context("delete_network_postcommit: network", network) segments = context.network_segments tenant_id = network['project_id'] self.delete_segments(segments) ...
Delete the network from CVX
def likelihood_weighting(X, e, bn, N): """Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298' ""...
Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298'
def setRoute(self, vehID, edgeList): """ setRoute(string, list) -> None changes the vehicle route to given edges list. The first edge in the list has to be the one that the vehicle is at at the moment. example usage: setRoute('1', ['1', '2', '4', '6', '7']) th...
setRoute(string, list) -> None changes the vehicle route to given edges list. The first edge in the list has to be the one that the vehicle is at at the moment. example usage: setRoute('1', ['1', '2', '4', '6', '7']) this changes route for vehicle id 1 to edges 1-2-4-6-7
def is_ascii_obfuscation(vm): """ Tests if any class inside a DalvikVMObject uses ASCII Obfuscation (e.g. UTF-8 Chars in Classnames) :param vm: `DalvikVMObject` :return: True if ascii obfuscation otherwise False """ for classe in vm.get_classes(): if is_ascii_problem(classe.get_name...
Tests if any class inside a DalvikVMObject uses ASCII Obfuscation (e.g. UTF-8 Chars in Classnames) :param vm: `DalvikVMObject` :return: True if ascii obfuscation otherwise False
def notifications_mark_read(input_params={}, always_retry=True, **kwargs): """ Invokes the /notifications/markRead API method. """ return DXHTTPRequest('/notifications/markRead', input_params, always_retry=always_retry, **kwargs)
Invokes the /notifications/markRead API method.
def append(self, position, array): """Append an array to the end of the map. The position must be greater than any positions in the map""" if not Gauged.map_append(self.ptr, position, array.ptr): raise MemoryError
Append an array to the end of the map. The position must be greater than any positions in the map
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Param...
Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) or DataDesc objects Typically is ``data_iter.provide_data``. Can also be a list of (data name,...
def ostree_path(self): """ ostree repository -- content """ if self._ostree_path is None: self._ostree_path = os.path.join(self.tmpdir, "ostree-repo") subprocess.check_call(["ostree", "init", "--mode", "bare-user-only", "--repo", self._ostree_pa...
ostree repository -- content
def setup(self, app): """ Setup the plugin from an application. """ super().setup(app) if isinstance(self.cfg.template_folders, str): self.cfg.template_folders = [self.cfg.template_folders] else: self.cfg.template_folders = list(self.cfg.template_folders) ...
Setup the plugin from an application.
def ConsultarDomicilios(self, nro_doc, tipo_doc=80, cat_iva=None): "Busca los domicilios, devuelve la cantidad y establece la lista" self.cursor.execute("SELECT direccion FROM domicilio WHERE " " tipo_doc=? AND nro_doc=? ORDER BY id ", [tipo_doc, ...
Busca los domicilios, devuelve la cantidad y establece la lista
def get_taf_alt_ice_turb(wxdata: [str]) -> ([str], str, [str], [str]): # type: ignore """ Returns the report list and removed: Altimeter string, Icing list, Turbulance list """ altimeter = '' icing, turbulence = [], [] for i, item in reversed(list(enumerate(wxdata))): if len(item) > 6 a...
Returns the report list and removed: Altimeter string, Icing list, Turbulance list
def as_report_request(self, rules, timer=datetime.utcnow): """Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determi...
Makes a `ServicecontrolServicesReportRequest` from this instance Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. timer: a function that determines the current time Return: a ``ServicecontrolServ...
def overlay(self, feature, color='Blue', opacity=0.6): """ Overlays ``feature`` on the map. Returns a new Map. Args: ``feature``: a ``Table`` of map features, a list of map features, a Map, a Region, or a circle marker map table. The features will be ...
Overlays ``feature`` on the map. Returns a new Map. Args: ``feature``: a ``Table`` of map features, a list of map features, a Map, a Region, or a circle marker map table. The features will be overlayed on the Map with specified ``color``. ``color`` (``st...
def grav_pot(self, x, y, rho0, gamma, center_x=0, center_y=0): """ gravitational potential (modulo 4 pi G and rho0 in appropriate units) :param x: :param y: :param rho0: :param a: :param s: :param center_x: :param center_y: :return: ...
gravitational potential (modulo 4 pi G and rho0 in appropriate units) :param x: :param y: :param rho0: :param a: :param s: :param center_x: :param center_y: :return:
def get_active_forms_state(self): """Extract ActiveForm INDRA Statements.""" for term in self._isolated_terms: act = term.find('features/active') if act is None: continue if act.text == 'TRUE': is_active = True elif act.text...
Extract ActiveForm INDRA Statements.
def _calculatePredictedCells(self, activeBasalSegments, activeApicalSegments): """ Calculate the predicted cells, given the set of active segments. An active basal segment is enough to predict a cell. An active apical segment is *not* enough to predict a cell. When a cell has both types of segment...
Calculate the predicted cells, given the set of active segments. An active basal segment is enough to predict a cell. An active apical segment is *not* enough to predict a cell. When a cell has both types of segments active, other cells in its minicolumn must also have both types of segments to be con...