code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def create_tipo_equipamento(self): """Get an instance of tipo_equipamento services facade.""" return TipoEquipamento( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of tipo_equipamento services facade.
def default_interface(ifconfig=None, route_output=None): """ Return just the default interface device dictionary. :param ifconfig: For mocking actual command output :param route_output: For mocking actual command output """ global Parser return Parser(ifconfig=ifconfig)._default_interface(r...
Return just the default interface device dictionary. :param ifconfig: For mocking actual command output :param route_output: For mocking actual command output
def update(self, data, ed): """Processes the given ciphertext/plaintext Inputs: data: raw string of any length ed: 'e' for encryption, 'd' for decryption Output: processed raw string block(s), if any When the supplied data is not a multiple of the ...
Processes the given ciphertext/plaintext Inputs: data: raw string of any length ed: 'e' for encryption, 'd' for decryption Output: processed raw string block(s), if any When the supplied data is not a multiple of the blocksize of the cipher, then...
def is_vhost_alive(self, vhost): """ Declares a test queue, then publishes and consumes a message. Intended for use by monitoring tools. :param vhost: The vhost name to check :type vhost: str """ return self._api_get('/api/aliveness-test/{0}'.format( ...
Declares a test queue, then publishes and consumes a message. Intended for use by monitoring tools. :param vhost: The vhost name to check :type vhost: str
def write(self, pkt): """ Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes """ if isinstance(pkt, bytes): ...
Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes
def all_low_level_calls(self): """ recursive version of low_level calls """ if self._all_low_level_calls is None: self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls) return self._all_low_level_calls
recursive version of low_level calls
def sample(self, hash, limit=None, offset=None): '''Return an object representing the sample identified by the input hash, or an empty object if that sample is not found''' uri = self._uris['sample'].format(hash) params = {'limit': limit, 'offset': offset} return self.get_parse(uri, pa...
Return an object representing the sample identified by the input hash, or an empty object if that sample is not found
def _write_image_description(self): """Write metadata to ImageDescription tag.""" if (not self._datashape or self._datashape[0] == 1 or self._descriptionoffset <= 0): return colormapped = self._colormap is not None if self._imagej: isrgb = self._s...
Write metadata to ImageDescription tag.
def GetTimeOfDay(self): """Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, None, None) if the date and time values do not represent a time of day. """ normalized_timestamp = self._GetNormalizedTimestam...
Retrieves the time of day represented by the date and time values. Returns: tuple[int, int, int]: hours, minutes, seconds or (None, None, None) if the date and time values do not represent a time of day.
def cubic_interpolate(x, y, precision=250, **kwargs): """ Interpolate x, y using a cubic algorithm https://en.wikipedia.org/wiki/Spline_interpolation """ n = len(x) - 1 # Spline equation is a + bx + cx² + dx³ # ie: Spline part i equation is a[i] + b[i]x + c[i]x² + d[i]x³ a = y b = [0...
Interpolate x, y using a cubic algorithm https://en.wikipedia.org/wiki/Spline_interpolation
def voltage_based(feedin, generators, curtailment_timeseries, edisgo, curtailment_key, **kwargs): """ Implements curtailment methodology 'voltage-based'. The curtailment that has to be met in each time step is allocated depending on the exceedance of the allowed voltage deviation at t...
Implements curtailment methodology 'voltage-based'. The curtailment that has to be met in each time step is allocated depending on the exceedance of the allowed voltage deviation at the nodes of the generators. The higher the exceedance, the higher the curtailment. The optional parameter `voltage_thre...
def _unlock(self): """ Unlock this keyring by getting the password for the keyring from the user. """ self.keyring_key = getpass.getpass( 'Please enter password for encrypted keyring: ') try: ref_pw = self.get_password('keyring-setting', 'password ...
Unlock this keyring by getting the password for the keyring from the user.
def hook(self, pc): """ A decorator used to register a hook function for a given instruction address. Equivalent to calling :func:`~add_hook`. :param pc: Address of instruction to hook :type pc: int or None """ def decorator(f): self.add_hook(pc, f) ...
A decorator used to register a hook function for a given instruction address. Equivalent to calling :func:`~add_hook`. :param pc: Address of instruction to hook :type pc: int or None
def _PrPz(r0, z0, r1, z1, r2, z2, r3, z3): """ Intersection point for infinite lines. Parameters ---------- r0 : float z0 : float r1 : float z1 : float r2 : float z2 : float r3 : float z3 : float Returns ---------- Pr : float Pz : float hit :...
Intersection point for infinite lines. Parameters ---------- r0 : float z0 : float r1 : float z1 : float r2 : float z2 : float r3 : float z3 : float Returns ---------- Pr : float Pz : float hit : bool
def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[RequiredAttributeError]: """ Validates to ensure that a set of attributes are present in spec """ return [ RequiredAttributeError(fully_qualified_name, spec, attri...
Validates to ensure that a set of attributes are present in spec
def get(self, id, domain='messages'): """ Gets a message translation. @rtype: str @return: The message translation """ assert isinstance(id, (str, unicode)) assert isinstance(domain, (str, unicode)) if self.defines(id, domain): return self.me...
Gets a message translation. @rtype: str @return: The message translation
async def get_pypi_version(self): """Get version published to PyPi.""" self._version_data["beta"] = self.beta self._version_data["source"] = "PyPi" info_version = None last_release = None try: async with async_timeout.timeout(5, loop=self.loop): ...
Get version published to PyPi.
def matched_interpreters(interpreters, constraints): """Given some filters, yield any interpreter that matches at least one of them. :param interpreters: a list of PythonInterpreter objects for filtering :param constraints: A sequence of strings that constrain the interpreter compatibility for this pex. Each...
Given some filters, yield any interpreter that matches at least one of them. :param interpreters: a list of PythonInterpreter objects for filtering :param constraints: A sequence of strings that constrain the interpreter compatibility for this pex. Each string uses the Requirement-style format, e.g. 'CPython>=...
def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file """ with open(path, 'r') as fh: ...
Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file
def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/...
Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags Returns: ...
def merge_entries_with_common_prefixes(list_, number_of_needed_commons=6): """ Returns a list where sequences of post-fixed entries are shortened to their common prefix. This might be useful in cases of several similar values, where the prefix is identical for several entries. If less than 'number_o...
Returns a list where sequences of post-fixed entries are shortened to their common prefix. This might be useful in cases of several similar values, where the prefix is identical for several entries. If less than 'number_of_needed_commons' are identically prefixed, they are kept unchanged. Example: ['tes...
def sample_qubo(self, qubo, **params): """Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. ...
Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. Returns: :obj:`Future` Exa...
def run_coral(clus_obj, out_dir, args): """ Run some CoRaL modules to predict small RNA function """ if not args.bed: raise ValueError("This module needs the bed file output from cluster subcmd.") workdir = op.abspath(op.join(args.out, 'coral')) safe_dirs(workdir) bam_in = op.abspath...
Run some CoRaL modules to predict small RNA function
def institutes(context, institute_id, json): """Show all institutes in the database""" LOG.info("Running scout view institutes") adapter = context.obj['adapter'] if institute_id: institute_objs = [] institute_obj = adapter.institute(institute_id) if not institute_obj: ...
Show all institutes in the database
def convert_flatten(net, node, module, builder): """Convert a flatten layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neu...
Convert a flatten layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
def create_option_group(name, engine_name, major_engine_version, option_group_description, tags=None, region=None, key=None, keyid=None, profile=None): ''' Create an RDS option group CLI example to create an RDS option group:: salt myminion boto_rds....
Create an RDS option group CLI example to create an RDS option group:: salt myminion boto_rds.create_option_group my-opt-group mysql 5.6 \ "group description"
def normalise_tensor(tensor): ''' Normalise the tensor by dividing it by its norm, defined such that np.sqrt(X:X) ''' tensor_norm = np.linalg.norm(tensor) return tensor / tensor_norm, tensor_norm
Normalise the tensor by dividing it by its norm, defined such that np.sqrt(X:X)
def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparams
With sequence length 4096.
def iterchunks(data, chunksize): """iterate chunks of data """ offt = 0 while offt < len(data): yield data[offt:offt+chunksize] offt += chunksize
iterate chunks of data
def move(self, module_path, configuration=True, module=True): """Move the submodule to a another module path. This involves physically moving the repository at our current path, changing the configuration, as well as adjusting our index entry accordingly. :param module_path: the path to...
Move the submodule to a another module path. This involves physically moving the repository at our current path, changing the configuration, as well as adjusting our index entry accordingly. :param module_path: the path to which to move our module in the parent repostory's working tree, ...
def select_join(self, table, field, join_table, join_field): """.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null; """...
.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null;
def addFilter(self, layer_id, where=None, outFields="*"): """ adds a layer definition filter """ import copy f = copy.deepcopy(self._filterTemplate) f['layerId'] = layer_id f['outFields'] = outFields if where is not None: f['where'] = where if f not in...
adds a layer definition filter
def EnablePlugins(self, plugin_includes): """Enables parser plugins. Args: plugin_includes (list[str]): names of the plugins to enable, where None or an empty list represents all plugins. Note that the default plugin is handled separately. """ super(SyslogParser, self).EnableP...
Enables parser plugins. Args: plugin_includes (list[str]): names of the plugins to enable, where None or an empty list represents all plugins. Note that the default plugin is handled separately.
def get_dist(self): """Return a pkg_resources.Distribution built from self.egg_info_path""" egg_info = self.egg_info_path('').rstrip('/') base_dir = os.path.dirname(egg_info) metadata = pkg_resources.PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(e...
Return a pkg_resources.Distribution built from self.egg_info_path
def _partition_species(composition, max_components=2): """ Private method to split a list of species into various partitions. """ def _partition(collection): # thanks https://stackoverflow.com/a/30134039 if len(collection) == 1: yield [co...
Private method to split a list of species into various partitions.
def chambers(self): """ Return distinct chambers. You probably want to prefetch documents__chamber before calling that. """ # Use sorted() because using order_by will hit the database no matter # what was prefetched return set(sorted([d.chamber for d in self.docu...
Return distinct chambers. You probably want to prefetch documents__chamber before calling that.
def rmdir(store, path=None): """Remove all items under the given path. If `store` provides a `rmdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'rmdir'): # pass through ...
Remove all items under the given path. If `store` provides a `rmdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.
def get_system_time(): ''' Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time ''' now = win32api.GetLocalTime() meridian = 'AM' hours = int(now[4]) if h...
Get the system time. Returns: str: Returns the system time in HH:MM:SS AM/PM format. CLI Example: .. code-block:: bash salt 'minion-id' system.get_system_time
def init_process(self): """ init a standard daq process for a single device """ self.device = Device.objects.filter(protocol__daq_daemon=1, active=1, id=self.device_id).first() if not self.device: logger.error("Error init_process for %s" % self.device_id) ...
init a standard daq process for a single device
def create_html(api_key, attrs): '''Returns complete html tag string.''' gif = get_gif(api_key, attrs['gif_id']) if 'alt' not in attrs.keys(): attrs['alt'] = 'source: {}'.format(gif['data']['source']) html_out = '<a href="{}">'.format(gif['data']['url']) html_out += '<img src="{}" alt="{}"...
Returns complete html tag string.
def doit(self, classes=None, recursive=True, **kwargs): """Rewrite (sub-)expressions in a more explicit form Return a modified expression that is more explicit than the original expression. The definition of "more explicit" is decided by the relevant subclass, e.g. a :meth:`Commutator <...
Rewrite (sub-)expressions in a more explicit form Return a modified expression that is more explicit than the original expression. The definition of "more explicit" is decided by the relevant subclass, e.g. a :meth:`Commutator <.Commutator.doit>` is written out according to its definiti...
def get_role(self, account_id, role_id): """ Get information about a single role, for the passed Canvas account ID. https://canvas.instructure.com/doc/api/roles.html#method.role_overrides.show """ url = ACCOUNTS_API.format(account_id) + "/roles/{}".format(role_id) return...
Get information about a single role, for the passed Canvas account ID. https://canvas.instructure.com/doc/api/roles.html#method.role_overrides.show
def _action(self, action): """do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! ...
do something! What you do is determined by the argument: 1 Output A. Copy B to A. Get the next B. 2 Copy B to A. Get the next B. (Delete A). 3 Get the next B. (Delete B). action treats a string as a single character. Wow! action recognizes a regular expressio...
def stationary_distribution_from_backward_iteration(P, eps=1e-15): r"""Fast computation of the stationary vector using backward iteration. Parameters ---------- P : (M, M) scipy.sparse matrix Transition matrix eps : float (optional) Perturbation parameter for the true eigenvalue...
r"""Fast computation of the stationary vector using backward iteration. Parameters ---------- P : (M, M) scipy.sparse matrix Transition matrix eps : float (optional) Perturbation parameter for the true eigenvalue. Returns ------- pi : (M,) ndarray Stationary vec...
def main(): """ Prototype to see how an RPG simulation might be used in the AIKIF framework. The idea is to build a simple character and run a simulation to see how it succeeds in a random world against another players character character stats world locations ""...
Prototype to see how an RPG simulation might be used in the AIKIF framework. The idea is to build a simple character and run a simulation to see how it succeeds in a random world against another players character character stats world locations
def handle(self, *args, **options): """ Queues the function given with the first argument with the parameters given with the rest of the argument list. """ verbosity = int(options.get('verbosity', 1)) timeout = options.get('timeout') queue = get_queue(options.get(...
Queues the function given with the first argument with the parameters given with the rest of the argument list.
def load_tasks_from_file(self, file_path): """ Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is Cust...
Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself ...
def get_action(self, action): """Get a callable action.""" func_name = action.replace('-', '_') if not hasattr(self, func_name): # Function doesn't exist raise DaemonError( 'Invalid action "{action}"'.format(action=action)) func = getattr(self, fu...
Get a callable action.
def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None): """For each selected base estimator, average models trained on each fold""" fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object) for i, idx in enumerate(idx_models_included): mod...
For each selected base estimator, average models trained on each fold
def f_to_dict(self, fast_access=False, short_names=False, nested=False, copy=True, with_links=True): """Returns a dictionary with pairings of (full) names as keys and instances/values. :param fast_access: If True, parameter values are returned instead of the instances. ...
Returns a dictionary with pairings of (full) names as keys and instances/values. :param fast_access: If True, parameter values are returned instead of the instances. Works also for results if they contain a single item with the name of the result. :param short_names: ...
def _get_next_occurrence(haystack, offset, needles): """ Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found""" # make map of first char to full needle (only works if all needles # have di...
Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found
def unpack(self, key, value): """Unpack and return value only if it is fresh.""" value, freshness = value if not self.is_fresh(freshness): raise KeyError('{} (stale)'.format(key)) return value
Unpack and return value only if it is fresh.
def _getBasicOrbit(self, orbit=None): """Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed, negative indexes allowed, -1 last orbit Note ---- A day of data must be loaded before this routine ...
Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed, negative indexes allowed, -1 last orbit Note ---- A day of data must be loaded before this routine functions properly. If the last orbit of ...
def _add_workflow(mcs, field_name, state_field, attrs): """Attach a workflow to the attribute list (create a StateProperty).""" attrs[field_name] = StateProperty(state_field.workflow, field_name)
Attach a workflow to the attribute list (create a StateProperty).
def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False): """Setup a mask where all pixels are unmasked. Parameters ---------- shape : (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pix...
Setup a mask where all pixels are unmasked. Parameters ---------- shape : (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pixel conversion factor of each pixel.
def appendbcolz(table, obj, check_names=True): """Append data into a bcolz ctable. The `obj` argument can be either an existing ctable or the name of a directory were an on-disk ctable is stored. .. versionadded:: 1.1.0 """ import bcolz import numpy as np if isinstance(obj, string_ty...
Append data into a bcolz ctable. The `obj` argument can be either an existing ctable or the name of a directory were an on-disk ctable is stored. .. versionadded:: 1.1.0
def filesize(value): '''Display a human readable filesize''' suffix = 'o' for unit in '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z': if abs(value) < 1024.0: return "%3.1f%s%s" % (value, unit, suffix) value /= 1024.0 return "%.1f%s%s" % (value, 'Y', suffix)
Display a human readable filesize
def _evaluatephiforces(Pot,R,z,phi=None,t=0.,v=None): """Raw, undecorated function for internal use""" isList= isinstance(Pot,list) nonAxi= _isNonAxi(Pot) if nonAxi and phi is None: raise PotentialError("The (list of) Potential instances is non-axisymmetric, but you did not provide phi") dis...
Raw, undecorated function for internal use
def _enable_logpersist(self): """Attempts to enable logpersist daemon to persist logs.""" # Logpersist is only allowed on rootable devices because of excessive # reads/writes for persisting logs. if not self._ad.is_rootable: return logpersist_warning = ('%s encounter...
Attempts to enable logpersist daemon to persist logs.
def join(self, userId, groupId, groupName): """ 将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 方法 @param userId:要加入群的用户 Id,可提交多个,最多不超过 1000 个。(必传) @param groupId:要加入的群 Id。(必传) @param groupName:要加入的群 Id 对应的名称。(必传) @return code:返回码,200 为正常。 @return err...
将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 方法 @param userId:要加入群的用户 Id,可提交多个,最多不超过 1000 个。(必传) @param groupId:要加入的群 Id。(必传) @param groupName:要加入的群 Id 对应的名称。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
def datediff(end, start): """ Returns the number of days from `start` to `end`. >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2']) >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect() [Row(diff=32)] """ sc = SparkContext._active_spark_context return Col...
Returns the number of days from `start` to `end`. >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2']) >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect() [Row(diff=32)]
def _needSwapWH(self, oldDirection, newDirection ): """! \~english return screen direction status @return Boolean @note No need to rotate if the screen orientation is 0 degrees and 180 degrees \~chinese 返回屏幕方向状态 @return 布尔值 @note 如果屏幕方向是0度和180度就不需...
! \~english return screen direction status @return Boolean @note No need to rotate if the screen orientation is 0 degrees and 180 degrees \~chinese 返回屏幕方向状态 @return 布尔值 @note 如果屏幕方向是0度和180度就不需要旋转
def learnPlaceCode(self, runs, dir=1, periodic=False, recurrent=True, randomSpeed=False, learnRecurrent=False): """ Traverses a sinusoidal trajectory across the environment, learning dur...
Traverses a sinusoidal trajectory across the environment, learning during the process. A pair of runs across the environment (one in each direction) takes 10 seconds if in a periodic larger environment, and 4 seconds in a smaller nonperiodic environment. :param runs: How many runs across the environmen...
def _setBorder(self, border, doc, xref): """_setBorder(self, border, doc, xref) -> PyObject *""" return _fitz.Link__setBorder(self, border, doc, xref)
_setBorder(self, border, doc, xref) -> PyObject *
def dump_to_string(self, cnf, **opts): """ :param cnf: Configuration data to dump :param opts: optional keyword parameters :return: string represents the configuration """ tree = container_to_etree(cnf, **opts) buf = BytesIO() etree_write(tree, buf) ...
:param cnf: Configuration data to dump :param opts: optional keyword parameters :return: string represents the configuration
def system_status(self): """The system status codes.""" flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer))) return { # convert unix timestamp to datetime object 'timestamp': datetime.datetime.fromtimestamp(timestamp), # bit 0-3 repr...
The system status codes.
def _prepare_record(self, group): """ compute record dtype and parents dict for this group Parameters ---------- group : dict MDF group dict Returns ------- parents, dtypes : dict, numpy.dtype mapping of channels to records fields, record...
compute record dtype and parents dict for this group Parameters ---------- group : dict MDF group dict Returns ------- parents, dtypes : dict, numpy.dtype mapping of channels to records fields, records fiels dtype
def idna_encode (host): """Encode hostname as internationalized domain name (IDN) according to RFC 3490. @raise: UnicodeError if hostname is not properly IDN encoded. """ if host and isinstance(host, unicode): try: host.encode('ascii') return host, False excep...
Encode hostname as internationalized domain name (IDN) according to RFC 3490. @raise: UnicodeError if hostname is not properly IDN encoded.
def _handle_clear(self, load): ''' Process a cleartext command :param dict load: Cleartext payload :return: The result of passing the load to a function in ClearFuncs corresponding to the command specified in the load's 'cmd' key. ''' log.trace('Clear pa...
Process a cleartext command :param dict load: Cleartext payload :return: The result of passing the load to a function in ClearFuncs corresponding to the command specified in the load's 'cmd' key.
def _set_vlan_add(self, v, load=False): """ Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_add is considered as a private method. Back...
Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_add is considered as a private method. Backends looking to populate this variable should do...
def delete(self, skip_mapping=False): """Delete all entries from ElasticSearch.""" for index in self.indexes: index.destroy() if not skip_mapping: index.create_mapping()
Delete all entries from ElasticSearch.
def getAllKws(self): """ extract all keywords into two categories kws_ele: magnetic elements kws_bl: beamline elements return (kws_ele, kws_bl) """ kws_ele = [] kws_bl = [] for ele in self.all_elements: if ele == '_prefixstr' or e...
extract all keywords into two categories kws_ele: magnetic elements kws_bl: beamline elements return (kws_ele, kws_bl)
def lists(self): """ :class:`Lists feed <pypump.models.feed.Lists>` with all lists owned by the person. Example: >>> for list in pump.me.lists: ... print(list) ... Acquaintances Family Coworkers Friends ...
:class:`Lists feed <pypump.models.feed.Lists>` with all lists owned by the person. Example: >>> for list in pump.me.lists: ... print(list) ... Acquaintances Family Coworkers Friends
def get_labels(obj): """ Retrieve the labels of a clustering.rst object :param obj: the clustering.rst object :return: the resulting labels """ if Clustering.is_pyclustering_instance(obj.model): return obj._labels_from_pyclusters else: ret...
Retrieve the labels of a clustering.rst object :param obj: the clustering.rst object :return: the resulting labels
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): """Returns audit entries stored in the database.""" quer...
Returns audit entries stored in the database.
def chunks(lst, size): """Yield successive n-sized chunks from lst.""" for i in xrange(0, len(lst), size): yield lst[i:i + size]
Yield successive n-sized chunks from lst.
def DisjoinCalendars(self, cutoff): """Forces the old and new calendars to be disjoint about a cutoff date. This truncates the service periods of the old schedule so that service stops one day before the given cutoff date and truncates the new schedule so that service only begins on the cutoff date. ...
Forces the old and new calendars to be disjoint about a cutoff date. This truncates the service periods of the old schedule so that service stops one day before the given cutoff date and truncates the new schedule so that service only begins on the cutoff date. Args: cutoff: The cutoff date as a...
def complete( text: str, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN ) -> Iterable[str]: """Return an iterable of possible completions for the given text.""" assert text.startswith(":") interns = kw_cache.deref() text = text[1:] if "/" in text: prefix, suffix = text.split("/", ...
Return an iterable of possible completions for the given text.
def xover_gen(self, range=None): """Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a t...
Generator for the XOVER command. The XOVER command returns information from the overview database for the article(s) specified. <http://tools.ietf.org/html/rfc2980#section-2.8> Args: range: An article number as an integer, or a tuple of specifying a range o...
def __merge_by_signle_link(self): """! @brief Merges the most similar clusters in line with single link type. """ minimum_single_distance = float('Inf'); indexes = None; for index_cluster1 in range(0, len(self.__clusters)): for index...
! @brief Merges the most similar clusters in line with single link type.
async def start_serving(self, connection_config: ConnectionConfig, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: """ Start serving this :class:`~lahja.endpoint.Endpoint` so that it can receive events. Await until the :class:`~l...
Start serving this :class:`~lahja.endpoint.Endpoint` so that it can receive events. Await until the :class:`~lahja.endpoint.Endpoint` is ready.
def _simple_chart(x=None, y=None, name=None, color=None, width=None, dash=None, opacity=None, mode='lines+markers', yaxis=1, fill=None, text='', style='line', markersize=6): """Draws connected dots. Parameters ---------- x : array-like, optional y : array-like, o...
Draws connected dots. Parameters ---------- x : array-like, optional y : array-like, optional label : array-like, optional Returns ------- Chart
def symlink_list(self, load): ''' Return a list of symlinked files and dirs ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {} if 'saltenv' not in load: return {} if not isinstance(load['sal...
Return a list of symlinked files and dirs
def _get_other_names(self, line): """Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file """ m = re.search(self.compound_regex['other_names'][0], line, re.IGNORECASE) if m: self.other_names.app...
Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file
def is_deaf(self): """ Глухая ли согласная. """ if not self.is_consonant(): return False if self.letter in self.forever_deaf: return True if self.letter in self.forever_sonorus: return False if self.__forsed_sonorus: ...
Глухая ли согласная.
def type(self): """Whether this is a method or function. :returns: 'method' if this is a method, 'function' otherwise. :rtype: str """ # pylint: disable=no-member if self.args.args and self.args.args[0].name == "self": if isinstance(self.parent.scope(), Class...
Whether this is a method or function. :returns: 'method' if this is a method, 'function' otherwise. :rtype: str
def compute_freq_cross(self, csd, asd, output='coherence'): """Compute cross-spectrum, gain, phase shift and/or coherence. Parameters ---------- csd : list of dict with 'data' key as instance of ChanFreq cross-spectral density, one channel asd : list of dict with 'da...
Compute cross-spectrum, gain, phase shift and/or coherence. Parameters ---------- csd : list of dict with 'data' key as instance of ChanFreq cross-spectral density, one channel asd : list of dict with 'data' key as instance of ChanFreq autospectral density, two c...
def _add_dict_values(self, d1, d2): """ Merges the values of two dictionaries, which are expected to be dictionaries, e.g d1 = {'a': {'x': pqr}} d2 = {'a': {'y': lmn}, 'b': {'y': rst}} will return: {'a': {'x': pqr, 'y': lmn}, 'b': {'y': rst}}. Collisions of the keys of th...
Merges the values of two dictionaries, which are expected to be dictionaries, e.g d1 = {'a': {'x': pqr}} d2 = {'a': {'y': lmn}, 'b': {'y': rst}} will return: {'a': {'x': pqr, 'y': lmn}, 'b': {'y': rst}}. Collisions of the keys of the sub-dictionaries are not checked.
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, typeahead=False, language=None, ): """ Return a location point by address. :param str query: The address or query you wish to...
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before rais...
def save(self, path, table_format='txt', sep='\t', table_ext=None, float_format='%.12g'): """ Saving the system to path Parameters ---------- path : pathlib.Path or string path for the saved data (will be created if necessary, data within will be ov...
Saving the system to path Parameters ---------- path : pathlib.Path or string path for the saved data (will be created if necessary, data within will be overwritten). table_format : string Format to save the DataFrames: - 'pkl' : Bi...
def setText(self, text): """ Sets the text for this connection to the inputed text. :param text | <str> """ self._text = text if text: if self._textItem is None: self._textItem = QGraphicsTextItem() self._textItem...
Sets the text for this connection to the inputed text. :param text | <str>
def _rt_parse_execs(self, statement, element, mode, lineparser): """As part of parse_line(), checks for new executable declarations in the statement.""" #This is the same deal as with _rt_parse_types() below. if mode == "insert": enew, start, end = self.xparser.parse_signature(statem...
As part of parse_line(), checks for new executable declarations in the statement.
async def write(self, data): """ This method writes sends data to the IP device :param data: :return: None """ self.writer.write((bytes([ord(data)]))) await self.writer.drain()
This method writes sends data to the IP device :param data: :return: None
def by_median_home_value(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.median_home_value.name, ascending=False, ...
Search zipcode information by median home value.
def reblog(self, blogname, **kwargs): """ Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param com...
Creates a reblog on the given blogname :param blogname: a string, the url of the blog you want to reblog to :param id: an int, the post id that you are reblogging :param reblog_key: a string, the reblog key of the post :param comment: a string, a comment added to the reblogged post ...
def sorted(list, cmp=None, reversed=False): """ Returns a sorted copy of the list. """ list = [x for x in list] list.sort(cmp) if reversed: list.reverse() return list
Returns a sorted copy of the list.
def get_opts(opts): """ Validate options and apply defaults for options not supplied. :param opts: dictionary mapping str->str. :return: dictionary mapping str->Opt. All possible keys are present. """ defaults = { 'board': None, 'terrain': Opt.random, 'numbers': Opt.pres...
Validate options and apply defaults for options not supplied. :param opts: dictionary mapping str->str. :return: dictionary mapping str->Opt. All possible keys are present.
def is_dir_or_file(dirname): '''Checks if a path is an actual directory that exists or a file''' if not os.path.isdir(dirname) and not os.path.isfile(dirname): msg = "{0} is not a directory nor a file".format(dirname) raise argparse.ArgumentTypeError(msg) else: return dirname
Checks if a path is an actual directory that exists or a file
def prompt(self, error=''): """ Prompts the user to set the value for this item. :return <bool> | success """ if self.hidden: return True cmd = [self.label] if self.default is not None: cmd.append('(default: {0})'.format(self...
Prompts the user to set the value for this item. :return <bool> | success
def generate(env): """Add Builders and construction variables for TeX to an Environment.""" global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCon...
Add Builders and construction variables for TeX to an Environment.