code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def convolve2d_disk(fn, r, sig, nstep=200): """Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is azimuthally symmetric function in two dimensions and g is a step function given by: g(r) = H(1-r/s) Parameters ---------- fn : function Input function that takes a single radial...
Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is azimuthally symmetric function in two dimensions and g is a step function given by: g(r) = H(1-r/s) Parameters ---------- fn : function Input function that takes a single radial coordinate parameter. r : `~numpy.ndarray` ...
def delete(self, route: str(), callback: object()): """ Binds a PUT route with the given callback :rtype: object """ self.__set_route('delete', {route: callback}) return RouteMapping
Binds a PUT route with the given callback :rtype: object
def request_connect(self, act, coro): "Requests a connect for `coro` corutine with parameters and completion \ passed via `act`" result = self.try_run_act(act, perform_connect) if result: return result, coro else: self.add_token(act, coro, perform_c...
Requests a connect for `coro` corutine with parameters and completion \ passed via `act`
def has_connection(self, i, j): """! @brief Returns True if there is connection between i and j oscillators and False - if connection doesn't exist. @param[in] i (uint): index of an oscillator in the network. @param[in] j (uint): index of an oscillator in the network. ...
! @brief Returns True if there is connection between i and j oscillators and False - if connection doesn't exist. @param[in] i (uint): index of an oscillator in the network. @param[in] j (uint): index of an oscillator in the network.
def _get_jamo_short_name(jamo): """ Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. http...
Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. https://www.unicode.org/versions/latest/ch03.pdf...
def p_elision(self, p): """elision : COMMA | elision COMMA """ if len(p) == 2: p[0] = [ast.Elision(p[1])] else: p[1].append(ast.Elision(p[2])) p[0] = p[1]
elision : COMMA | elision COMMA
def create(self, basedir, outdir, name, prefix=None): """ :API: public """ zippath = os.path.join(outdir, '{}.{}'.format(name, self.extension)) with open_zip(zippath, 'w', compression=self.compression) as zip: # For symlinks, we want to archive the actual content of linked files but # un...
:API: public
def _job_statistics(self): """Helper for job-type specific statistics-based properties.""" statistics = self._properties.get("statistics", {}) return statistics.get(self._JOB_TYPE, {})
Helper for job-type specific statistics-based properties.
def _add(self, codeobj): """Add a child (value) to this object.""" assert isinstance(codeobj, CodeExpression.TYPES) self.value = codeobj
Add a child (value) to this object.
def _get_exception_class_from_status_code(status_code): """ Utility function that accepts a status code, and spits out a reference to the correct exception class to raise. :param str status_code: The status code to return an exception class for. :rtype: PetfinderAPIError or None :returns: The a...
Utility function that accepts a status code, and spits out a reference to the correct exception class to raise. :param str status_code: The status code to return an exception class for. :rtype: PetfinderAPIError or None :returns: The appropriate PetfinderAPIError subclass. If the status code is...
def get_all_adv_settings() -> Dict[str, Dict[str, Union[str, bool, None]]]: """ :return: a dict of settings keyed by setting ID, where each value is a dict with keys "id", "title", "description", and "value" """ settings_file = CONFIG['feature_flags_file'] values, _ = _read_settings_file(se...
:return: a dict of settings keyed by setting ID, where each value is a dict with keys "id", "title", "description", and "value"
def as_dict(self): """ Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object. :return: Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object. """ return {"@module": self.__class__.__module__, "@class": self.__c...
Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object. :return: Bson-serializable dict representation of the WeightedNbSetChemenvStrategy object.
def get_bac(age, weight, height, sex, volume, percent): """Returns the *Blood Alcohol Content* (raise) for a person (described by the given attributes) after a drink containing *volume* ml of alcohol with the given *percent* (vol/vol). """ return gramm_to_promille( calculate_alcohol(volume, percent)...
Returns the *Blood Alcohol Content* (raise) for a person (described by the given attributes) after a drink containing *volume* ml of alcohol with the given *percent* (vol/vol).
def get_full_angles(self): """Get the interpolated lons/lats. """ if (self.sun_azi is not None and self.sun_zen is not None and self.sat_azi is not None and self.sat_zen is not None): return self.sun_azi, self.sun_zen, self.sat_azi, self.sat_zen self.sun_azi,...
Get the interpolated lons/lats.
def save_thumbnail(self, thumbnail): """ Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups. """ filename = thumbnail.name try: self.thumbnail_sto...
Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups.
def set_portfast(self, name, value=None, default=False, disable=False): """Configures the portfast value for the specified interface Args: name (string): The interface identifier to configure. The name must be the full interface name (eg Ethernet1, not Et1) val...
Configures the portfast value for the specified interface Args: name (string): The interface identifier to configure. The name must be the full interface name (eg Ethernet1, not Et1) value (bool): True if portfast is enabled otherwise False default (bool):...
def _make_weirdness_regex(): """ Creates a list of regexes that match 'weird' character sequences. The more matches there are, the weirder the text is. """ groups = [] # Match diacritical marks, except when they modify a non-cased letter or # another mark. # # You wouldn't put a dia...
Creates a list of regexes that match 'weird' character sequences. The more matches there are, the weirder the text is.
def _notebook_model_from_db(self, record, content): """ Build a notebook model from database record. """ path = to_api_path(record['parent_name'] + record['name']) model = base_model(path) model['type'] = 'notebook' model['last_modified'] = model['created'] = reco...
Build a notebook model from database record.
def list_parameters(self, parameter_type=None, page_size=None): """Lists the parameters visible to this client. Parameters are returned in lexicographical order. :param str parameter_type: The type of parameter :rtype: :class:`.Parameter` iterator """ params = {'details...
Lists the parameters visible to this client. Parameters are returned in lexicographical order. :param str parameter_type: The type of parameter :rtype: :class:`.Parameter` iterator
def _platform_patterns(self, platform='generic', compiled=False): """Return all the patterns for specific platform.""" patterns = self._dict_compiled.get(platform, None) if compiled else self._dict_text.get(platform, None) if patterns is None: raise KeyError("Unknown platform: {}".fo...
Return all the patterns for specific platform.
def delete_maintenance_window(self, id, **kwargs): # noqa: E501 """Delete a specific maintenance window # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete...
Delete a specific maintenance window # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_maintenance_window(id, async_req=True) >>> result = thread.get() ...
def _tryConnect(src, unit, intfName): """ Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver. """ try: dst = getattr(unit, intfName) except AttributeError: return if not dst._sig.drivers: connect(src,...
Try connect src to interface of specified name on unit. Ignore if interface is not present or if it already has driver.
def _find_known(row): """Find variant present in known pathogenic databases. """ out = [] clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic", "uncertain_significance", "uncertain_significance", "not_provided", "benign", "likel...
Find variant present in known pathogenic databases.
def _add_zone(self, zone, name='', status=Zone.CLEAR, expander=False): """ Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: in...
Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int
def bin_remove(self): """Remove Slackware packages """ packages = self.args[1:] options = [ "-r", "--removepkg" ] additional_options = [ "--deps", "--check-deps", "--tag", "--checklist" ] ...
Remove Slackware packages
def roles_remove(user, role): """Remove user from role.""" user, role = _datastore._prepare_role_modify_args(user, role) if user is None: raise click.UsageError('Cannot find user.') if role is None: raise click.UsageError('Cannot find role.') if _datastore.remove_role_from_user(user,...
Remove user from role.
def url_defaults(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add a url default preprocessor. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.url_defaults def default(endpoint, values): .....
Add a url default preprocessor. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.url_defaults def default(endpoint, values): ...
def get_mac_acl_for_intf_input_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf") config = get_mac_acl_for_intf input = ET.SubElement(get_mac_acl_for_intf, "input") int...
Auto Generated Code
def _prepare_nameparser_constants(): """Prepare nameparser Constants. Remove nameparser's titles and use our own and add as suffixes the roman numerals. Configuration is the same for all names (i.e. instances). """ constants = Constants() roman_numeral_suffixes = [u'v', u'vi', u'vii', u'viii', ...
Prepare nameparser Constants. Remove nameparser's titles and use our own and add as suffixes the roman numerals. Configuration is the same for all names (i.e. instances).
def run_sequential(self): """Perform the computation sequentially, only holding two computed objects in memory at a time. """ try: result = self.empty_result(*self.context) for obj in self.iterable: r = self.compute(obj, *self.context) ...
Perform the computation sequentially, only holding two computed objects in memory at a time.
def merge_plugin_from_baseline(baseline_plugins, args): """ :type baseline_plugins: tuple of BasePlugin :param baseline_plugins: BasePlugin instances from baseline file :type args: dict :param args: diction of arguments parsed from usage param priority: input param > baseline param > default ...
:type baseline_plugins: tuple of BasePlugin :param baseline_plugins: BasePlugin instances from baseline file :type args: dict :param args: diction of arguments parsed from usage param priority: input param > baseline param > default :Returns tuple of initialized plugins
def _get_consecutive_portions_of_front(front): """ Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form), such that each list yielded is consecutive in frequency. """ last_f = None ls = [] for f, s in front: if last_f is not ...
Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form), such that each list yielded is consecutive in frequency.
def batch_per(hyps: Sequence[Sequence[T]], refs: Sequence[Sequence[T]]) -> float: """ Calculates the phoneme error rate of a batch.""" macro_per = 0.0 for i in range(len(hyps)): ref = [phn_i for phn_i in refs[i] if phn_i != 0] hyp = [phn_i for phn_i in hyps[i] if phn_i != 0] ...
Calculates the phoneme error rate of a batch.
def list_migration_issues_accounts(self, account_id, content_migration_id): """ List migration issues. Returns paginated migration issues """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["accoun...
List migration issues. Returns paginated migration issues
def read(self, size=None): """Read bytes from an iterator.""" while size is None or len(self.buffer) < size: try: self.buffer += next(self.data_stream) except StopIteration: break sized_chunk = self.buffer[:size] if size is None: ...
Read bytes from an iterator.
def number(type=None, length=None, prefixes=None): """ Return a random credit card number. :param type: credit card type. Defaults to a random selection. :param length: length of the credit card number. Defaults to the length for the selected card type. :param prefixes: allowed p...
Return a random credit card number. :param type: credit card type. Defaults to a random selection. :param length: length of the credit card number. Defaults to the length for the selected card type. :param prefixes: allowed prefixes for the card number. Defaults to p...
def record_exists(self, table, keys): """ Checks if a record exists in Cassandra :param table: Target Cassandra table. Use dot notation to target a specific keyspace. :type table: str :param keys: The keys and their values to check the existence. :t...
Checks if a record exists in Cassandra :param table: Target Cassandra table. Use dot notation to target a specific keyspace. :type table: str :param keys: The keys and their values to check the existence. :type keys: dict
def iget(self, irods_path, attempts=1, pause=15): """Add an iget command to retrieve a file from iRODS. Parameters ---------- irods_path: str Filepath which should be fetched using iget attempts: int (default: 1) Number of retries, if iROD...
Add an iget command to retrieve a file from iRODS. Parameters ---------- irods_path: str Filepath which should be fetched using iget attempts: int (default: 1) Number of retries, if iRODS access fails pause: int (default: 15) ...
def openRtpPort(self): """Open RTP socket binded to a specified port.""" #------------- # TO COMPLETE #------------- # Create a new datagram socket to receive RTP packets from the server # self.rtpSocket = ... # Set the timeout value of the socket to 0.5sec # ... self.rtpSocket.set...
Open RTP socket binded to a specified port.
def ClearAllVar(self): """Clear this Value.""" self.value = None # Call OnClearAllVar on options. _ = [option.OnClearAllVar() for option in self.options]
Clear this Value.
def fetchall(self): """Fetch all rows.""" result = self.query.result() return [row.values() for row in result]
Fetch all rows.
def GaussianCdfInverse(p, mu=0, sigma=1): """Evaluates the inverse CDF of the gaussian distribution. See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function Args: p: float mu: mean parameter sigma: standard deviation parameter Returns...
Evaluates the inverse CDF of the gaussian distribution. See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function Args: p: float mu: mean parameter sigma: standard deviation parameter Returns: float
def get_index_translog_disable_flush(self): """Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": ...
Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": False, # Autoflushing ENABLED "inde...
def kakwani(values, ineq_axis, weights = None): """ Computes the Kakwani index """ from scipy.integrate import simps if weights is None: weights = ones(len(values)) # sign = -1 # if tax == True: # sign = -1 # else: # sign = 1 PLCx, PLCy = pseudo_lorenz(values, i...
Computes the Kakwani index
def dequeue(self, destination): """ Removes and returns an item from the queue (or C{None} if no items in queue). @param destination: The queue name (destinationination). @type destination: C{str} @return: The first frame in the specified queue, or C{None} if there are none. ...
Removes and returns an item from the queue (or C{None} if no items in queue). @param destination: The queue name (destinationination). @type destination: C{str} @return: The first frame in the specified queue, or C{None} if there are none. @rtype: C{stompclient.frame.Frame}
def determine_extra_packages(self, packages): """ Return all packages that are installed, but missing from "packages". Return value is a tuple of the package names """ args = [ "pip", "freeze", ] installed = subprocess.check_output(args, universal_new...
Return all packages that are installed, but missing from "packages". Return value is a tuple of the package names
def watch(static_root, watch_paths=None, on_reload=None, host='localhost', port=5555, server_base_path="/", watcher_interval=1.0, recursive=True, open_browser=True, open_browser_delay=1.0): """Initialises an HttpWatcherServer to watch the given path for changes. Watches until the IO loop is terminated...
Initialises an HttpWatcherServer to watch the given path for changes. Watches until the IO loop is terminated, or a keyboard interrupt is intercepted. Args: static_root: The path whose contents are to be served and watched. watch_paths: The paths to be watched for changes. If not supplied, this...
def later(timeout, f, *args, **kwargs): ''' Sets a timer that will call the *f* function past *timeout* seconds. See example in :ref:`sample_inter` :return: :class:`Greenlet` new 'thread' which will perform the call when specified. ''' def wrap(*args, **kwargs): sleep(timeout) ...
Sets a timer that will call the *f* function past *timeout* seconds. See example in :ref:`sample_inter` :return: :class:`Greenlet` new 'thread' which will perform the call when specified.
def _flow_check_handler_internal(self): """Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity to delete stale fl...
Periodic handler to check if installed flows are present. This handler runs periodically to check if installed flows are present. This function cannot detect and delete the stale flows, if present. It requires more complexity to delete stale flows. Generally, stale flows are not present...
def render(self, template, **data): """Render data with template, return html unicodes. parameters template str the template's filename data dict the data to render """ # make a copy and update the copy dct = self.global_data.copy() dct.update...
Render data with template, return html unicodes. parameters template str the template's filename data dict the data to render
def delete_audio_mp3_profile(apps, schema_editor): """ Delete audio_mp3 profile """ Profile = apps.get_model('edxval', 'Profile') Profile.objects.filter(profile_name=AUDIO_MP3_PROFILE).delete()
Delete audio_mp3 profile
def delete(self, moveFixIssuesTo=None, moveAffectedIssuesTo=None): """Delete this project version from the server. If neither of the arguments are specified, the version is removed from all issues it is attached to. :param moveFixIssuesTo: in issues for which this version is a fix ...
Delete this project version from the server. If neither of the arguments are specified, the version is removed from all issues it is attached to. :param moveFixIssuesTo: in issues for which this version is a fix version, add this argument version to the fix version list ...
def _init_properties(self): """ Init Properties """ super(BaseCRUDView, self)._init_properties() # Reset init props self.related_views = self.related_views or [] self._related_views = self._related_views or [] self.description_columns = self.descriptio...
Init Properties
def crystal(positions, molecules, group, cellpar=[1.0, 1.0, 1.0, 90, 90, 90], repetitions=[1, 1, 1]): '''Build a crystal from atomic positions, space group and cell parameters. **Parameters** positions: list of coordinates A list of the atomic positions molecules: list of ...
Build a crystal from atomic positions, space group and cell parameters. **Parameters** positions: list of coordinates A list of the atomic positions molecules: list of Molecule The molecules corresponding to the positions, the molecule will be translated in all the equival...
def _Open(self, path_spec, mode='rb'): """Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification of the file system. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: Access...
Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification of the file system. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was deni...
def analyze_xml(xml): """Analyzes `file` against packtools' XMLValidator. """ f = StringIO(xml) try: xml = packtools.XMLValidator.parse(f, sps_version='sps-1.4') except packtools.exceptions.PacktoolsError as e: logger.exception(e) summary = {} summary['dtd_is_valid'...
Analyzes `file` against packtools' XMLValidator.
def revoke(self, only_access=False): """Revoke the current Authorization. :param only_access: (Optional) When explicitly set to True, do not evict the refresh token if one is set. Revoking a refresh token will in-turn revoke all access tokens associated with that authorizat...
Revoke the current Authorization. :param only_access: (Optional) When explicitly set to True, do not evict the refresh token if one is set. Revoking a refresh token will in-turn revoke all access tokens associated with that authorization.
def parse_quadrant_measurement(quad_azimuth): """ Parses a quadrant measurement of the form "AxxB", where A and B are cardinal directions and xx is an angle measured relative to those directions. In other words, it converts a measurement such as E30N into an azimuth of 60 degrees, or W10S into an a...
Parses a quadrant measurement of the form "AxxB", where A and B are cardinal directions and xx is an angle measured relative to those directions. In other words, it converts a measurement such as E30N into an azimuth of 60 degrees, or W10S into an azimuth of 260 degrees. For ambiguous quadrant measure...
def _run_tRNA_scan(fasta_file): """ Run tRNA-scan-SE to predict tRNA """ out_file = fasta_file + "_trnascan" se_file = fasta_file + "_second_str" cmd = "tRNAscan-SE -q -o {out_file} -f {se_file} {fasta_file}" run(cmd.format(**locals())) return out_file, se_file
Run tRNA-scan-SE to predict tRNA
def register( model, app=None, manager_name="history", records_class=None, table_name=None, **records_config ): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historical model into (defaults to model.__modu...
Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historical model into (defaults to model.__module__) manager_name -- class attribute name to use for historical manager records_class -- class to use for history relation (defaults to ...
def _getZoomLevelRange(self, resolution, unit='meters'): "Return lower and higher zoom level given a resolution" assert unit in ('meters', 'degrees') if unit == 'meters' and self.unit == 'degrees': resolution = resolution / self.metersPerUnit elif unit == 'degrees' and self.u...
Return lower and higher zoom level given a resolution
def ReadUserDefinedFunction(self, udf_link, options=None): """Reads a user defined function. :param str udf_link: The link to the user defined function. :param dict options: The request options for the request. :return: The read UDF. :rtype: ...
Reads a user defined function. :param str udf_link: The link to the user defined function. :param dict options: The request options for the request. :return: The read UDF. :rtype: dict
async def rt_connect(self, loop): """Start subscription manager for real time data.""" if self.sub_manager is not None: return self.sub_manager = SubscriptionManager( loop, "token={}".format(self._access_token), SUB_ENDPOINT ) self.sub_manager.start()
Start subscription manager for real time data.
def iteration(self, node_status=True): """ Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status) """ self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in futur...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
def on_connection_close(self) -> None: """Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you ...
Called in async handlers if the client closed the connection. Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request over...
def split_input(cls, mapper_spec, _reader=blobstore.BlobReader): """Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_keys' parameter with one or more blob keys. _reader: a callable that returns a file-like objec...
Returns a list of input readers for the input spec. Args: mapper_spec: The MapperSpec for this InputReader. Must contain 'blob_keys' parameter with one or more blob keys. _reader: a callable that returns a file-like object for reading blobs. Used for dependency injection. Retur...
def closeEvent(self, event): """Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing """ # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or ...
Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing
def _setLocation(self, path): '''Set current location to *path*. *path* must be the same as root or under the root. .. note:: Comparisons are case-sensitive. If you set the root as 'D:/' then location can be set as 'D:/folder' *not* 'd:/folder'. ''' mo...
Set current location to *path*. *path* must be the same as root or under the root. .. note:: Comparisons are case-sensitive. If you set the root as 'D:/' then location can be set as 'D:/folder' *not* 'd:/folder'.
def do_it(self, dbg): '''Starts a thread that will load values asynchronously''' try: var_objects = [] for variable in self.vars: variable = variable.strip() if len(variable) > 0: if '\t' in variable: # there are attributes bey...
Starts a thread that will load values asynchronously
def parse_uint(self, buff, start, end): ''' parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end: ''' return struct.unpack_from(self.ustructmap[end - start], buff, start)[0]
parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end:
def average_dtu_configurations(list_of_objects): """Return DtuConfiguration instance with averaged values. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with a...
Return DtuConfiguration instance with averaged values. Parameters ---------- list_of_objects : python list List of DtuConfiguration instances to be averaged. Returns ------- result : DtuConfiguration instance Object with averaged values.
def getCachedOrUpdatedValue(self, key, channel=None): """ Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned. """ if channel: return ...
Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned.
def get_iso_packet_buffer_list(transfer_p): """ Python-specific helper extracting a list of iso packet buffers. """ transfer = transfer_p.contents offset = 0 result = [] append = result.append for iso_transfer in _get_iso_packet_list(transfer): length = iso_transfer.length ...
Python-specific helper extracting a list of iso packet buffers.
def fit(self, X=None, u=None): """Fit X into an embedded space. Inputs ---------- X : array, shape (n_samples, n_features) u,s,v : svd decomposition of X (optional) Assigns ---------- embedding : array-like, shape (n_samples, n_components) Sto...
Fit X into an embedded space. Inputs ---------- X : array, shape (n_samples, n_features) u,s,v : svd decomposition of X (optional) Assigns ---------- embedding : array-like, shape (n_samples, n_components) Stores the embedding vectors. u,sv,v ...
def cells_from_defaults(clz, jsonobj): """ Creates a referent instance of type `json.kind` and initializes it to default values. """ # convert strings to dicts if isinstance(jsonobj, (str, unicode)): jsonobj = json.loads(jsonobj) assert 'cells' in js...
Creates a referent instance of type `json.kind` and initializes it to default values.
def histogram(values, num_bins, bounds, normalized=True, plot=False, color='b'): """Generate a histogram plot. Parameters ---------- values : :obj:`numpy.ndarray` An array of values to put in the histogram. num_bins : int The number equal-width bins in the histogram. bounds : ...
Generate a histogram plot. Parameters ---------- values : :obj:`numpy.ndarray` An array of values to put in the histogram. num_bins : int The number equal-width bins in the histogram. bounds : :obj:`tuple` of float Two floats - a min and a max - that define the lower and u...
def encode_aes256(key, plaintext): """ Utility method to encode some given plaintext with the given key. Important thing to note: This is not a general purpose encryption method - it has specific semantics (see below for details). Takes the given hex string key and converts it to a 256 bit binary ...
Utility method to encode some given plaintext with the given key. Important thing to note: This is not a general purpose encryption method - it has specific semantics (see below for details). Takes the given hex string key and converts it to a 256 bit binary blob. Then pads the given plaintext to AES ...
def build_package_from_pr_number(gh_token, sdk_id, pr_number, output_folder, *, with_comment=False): """Will clone the given PR branch and vuild the package with the given name.""" con = Github(gh_token) repo = con.get_repo(sdk_id) sdk_pr = repo.get_pull(pr_number) # "get_files" of Github only down...
Will clone the given PR branch and vuild the package with the given name.
def get_bgcolor(self, index): """Background color depending on value""" value = self.get_value(index) if index.column() < 3: color = ReadOnlyCollectionsModel.get_bgcolor(self, index) else: if self.remote: color_name = value['color'] ...
Background color depending on value
def configure_roles_on_host(api, host): """ Go through all the roles on this host, and configure them if they match the role types that we care about. """ for role_ref in host.roleRefs: # Mgmt service/role has no cluster name. Skip over those. if role_ref.get('clusterName') is None: continue ...
Go through all the roles on this host, and configure them if they match the role types that we care about.
def get_data(__pkg: str, __name: str) -> str: """Return top-most data file for given package. Args: __pkg: Package name __name: Data file name """ for dname in get_data_dirs(__pkg): test_path = path.join(dname, __name) if path.exists(test_path): return test_p...
Return top-most data file for given package. Args: __pkg: Package name __name: Data file name
def _wrap_OCLArray(cls): """ WRAPPER """ def prepare(arr): return np.require(arr, None, "C") @classmethod def from_array(cls, arr, *args, **kwargs): queue = get_device().queue return cl_array.to_device(queue, prepare(arr), *args, **kwargs) @classmethod def empt...
WRAPPER
def rollback(self): """ Rollback of this current transaction. """ self._check_thread() if self.state not in (_STATE_ACTIVE, _STATE_PARTIAL_COMMIT): raise TransactionError("Transaction is not active.") try: if self.state != _STATE_PARTIAL_COMMIT: ...
Rollback of this current transaction.
def parse_domains(self, domain, params): """ Parse a single Route53Domains domain """ domain_id = self.get_non_aws_id(domain['DomainName']) domain['name'] = domain.pop('DomainName') #TODO: Get Dnssec info when available #api_client = params['api_client'] #...
Parse a single Route53Domains domain
def make_default_docstr(func, with_args=True, with_ret=True, with_commandline=True, with_example=True, with_header=False, with_debug=False): r""" Tries to make a sensible default docstr so the user can fill things in without typing too much # TODO: Interl...
r""" Tries to make a sensible default docstr so the user can fill things in without typing too much # TODO: Interleave old documentation with new documentation Args: func (function): live python function with_args (bool): with_ret (bool): (Defaults to True) with_command...
def add_at_risk_counts(*fitters, **kwargs): """ Add counts showing how many individuals were at risk at each time point in survival/hazard plots. Parameters ---------- fitters: One or several fitters, for example KaplanMeierFitter, NelsonAalenFitter, etc... Returns -------...
Add counts showing how many individuals were at risk at each time point in survival/hazard plots. Parameters ---------- fitters: One or several fitters, for example KaplanMeierFitter, NelsonAalenFitter, etc... Returns -------- ax: The axes which was used. Examples -...
def popen(self, stdout, stderr): """Build popen object to run :rtype: subprocess.Popen """ self.logger.info('Executing command: %s', self.command_str) return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)
Build popen object to run :rtype: subprocess.Popen
def perform(cls, entity_cls, usecase_cls, request_object_cls, payload: dict, raise_error=False): """ This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_...
This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_cls: The usecase class that will be executed by the tasklet. :param request_object_cls: The request object to be used...
def airspeed_ratio(VFR_HUD): '''recompute airspeed with a different ARSPD_RATIO''' import mavutil mav = mavutil.mavfile_global airspeed_pressure = (VFR_HUD.airspeed**2) / ratio airspeed = sqrt(airspeed_pressure * ratio) return airspeed
recompute airspeed with a different ARSPD_RATIO
def get_last_doc(self): """Get the most recently modified document from Elasticsearch. This method is used to help define a time window within which documents may be in conflict after a MongoDB rollback. """ try: result = self.elastic.search( index=se...
Get the most recently modified document from Elasticsearch. This method is used to help define a time window within which documents may be in conflict after a MongoDB rollback.
def recurse(self, factory_meta, extras): """Recurse into a sub-factory call.""" return self.__class__(factory_meta, extras, strategy=self.strategy)
Recurse into a sub-factory call.
def on_menu_criteria_file(self, event): """ read pmag_criteria.txt file and open changecriteria dialog """ if self.data_model == 3: default_file = "criteria.txt" else: default_file = "pmag_criteria.txt" read_sucsess = False dlg = wx...
read pmag_criteria.txt file and open changecriteria dialog
def has_return_exprs(self, node): """Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.) """ results = {} if self.return_expr.match(node, result...
Traverse the tree below node looking for 'return expr'. Return True if at least 'return expr' is found, False if not. (If both 'return' and 'return expr' are found, return True.)
def check_dependency(self, operation, dependency): """ Enhances default behavior of method by checking dependency for matching operation. """ if isinstance(dependency[1], SQLBlob): # NOTE: we follow the sort order created by `assemble_changes` so we build a fixed chain ...
Enhances default behavior of method by checking dependency for matching operation.
def load(self): """ Load publish info from remote """ publish = self._get_publish() self.architectures = publish['Architectures'] for source in publish['Sources']: component = source['Component'] snapshot = source['Name'] self.publish_s...
Load publish info from remote
def single_gene_deletion(model, gene_list=None, method="fba", solution=None, processes=None, **kwargs): """ Knock out each gene from a given list. Parameters ---------- model : cobra.Model The metabolic model to perform deletions in. gene_list : iterable ...
Knock out each gene from a given list. Parameters ---------- model : cobra.Model The metabolic model to perform deletions in. gene_list : iterable ``cobra.Gene``s to be deleted. If not passed, all the genes from the model are used. method: {"fba", "moma", "linear moma", "roo...
def parse(content): """ Parse the content of a .env file (a line-delimited KEY=value format) into a dictionary mapping keys to values. """ values = {} for line in content.splitlines(): lexer = shlex.shlex(line, posix=True) tokens = list(lexer) # parses the assignment sta...
Parse the content of a .env file (a line-delimited KEY=value format) into a dictionary mapping keys to values.
def ensure_unicoded_and_unique(args_list, application): """ Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order. """ unicoded_args = [] for argument in args_list: argument = (six.u(argument) ...
Iterate over args_list, make it unicode if needed and ensure that there are no duplicates. Returns list of unicoded arguments in the same order.
def add_category(self, category): """Add a category assigned to this message :rtype: Category """ self._categories = self._ensure_append(category, self._categories)
Add a category assigned to this message :rtype: Category
def extract_request_details(request_object, session_object=None): ''' a method for extracting request details from request and session objects NOTE: method is also a placeholder funnel for future validation processes, request logging, request context building and ...
a method for extracting request details from request and session objects NOTE: method is also a placeholder funnel for future validation processes, request logging, request context building and counter-measures for the nasty web :param request_object: request object...