positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and ei...
def _inherit_outputs(self, pipeline_name, already_defined, resolve_outputs=False): """Inherits outputs from a calling Pipeline. Args: pipeline_name: The Pipeline class name (used for debugging). already_defined: Maps output name t...
Inherits outputs from a calling Pipeline. Args: pipeline_name: The Pipeline class name (used for debugging). already_defined: Maps output name to stringified db.Key (of _SlotRecords) of any exiting output slots to be inherited by this future. resolve_outputs: When True, this method will d...
def create_instances(self, config_list): """Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance ...
Creates multiple virtual server instances. This takes a list of dictionaries using the same arguments as create_instance(). .. warning:: This will add charges to your account Example:: # Define the instance we want to create. new_vsi = { ...
def filter(self, names): """ Returns a list with the names matching the pattern. """ names = list_strings(names) fnames = [] for f in names: for pat in self.pats: if fnmatch.fnmatch(f, pat): fnames.append(f) return...
Returns a list with the names matching the pattern.
def _fulfills_version_spec(version, version_spec): ''' Check version number against version specification info and return a boolean value based on whether or not the version number meets the specified version. ''' for oper, spec in version_spec: if oper is None: continue ...
Check version number against version specification info and return a boolean value based on whether or not the version number meets the specified version.
def backendStatus(self, *args, **kwargs): """ Backend Status This endpoint is used to show when the last time the provisioner has checked in. A check in is done through the deadman's snitch api. It is done at the conclusion of a provisioning iteration and used to tell ...
Backend Status This endpoint is used to show when the last time the provisioner has checked in. A check in is done through the deadman's snitch api. It is done at the conclusion of a provisioning iteration and used to tell if the background provisioning process is still runnin...
def parse_addr(addr, *, proto=None, host=None): """Parses an address Returns: Address: the parsed address """ port = None if isinstance(addr, Address): return addr elif isinstance(addr, str): if addr.startswith('http://'): proto, addr = 'http', addr[7:] ...
Parses an address Returns: Address: the parsed address
def _read_mptcp_dss(self, bits, size, kind): """Read Data Sequence Signal (Data ACK and Data Sequence Mapping) option. Positional arguments: * bits - str, 4-bit data * size - int, length of option * kind - int, 30 (Multipath TCP) Returns: * dict ...
Read Data Sequence Signal (Data ACK and Data Sequence Mapping) option. Positional arguments: * bits - str, 4-bit data * size - int, length of option * kind - int, 30 (Multipath TCP) Returns: * dict -- extracted Data Sequence Signal (DSS) option ...
def set_static_ip_address(self, payload): """Set static ip address for a VM.""" # This request is received from CLI for setting ip address of an # instance. macaddr = payload.get('mac') ipaddr = payload.get('ip') # Find the entry associated with the mac in the database....
Set static ip address for a VM.
def libvlc_set_user_agent(p_instance, name, http): '''Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param p_instance: LibVLC instance. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "...
Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param p_instance: LibVLC instance. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0". @version: LibVLC 1.1.1 or ...
def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn): """Compute the CTC loss.""" del model_hparams, vocab_size # unused arg logits = top_out with tf.name_scope("ctc_loss", values=[logits, targets]): # For CTC we assume targets are 1d, [batch, length, 1, 1] here. targets_shape = ...
Compute the CTC loss.
def _compare_replication(current, desired, region, key, keyid, profile): ''' Replication accepts a non-ARN role name, but always returns an ARN ''' if desired is not None and desired.get('Role'): desired = copy.deepcopy(desired) desired['Role'] = _get_role_arn(desired['Role'], ...
Replication accepts a non-ARN role name, but always returns an ARN
def transport_jsonrpc(self): """ Installs the JSON-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.json_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discover...
Installs the JSON-RPC transport bundles and instantiates components
def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.Marath...
List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`]
def dms2dd(degrees, minutes, seconds, direction): """convert degrees, minutes, seconds to dd :param string direction: one of N S W E """ dd = (degrees + minutes/60.0) + (seconds/3600.0) # 60.0 fraction for python 2+ compatibility return dd * -1 if direction == 'S' or direction == 'W' else ...
convert degrees, minutes, seconds to dd :param string direction: one of N S W E
def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None): """ Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is pr...
Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_bgedge` method. :param bgedge: an edge to find most "simil...
def ignores_exc_tb(*args, **kwargs): """ PYTHON 2 ONLY VERSION -- needs to be in its own file for syntactic reasons ignore_exc_tb decorates a function and remove both itself and the function from any exception traceback that occurs. This is useful to decorate other trivial decorators which are...
PYTHON 2 ONLY VERSION -- needs to be in its own file for syntactic reasons ignore_exc_tb decorates a function and remove both itself and the function from any exception traceback that occurs. This is useful to decorate other trivial decorators which are polluting your stacktrace. if IGNORE_TRACEB...
def get_epoch_namespace_prices( block_height, units ): """ get the list of namespace prices by block height """ assert units in ['BTC', TOKEN_TYPE_STACKS], 'Invalid unit {}'.format(units) epoch_config = get_epoch_config( block_height ) if units == 'BTC': return epoch_config['namespace_...
get the list of namespace prices by block height
def delling_network(): """ Architecture according to Duelling DQN: https://arxiv.org/abs/1511.06581 """ @tt.model(tracker=tf.train.ExponentialMovingAverage(1 - .0005), # TODO: replace with original weight freeze optimizer=tf.train.RMSPropOptimizer(6.25e-5, .95, .95, .01)) ...
Architecture according to Duelling DQN: https://arxiv.org/abs/1511.06581
def get_all_bundle_tasks(self, bundle_ids=None, filters=None): """ Retrieve current bundling tasks. If no bundle id is specified, all tasks are retrieved. :type bundle_ids: list :param bundle_ids: A list of strings containing identifiers for previously...
Retrieve current bundling tasks. If no bundle id is specified, all tasks are retrieved. :type bundle_ids: list :param bundle_ids: A list of strings containing identifiers for previously created bundling tasks. :type filters: dict :param filters: Optio...
def _get_mixed_actions(labeling_bits, equation_tup, trans_recips): """ From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- ...
From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- labeling_bits : scalar(np.uint64) Integer with set bits representing...
def clear_further_steps(self): """Clear all further steps in order to properly calculate the prev step """ self.parent.step_kw_hazard_category.lstHazardCategories.clear() self.parent.step_kw_subcategory.lstSubcategories.clear() self.parent.step_kw_layermode.lstLayerModes.clear() ...
Clear all further steps in order to properly calculate the prev step
def add(self, path): """Add a path to the overlay filesytem. Any filesystem operation involving the this path or any sub-paths of it will be transparently redirected to temporary root dir. @path: An absolute path string. """ if not path.startswith(os.sep): r...
Add a path to the overlay filesytem. Any filesystem operation involving the this path or any sub-paths of it will be transparently redirected to temporary root dir. @path: An absolute path string.
def make_hmap(pmap, imtls, poes): """ Compute the hazard maps associated to the passed probability map. :param pmap: hazard curves in the form of a ProbabilityMap :param imtls: DictArray with M intensity measure types :param poes: P PoEs where to compute the maps :returns: a ProbabilityMap with...
Compute the hazard maps associated to the passed probability map. :param pmap: hazard curves in the form of a ProbabilityMap :param imtls: DictArray with M intensity measure types :param poes: P PoEs where to compute the maps :returns: a ProbabilityMap with size (N, M, P)
def format_page(text): """Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string. """ width = max(map(len, text.splitlines())) page = "+-" + "-" * width + "-+\n" for line in...
Format the text for output adding ASCII frame around the text. Args: text (str): Text that needs to be formatted. Returns: str: Formatted string.
def mission_request_partial_list_encode(self, target_system, target_component, start_index, end_index): ''' Request a partial list of mission items from the system/component. http://qgroundcontrol.org/mavlink/waypoint_protocol. If start and end index are t...
Request a partial list of mission items from the system/component. http://qgroundcontrol.org/mavlink/waypoint_protocol. If start and end index are the same, just send one waypoint. target_system : System ID (uint8_t) target_com...
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None): ''' Generate minion RSA public keypair ''' keydir, keyname, keysize, user = self._get_key_attrs(keydir, keyname, keysize, user) salt.crypt.gen_keys...
Generate minion RSA public keypair
def name(self, pretty=False): """ Return the name of the OS distribution, as a string. For details, see :func:`distro.name`. """ name = self.os_release_attr('name') \ or self.lsb_release_attr('distributor_id') \ or self.distro_release_attr('name') \ ...
Return the name of the OS distribution, as a string. For details, see :func:`distro.name`.
def set_implementation(self, impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ if impl.lower() == 'python': self.__impl__ = self.__IMPL_PYTHON__ elif impl.lower() == 'c':...
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]
def _get_prefix_length(number1, number2, bits): """Get the number of leading bits that are same for two numbers. Args: number1: an integer. number2: another integer. bits: the maximum number of bits to compare. Returns: The number of leading bits that are the same for two n...
Get the number of leading bits that are same for two numbers. Args: number1: an integer. number2: another integer. bits: the maximum number of bits to compare. Returns: The number of leading bits that are the same for two numbers.
def stream(identifier=None, priority=LOG_INFO, level_prefix=False): r"""Return a file object wrapping a stream to journal. Log messages written to this file as simple newline sepearted text strings are written to the journal. The file will be line buffered, so messages are actually sent after a ne...
r"""Return a file object wrapping a stream to journal. Log messages written to this file as simple newline sepearted text strings are written to the journal. The file will be line buffered, so messages are actually sent after a newline character is written. >>> from systemd import journal >>>...
def p_operation_definition4(self, p): """ operation_definition : operation_type name selection_set """ p[0] = self.operation_cls(p[1])(selections=p[3], name=p[2])
operation_definition : operation_type name selection_set
def check_requirements(to_populate, prompts, helper=False): ''' Iterates through required values, checking to_populate for required values If a key in prompts is missing in to_populate and ``helper==True``, prompts the user using the values in to_populate. Otherwise, raises an error. Parameter...
Iterates through required values, checking to_populate for required values If a key in prompts is missing in to_populate and ``helper==True``, prompts the user using the values in to_populate. Otherwise, raises an error. Parameters ---------- to_populate : dict Data dictionary to fill...
def is_topology(self, layers=None): ''' valid the topology ''' if layers is None: layers = self.layers layers_nodle = [] result = [] for i, layer in enumerate(layers): if layer.is_delete is False: layers_nodle.append(i) ...
valid the topology
def blit_2x( self, console: tcod.console.Console, dest_x: int, dest_y: int, img_x: int = 0, img_y: int = 0, img_width: int = -1, img_height: int = -1, ) -> None: """Blit onto a Console with double resolution. Args: console ...
Blit onto a Console with double resolution. Args: console (Console): Blit destination Console. dest_x (int): Console tile X position starting from the left at 0. dest_y (int): Console tile Y position starting from the top at 0. img_x (int): Left corner pixel of t...
def WriteOutput(title, locations, limit, f): """Write html to f for up to limit trips between locations. Args: title: String used in html title locations: list of (lat, lng) tuples limit: maximum number of queries in the html f: a file object """ output_prefix = """ <html> <head> <meta http-equ...
Write html to f for up to limit trips between locations. Args: title: String used in html title locations: list of (lat, lng) tuples limit: maximum number of queries in the html f: a file object
async def chain(*sources): """Chain asynchronous sequences together, in the order they are given. Note: the sequences are not iterated until it is required, so if the operation is interrupted, the remaining sequences will be left untouched. """ for source in sources: async with streamco...
Chain asynchronous sequences together, in the order they are given. Note: the sequences are not iterated until it is required, so if the operation is interrupted, the remaining sequences will be left untouched.
def update(self, new_data: Dict[Text, Dict[Text, Text]]): """ Receive an update from a loader. :param new_data: New translation data from the loader """ for locale, data in new_data.items(): if locale not in self.dict: self.dict[locale] = {} ...
Receive an update from a loader. :param new_data: New translation data from the loader
def get_url_by_label(self, label, asset_content_type=None): """stub""" return self._get_asset_content(self.get_asset_id_by_label(label)).get_url()
stub
def _iop(self, operation, other, *allowed): """An iterative operation operating on multiple values. Consumes iterators to construct a concrete list at time of execution. """ f = self._field if self._combining: # We are a field-compound query fragment, e.g. (Foo.bar & Foo.baz). return reduce(self....
An iterative operation operating on multiple values. Consumes iterators to construct a concrete list at time of execution.
def protocol(self): """The iperf3 instance protocol valid protocols are 'tcp' and 'udp' :rtype: str """ proto_id = self.lib.iperf_get_test_protocol_id(self._test) if proto_id == SOCK_STREAM: self._protocol = 'tcp' elif proto_id == SOCK_DGRAM: ...
The iperf3 instance protocol valid protocols are 'tcp' and 'udp' :rtype: str
def c2ln(c,l1,l2,n): "char[n] to two unsigned long???" c = c + n l1, l2 = U32(0), U32(0) f = 0 if n == 8: l2 = l2 | (U32(c[7]) << 24) f = 1 if f or (n == 7): l2 = l2 | (U32(c[6]) << 16) f = 1 if f or (n == 6): l2 = l2 | (U32(c[5]) << 8) f = 1 ...
char[n] to two unsigned long???
def _add_dominance_relation(self, source, target): """add a dominance relation to this docgraph""" # TODO: fix #39, so we don't need to add nodes by hand self.add_node(target, layers={self.ns, self.ns+':unit'}) self.add_edge(source, target, layers={self.ns, self.ns+...
add a dominance relation to this docgraph
def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]: """Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse. """ match = self._pattern.match(buf) if not match: raise N...
Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse.
def auto_levels_cb(self, setting, value): """Handle callback related to changes in auto-cut levels.""" # Did we change the method? method = self.t_['autocut_method'] params = self.t_.get('autocut_params', []) params = dict(params) if method != str(self.autocuts): ...
Handle callback related to changes in auto-cut levels.
def add_plugin(plugin, directory=None): """Adds the specified plugin. This returns False if it was already added.""" repo = require_repo(directory) plugins = get_value(repo, 'plugins', expect_type=dict) if plugin in plugins: return False plugins[plugin] = {} set_value(repo, 'plugins', p...
Adds the specified plugin. This returns False if it was already added.
def add_embed_field(self, **kwargs): """ set field of embed :keyword name: name of the field :keyword value: value of the field :keyword inline: (optional) whether or not this field should display inline """ self.fields.append({ 'name': kwargs.get('nam...
set field of embed :keyword name: name of the field :keyword value: value of the field :keyword inline: (optional) whether or not this field should display inline
def _set_adjustment_threshold(self, v, load=False): """ Setter method for adjustment_threshold, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/autobw_template/adjustment_threshold (container) If this variable is read-only (config: false) in the source YANG file, then _set_adjustment...
Setter method for adjustment_threshold, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/autobw_template/adjustment_threshold (container) If this variable is read-only (config: false) in the source YANG file, then _set_adjustment_threshold is considered as a private method. Backends looki...
def exit_sync(self): ''' Waiting for all threads to appear, then continue. ''' if self._scan_threads and self.current_module_handle not in [t.name for t in self._scan_threads]: raise RuntimeError('Thread name "%s" is not valid.') if self._scan_threads and self.current_module_...
Waiting for all threads to appear, then continue.
def get_by_name(self, name, style_type = None): """Find style by it's descriptive name. :Returns: Returns found style of type :class:`ooxml.doc.Style`. """ for st in self.styles.values(): if st: if st.name == name: return st ...
Find style by it's descriptive name. :Returns: Returns found style of type :class:`ooxml.doc.Style`.
def POST(self, *args, **kwargs): """ POST request """ return self._handle_api(self.API_POST, args, kwargs)
POST request
def start(self): """Public method for initiating connectivity with the emby server.""" asyncio.ensure_future(self.register(), loop=self._event_loop) if self._own_loop: _LOGGER.info("Starting up our own event loop.") self._event_loop.run_forever() self._event_...
Public method for initiating connectivity with the emby server.
def parse(self, data, extent): # type: (bytes, int) -> None ''' Parse the passed in data into a UDF NSR Volume Structure. Parameters: data - The data to parse. extent - The extent that this descriptor currently lives at. Returns: Nothing. ''' ...
Parse the passed in data into a UDF NSR Volume Structure. Parameters: data - The data to parse. extent - The extent that this descriptor currently lives at. Returns: Nothing.
def derivative(f, t): """Fourth-order finite-differencing with non-uniform time steps The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a ...
Fourth-order finite-differencing with non-uniform time steps The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a fourth-order formula -- th...
def send(self, data, opcode=ABNF.OPCODE_TEXT): """ send message. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ if not self.sock or self.sock.send(da...
send message. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT.
def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} if 'word' in _dict: args['word'] = _dict.get('word') else: raise ValueError( 'Required property \'word\' not present in Word JSON') if 'sounds_like...
Initialize a Word object from a json dictionary.
def vn_info(call=None, kwargs=None): ''' Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gathe...
Retrieves information for the virtual network. .. versionadded:: 2016.3.0 name The name of the virtual network for which to gather information. Can be used instead of ``vn_id``. vn_id The ID of the virtual network for which to gather information. Can be used instead of ``n...
def save_filelist(self, opFile, opFormat, delim=',', qu='"'): """ uses a List of files and collects meta data on them and saves to an text file as a list or with metadata depending on opFormat. """ op_folder = os.path.dirname(opFile) if op_folder is not None: # ...
uses a List of files and collects meta data on them and saves to an text file as a list or with metadata depending on opFormat.
def resource_types(self): """resource types used by the collection.""" rtypes = set() for p in self.policies: rtypes.add(p.resource_type) return rtypes
resource types used by the collection.
def _synthesize_single_python_helper( self, text, voice_code, output_file_path=None, return_audio_data=True ): """ This is an helper function to synthesize a single text fragment via a Python call. If ``output_file_path`` is ``None``, the audi...
This is an helper function to synthesize a single text fragment via a Python call. If ``output_file_path`` is ``None``, the audio data will not persist to file at the end of the method. :rtype: tuple (result, (duration, sample_rate, encoding, data))
def quantile(x, q, interpolation_method='fraction'): """ Compute sample quantile or quantiles of the input array. For example, q=0.5 computes the median. The `interpolation_method` parameter supports three values, namely `fraction` (default), `lower` and `higher`. Interpolation is done only, if...
Compute sample quantile or quantiles of the input array. For example, q=0.5 computes the median. The `interpolation_method` parameter supports three values, namely `fraction` (default), `lower` and `higher`. Interpolation is done only, if the desired quantile lies between two data points `i` and `j`. F...
def from_two_bytes(bytes): """ Return an integer from two 7 bit bytes. """ lsb, msb = bytes try: # Usually bytes have been converted to integers with ord already return msb << 7 | lsb except TypeError: # But add this for easy testing # One of them can be a string,...
Return an integer from two 7 bit bytes.
def list(self, **kwargs): """ https://api.slack.com/methods/groups.list """ if kwargs: self.params.update(kwargs) return FromUrl('https://slack.com/api/groups.list', self._requests)(data=self.params).get()
https://api.slack.com/methods/groups.list
def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos): ''' Searches for the next location where a valid block could reside and constructs the block object representing that location. ''' for row_index in range(len(table)): if row_...
Searches for the next location where a valid block could reside and constructs the block object representing that location.
def lstm_seq2seq_internal_attention_bid_encoder(inputs, targets, hparams, train): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention_bid_encoder"): inputs_length = common_layers.length_from_embeddin...
LSTM seq2seq model with attention, main step used for training.
def b58encode(b, errors='strict'): "Encode bytes to a base58-encoded string." len_ = len(b) # Convert big-endian bytes to integer n = BigInteger.deserialize(BytesIO(b), len_) # Divide that integer into base58 res = [] while n > 0: n, r = divmod (n, 58) res.append(b58digits[...
Encode bytes to a base58-encoded string.
def _determine_heterogen_chain_type(residue_types): '''We distinguish three types of heterogen chain: i) all solution; ii) all ligand; or iii) other (a mix of solution, ligand, and/or ions). residue_types should be a Set of sequence identifers e.g. GTP, ZN, HOH. ''' residue_type_id_le...
We distinguish three types of heterogen chain: i) all solution; ii) all ligand; or iii) other (a mix of solution, ligand, and/or ions). residue_types should be a Set of sequence identifers e.g. GTP, ZN, HOH.
def get_user_profile_photos(self, user_id, offset=None, limit=None): """ Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos :param user_id: :param offset: :param limit: :return: API reply. ...
Retrieves the user profile photos of the person with 'user_id' See https://core.telegram.org/bots/api#getuserprofilephotos :param user_id: :param offset: :param limit: :return: API reply.
def _build_request(self, method, url, params=None): """Build a function to do an API request "We have to go deeper" or "It's functions all the way down!" """ full_params = self._get_base_params() if params is not None: full_params.update(params) try: ...
Build a function to do an API request "We have to go deeper" or "It's functions all the way down!"
def doc_open(): """Build the HTML docs and open them in a web browser.""" doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows sub...
Build the HTML docs and open them in a web browser.
def lyap_e_len(**kwargs): """ Helper function that calculates the minimum number of data points required to use lyap_e. Note that none of the required parameters may be set to None. Kwargs: kwargs(dict): arguments used for lyap_e (required: emb_dim, matrix_dim, min_nb and min_tsep) Return...
Helper function that calculates the minimum number of data points required to use lyap_e. Note that none of the required parameters may be set to None. Kwargs: kwargs(dict): arguments used for lyap_e (required: emb_dim, matrix_dim, min_nb and min_tsep) Returns: minimum number of data poin...
def readlinkabs(l): """ Return an absolute path for the destination of a symlink """ assert (os.path.islink(l)) p = os.readlink(l) if os.path.isabs(p): return os.path.abspath(p) return os.path.abspath(os.path.join(os.path.dirname(l), p))
Return an absolute path for the destination of a symlink
def login(self, login, password, url=None): """login page """ auth = self._auth(login, password) cherrypy.session['isadmin'] = auth['isadmin'] cherrypy.session['connected'] = auth['connected'] if auth['connected']: if auth['isadmin']: message ...
login page
def querytime(self, value): """ Sets self._querytime as well as self.query.querytime. :param value: None or datetime :return: """ self._querytime = value self.query.querytime = value
Sets self._querytime as well as self.query.querytime. :param value: None or datetime :return:
def local_voxelize(mesh, point, pitch, radius, fill=True, **kwargs): """ Voxelize a mesh in the region of a cube around a point. When fill=True, uses proximity.contains to fill the resulting voxels so may be meaningless for non-watertight meshes. Useful to reduce memory cost for small values of pitc...
Voxelize a mesh in the region of a cube around a point. When fill=True, uses proximity.contains to fill the resulting voxels so may be meaningless for non-watertight meshes. Useful to reduce memory cost for small values of pitch as opposed to global voxelization. Parameters ----------- mesh : t...
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]: """Get jobs from a queue.""" jobs_json_string = self._run_script( self._get_jobs_from_queue, self._to_namespaced(queue), self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)), JobStatu...
Get jobs from a queue.
def get_macs(vm_): ''' Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name> ''' macs = [] nics = get_nics(vm_) if nics is None: return None for nic in nics: macs.append(nic) return macs
Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name>
def count(self, with_limit_and_skip=False): """Get the size of the results set for this query. Returns the number of documents in the results set for this query. Does not take :meth:`limit` and :meth:`skip` into account by default - set `with_limit_and_skip` to ``True`` if that is the d...
Get the size of the results set for this query. Returns the number of documents in the results set for this query. Does not take :meth:`limit` and :meth:`skip` into account by default - set `with_limit_and_skip` to ``True`` if that is the desired behavior. Raises :class:`~pymongo.errors...
def update_instance_extent(self, instance, module, operation): """Updates a new instance that was added to a module to be complete if the end token is present in any remaining, overlapping operations. """ #Essentially, we want to look in the rest of the statements that are #part ...
Updates a new instance that was added to a module to be complete if the end token is present in any remaining, overlapping operations.
def temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None, min_t=None,max_t=None,weight_function=None,normalize_time=False, normalize_n=False,start_units_with_0=True,cell_dimension='N'): """ Outputs a time histogram of spikes. ...
Outputs a time histogram of spikes. `bins`: number of bins (default is 1ms bins from 0 to t_max) `weight_function`: if set, computes a weighted histogram, dependent on the (index, time) tuples of each spike weight_function = lambda x: weight_map.flatten()[array(x[:,0],dtype...
def start(): ''' Start simple_server() ''' from wsgiref.simple_server import make_server # When started outside of salt-api __opts__ will not be injected if '__opts__' not in globals(): globals()['__opts__'] = get_opts() if __virtual__() is False: raise SystemExit(1...
Start simple_server()
def get_user_metadata( self, bucket: str, key: str ) -> typing.Dict[str, str]: """ Retrieves the user metadata for a given object in a given bucket. If the platform has any mandatory prefixes or suffixes for the metadata keys, they should be stripped befo...
Retrieves the user metadata for a given object in a given bucket. If the platform has any mandatory prefixes or suffixes for the metadata keys, they should be stripped before being returned. :param bucket: the bucket the object resides in. :param key: the key of the object for which metadata is...
def StartFlow(client_id=None, cpu_limit=None, creator=None, flow_args=None, flow_cls=None, network_bytes_limit=None, original_flow=None, output_plugins=None, start_at=None, parent_flow_obj=None,...
The main factory function for creating and executing a new flow. Args: client_id: ID of the client this flow should run on. cpu_limit: CPU limit in seconds for this flow. creator: Username that requested this flow. flow_args: An arg protocol buffer which is an instance of the required flow's ar...
def load(self, draw_bbox = False, **kwargs): ''' Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts ''' im = Image.new('RGBA', self.img_size) draw = None if draw_bbox: ...
Makes the canvas. This could be far speedier if it copied raw pixels, but that would take far too much time to write vs using Image inbuilts
def body_template(self, value): """ Must be an instance of a prestans.types.DataCollection subclass; this is generally set during the RequestHandler lifecycle. Setting this spwans the parsing process of the body. If the HTTP verb is GET an AssertionError is thrown. Use with extre...
Must be an instance of a prestans.types.DataCollection subclass; this is generally set during the RequestHandler lifecycle. Setting this spwans the parsing process of the body. If the HTTP verb is GET an AssertionError is thrown. Use with extreme caution.
def find_args(self, text, start=None): """implementation details""" if start is None: start = 0 first_occurance = text.find(self.__begin, start) if first_occurance == -1: return self.NOT_FOUND previous_found, found = first_occurance + 1, 0 while Tr...
implementation details
def get_supports(self): """Returns set of extension support strings referenced in this Registry :return: set of extension support strings """ out = set() for ext in self.extensions.values(): out.update(ext.get_supports()) return out
Returns set of extension support strings referenced in this Registry :return: set of extension support strings
def create_topic_rule(ruleName, sql, actions, description, ruleDisabled=False, region=None, key=None, keyid=None, profile=None): ''' Given a valid config, create a topic rule. Returns {created: true} if the rule was created and returns {created: False} if the rule was not create...
Given a valid config, create a topic rule. Returns {created: true} if the rule was created and returns {created: False} if the rule was not created. CLI Example: .. code-block:: bash salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\ '[{"lambda":{"fu...
def aggregate_precipitation(vec_data,hourly=True, percentile=50): """Aggregates highly resolved precipitation data and creates statistics Parameters ---------- vec_data : pd.Series hourly (hourly=True) OR 5-min values Returns ------- output : cascade object representing st...
Aggregates highly resolved precipitation data and creates statistics Parameters ---------- vec_data : pd.Series hourly (hourly=True) OR 5-min values Returns ------- output : cascade object representing statistics of the cascade model
def build_path(graph, node1, node2, path=None): """ Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path. """ if path is None: path = [] ...
Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path.
def complex_space(self): """The space corresponding to this space's `complex_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type. """ if not is_numeric_dtype(self.dtype): raise ValueError( '`complex_space` not de...
The space corresponding to this space's `complex_dtype`. Raises ------ ValueError If `dtype` is not a numeric data type.
def _read_data_type_none(self, length): """Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | ...
Read IPv6-Route unknown type data. Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Routing Type | Segments Left | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
def join(delim, items, quotes=False): """ Joins the supplied list of strings after removing any empty strings from the list """ transform = lambda s: s if quotes == True: transform = lambda s: s if ' ' not in s else '"{}"'.format(s) stripped = list([transform(i) for i in items if len(i) > 0]) if len...
Joins the supplied list of strings after removing any empty strings from the list
def _scalar_property(fieldname): """Create a property descriptor around the :class:`_PropertyMixin` helpers. """ def _getter(self): """Scalar property getter.""" return self._properties.get(fieldname) def _setter(self, value): """Scalar property setter.""" self._patch_p...
Create a property descriptor around the :class:`_PropertyMixin` helpers.
def setup_ui(self, ): """Setup the ui :returns: None :rtype: None :raises: None """ labels = self.reftrack.get_option_labels() self.browser = ComboBoxBrowser(len(labels), headers=labels) self.browser_vbox.addWidget(self.browser)
Setup the ui :returns: None :rtype: None :raises: None
def napalm_cli(task: Task, commands: List[str]) -> Result: """ Run commands on remote devices using napalm Arguments: commands: commands to execute Returns: Result object with the following attributes set: * result (``dict``): result of the commands execution """ devi...
Run commands on remote devices using napalm Arguments: commands: commands to execute Returns: Result object with the following attributes set: * result (``dict``): result of the commands execution
def __CombineGlobalParams(self, global_params, default_params): """Combine the given params with the defaults.""" util.Typecheck(global_params, (type(None), self.__client.params_type)) result = self.__client.params_type() global_params = global_params or self.__client.params_type() ...
Combine the given params with the defaults.
def gpg_version(sp=subprocess): """Get a keygrip of the primary GPG key of the specified user.""" args = gpg_command(['--version']) output = check_output(args=args, sp=sp) line = output.split(b'\n')[0] # b'gpg (GnuPG) 2.1.11' line = line.split(b' ')[-1] # b'2.1.11' line = line.split(b'-')[0] ...
Get a keygrip of the primary GPG key of the specified user.
def init_app(self, app, env_file=None, verbose_mode=False): """Imports .env file.""" if self.app is None: self.app = app self.verbose_mode = verbose_mode if env_file is None: env_file = os.path.join(os.getcwd(), ".env") if not os.path.exists(env_file): ...
Imports .env file.
def _load_version(cls, unpickler, version): """ A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer...
A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer.