positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def handle_import_tags(userdata, import_root): """Handle @import(filepath)@ tags in a UserData script. :param import_root: Location for imports. :type import_root: str :param userdata: UserData script content. :type userdata: str :return: UserData script with the content...
Handle @import(filepath)@ tags in a UserData script. :param import_root: Location for imports. :type import_root: str :param userdata: UserData script content. :type userdata: str :return: UserData script with the contents of the imported files. :rtype: str
def physicaliam(aoi, n=1.526, K=4., L=0.002): ''' Determine the incidence angle modifier using refractive index, extinction coefficient, and glazing thickness. physicaliam calculates the incidence angle modifier as described in De Soto et al. "Improvement and validation of a model for photovolt...
Determine the incidence angle modifier using refractive index, extinction coefficient, and glazing thickness. physicaliam calculates the incidence angle modifier as described in De Soto et al. "Improvement and validation of a model for photovoltaic array performance", section 3. The calculation is base...
def getStat(cls, obj, name): """Gets the stat for the given object with the given name, or None if no such stat exists.""" objClass = type(obj) for theClass in objClass.__mro__: if theClass == object: break for value in theClass.__dict__.values(): if isinstance(value, Stat) and v...
Gets the stat for the given object with the given name, or None if no such stat exists.
def _requestDetails(self, ip_address=None): """Get IP address data by sending request to IPinfo API.""" if ip_address not in self.cache: url = self.API_URL if ip_address: url += '/' + ip_address response = requests.get(url, headers=self._get_headers()...
Get IP address data by sending request to IPinfo API.
def parse_error(res): """ Every server error should contain a "status" field with a human readable explanation of what went wrong as well as a "error_type" field indicating the kind of error that can be mapped to a Python type. There's a fallback error UnknownError for other types of exceptions (ne...
Every server error should contain a "status" field with a human readable explanation of what went wrong as well as a "error_type" field indicating the kind of error that can be mapped to a Python type. There's a fallback error UnknownError for other types of exceptions (network issues, api gateway prob...
def binomial_coefficient(k, i): """ Computes the binomial coefficient (denoted by *k choose i*). Please see the following website for details: http://mathworld.wolfram.com/BinomialCoefficient.html :param k: size of the set of distinct elements :type k: int :param i: size of the subsets :type i...
Computes the binomial coefficient (denoted by *k choose i*). Please see the following website for details: http://mathworld.wolfram.com/BinomialCoefficient.html :param k: size of the set of distinct elements :type k: int :param i: size of the subsets :type i: int :return: combination of *k* an...
def from_rfc3339(rfc3339_text, with_nanos=False): """Parse a RFC 3339 date string format to datetime.date. Example of accepted format: '1972-01-01T10:00:20.021-05:00' - By default, the result is a datetime.datetime - If with_nanos is true, the result is a 2-tuple, (datetime.datetime, nanos), where...
Parse a RFC 3339 date string format to datetime.date. Example of accepted format: '1972-01-01T10:00:20.021-05:00' - By default, the result is a datetime.datetime - If with_nanos is true, the result is a 2-tuple, (datetime.datetime, nanos), where the second field represents the possible nanosecond ...
def ReadPreprocessingInformation(self, knowledge_base): """Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (Knowle...
Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (KnowledgeBase): is used to store the preprocessing informat...
def get_parchg(self, poscar, kpoint, band, spin=None, phase=False, scale=2): """ Generates a Chgcar object, which is the charge density of the specified wavefunction. This function generates a Chgcar object with the charge density of the wavefunction specified...
Generates a Chgcar object, which is the charge density of the specified wavefunction. This function generates a Chgcar object with the charge density of the wavefunction specified by band and kpoint (and spin, if the WAVECAR corresponds to a spin-polarized calculation). The phase tag is...
def ready(self): """ Function used when agent is `lazy`. It is being processed only when `ready` condition is satisfied """ logger = self.get_logger() now = current_ts() logger.trace("Current time: {0}".format(now)) logger.trace("Last Run: {0}".format(self...
Function used when agent is `lazy`. It is being processed only when `ready` condition is satisfied
def setStateCodes(self): """ Generates (sorted) codes for the states in the statespace This is used to quickly identify which states occur after a transition/action """ #calculate the statespace and determine the minima and maxima each element in the state ve...
Generates (sorted) codes for the states in the statespace This is used to quickly identify which states occur after a transition/action
def storage_resolveBasedOnKey(self, *args, **kwargs): """ Call the remote service and ask for the storage location based on the key. :param args: :param kwargs: :return: """ global Gd_internalvar d_msg = { 'action': 'internalctl', ...
Call the remote service and ask for the storage location based on the key. :param args: :param kwargs: :return:
def main(): """ Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will....
Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will. These events can also b...
def collect(self): """ Collect libvirt data """ if libvirt is None: self.log.error('Unable to import either libvirt') return {} # Open a restricted (non-root) connection to the hypervisor conn = libvirt.openReadOnly(None) # Get hardware inf...
Collect libvirt data
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
Return a percentile range from an array of values.
def predict(self, X): """Predict targets for a feature matrix. Args: X (np.array of float): feature matrix for prediction Returns: prediction (np.array) """ logger.info('predicting ...') ps = self.predict_raw(X) return sigm(ps[:, 0])
Predict targets for a feature matrix. Args: X (np.array of float): feature matrix for prediction Returns: prediction (np.array)
def clear(self) -> None: """ Treat as if the *underlying* database will also be cleared by some other mechanism. We build a special empty changeset just for marking that all previous data should be ignored. """ # these internal records are used as a way to tell the differ...
Treat as if the *underlying* database will also be cleared by some other mechanism. We build a special empty changeset just for marking that all previous data should be ignored.
def get_watchers(self, username, offset=0, limit=10): """Get the user's list of watchers :param username: The username you want to get a list of watchers of :param offset: the pagination offset :param limit: the pagination limit """ response = self._req('/user/watchers...
Get the user's list of watchers :param username: The username you want to get a list of watchers of :param offset: the pagination offset :param limit: the pagination limit
def fetch_dictionary(name, url=None, format=None, index=0, rename=None, save=True, force_retrieve=False): ''' Retrieve a dictionary of text norms from the web or local storage. Args: name (str): The name of the dictionary. If no url is passed, this must match either one...
Retrieve a dictionary of text norms from the web or local storage. Args: name (str): The name of the dictionary. If no url is passed, this must match either one of the keys in the predefined dictionary file (see dictionaries.json), or the name assigned to a previous dictionary ...
def identify_delim(txt): """ identifies delimiters and returns a count by ROW in the text file as well as the delimiter value (if any) The delim is determined if the count of delims is consistant in all rows. """ possible_delims = _get_dict_char_count(txt) # {'C': 3, 'a': 4, 'b': 5, 'c': 6, ',': 6, 'A': ...
identifies delimiters and returns a count by ROW in the text file as well as the delimiter value (if any) The delim is determined if the count of delims is consistant in all rows.
def pid_tuning_encode(self, axis, desired, achieved, FF, P, I, D): ''' PID tuning information axis : axis (uint8_t) desired : desired rate (degrees/s) (float) achieved : achieved rate...
PID tuning information axis : axis (uint8_t) desired : desired rate (degrees/s) (float) achieved : achieved rate (degrees/s) (float) FF : FF component (float) P...
def obfuscate(self): """Disguise ciphertext by multiplying by r ** n with random r. This operation must be performed for every `EncryptedNumber` that is sent to an untrusted party, otherwise eavesdroppers might deduce relationships between this and an antecedent `EncryptedNumber...
Disguise ciphertext by multiplying by r ** n with random r. This operation must be performed for every `EncryptedNumber` that is sent to an untrusted party, otherwise eavesdroppers might deduce relationships between this and an antecedent `EncryptedNumber`. For example:: ...
def _fetch_option(cfg, ret_config, virtualname, attr_name): """ Fetch a given option value from the config. @see :func:`get_returner_options` """ # c_cfg is a dictionary returned from config.option for # any options configured for this returner. if isinstance(cfg, dict): c_cfg = cfg...
Fetch a given option value from the config. @see :func:`get_returner_options`
def __check_host_args(self, host, keys): """Checks parameters""" if host not in self.hosts_: raise ValueError("Host %s: not found" % host) if "host" in [x.lower() for x in keys]: raise ValueError("Cannot modify Host value")
Checks parameters
def install_visa_handler(self, session, event_type, handler, user_handle=None): """Installs handlers for event callbacks. :param session: Unique logical identifier to a session. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to...
Installs handlers for event callbacks. :param session: Unique logical identifier to a session. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be installed by a client application. :param user_handle: A value specified by an ...
def populate(self, obj=None, section=None, parse_types=True): """Set attributes in ``obj`` with ``setattr`` from the all values in ``section``. """ section = self.default_section if section is None else section obj = Settings() if obj is None else obj is_dict = isinstanc...
Set attributes in ``obj`` with ``setattr`` from the all values in ``section``.
def ExportModelOperationsMixin(model_name): """Returns a mixin for models to export counters for lifecycle operations. Usage: class User(ExportModelOperationsMixin('user'), Model): ... """ # Force create the labels for this model in the counters. This # is not necessary but it avoid...
Returns a mixin for models to export counters for lifecycle operations. Usage: class User(ExportModelOperationsMixin('user'), Model): ...
def archs(self, as_list=False): """Return all of the architectures for this target. Args: as_list (bool): Return a list instead of the default set object. Returns: set or list: All of the architectures used in this TargetSettings object. """ archs = sel...
Return all of the architectures for this target. Args: as_list (bool): Return a list instead of the default set object. Returns: set or list: All of the architectures used in this TargetSettings object.
def _pastorestr(ins): ''' Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW inmediate strings for the 2nd parameter, starting with '#'. ''' output = _paddr(ins.quad[1]) t...
Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW inmediate strings for the 2nd parameter, starting with '#'.
def visit_Return(self, node): """ Compute return type and merges with others possible return type.""" self.generic_visit(node) # No merge are done if the function is a generator. if not self.yield_points: assert node.value, "Values were added in each return statement." ...
Compute return type and merges with others possible return type.
def _coerceAll(self, inputs): """ XXX """ def associate(result, obj): return (obj, result) coerceDeferreds = [] for obj, dataSet in inputs: oneCoerce = self._coerceSingleRepetition(dataSet) oneCoerce.addCallback(associate, obj) ...
XXX
async def join( self, *, remote_addrs: Iterable[str], listen_addr: str = "0.0.0.0:2377", join_token: str, advertise_addr: str = None, data_path_addr: str = None ) -> bool: """ Join a swarm. Args: listen_addr ...
Join a swarm. Args: listen_addr Used for inter-manager communication advertise_addr Externally reachable address advertised to other nodes. data_path_addr Address or interface to use for data path traffic. remote...
def calibrate(filename): """ Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file. """ params = calibration_to(filename) with nc.loader(filename) as root: for key, value in params.items(): nc.getdim(r...
Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file.
def _logs_options(p): """ Add options specific to logs subcommand. """ _default_options(p, blacklist=['cache', 'quiet']) # default time range is 0 to "now" (to include all log entries) p.add_argument( '--start', default='the beginning', # invalid, will result in 0 help='Start d...
Add options specific to logs subcommand.
def on_recv_rsp(self, rsp_pb): """ 在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法 注意该回调是在独立子线程中 :param rsp_pb: 派生类中不需要直接处理该参数 :return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明 失败时返回(RET_ERROR, ERR_MSG, None)...
在收到实时经纪数据推送后会回调到该函数,使用者需要在派生类中覆盖此方法 注意该回调是在独立子线程中 :param rsp_pb: 派生类中不需要直接处理该参数 :return: 成功时返回(RET_OK, stock_code, [bid_frame_table, ask_frame_table]), 相关frame table含义见 get_broker_queue_ 的返回值说明 失败时返回(RET_ERROR, ERR_MSG, None)
def parser(self): """ Creates a parser for the method based on the documentation. :return <OptionParser> """ usage = self.usage() if self.__doc__: usage += '\n' + nstr(self.__doc__) parse = PARSER_CLASS(usage=usage) shorts = {v: ...
Creates a parser for the method based on the documentation. :return <OptionParser>
def findByPath(self, rel, path): """Traverses children, building a path based on relation <rel>, until given path is found.""" if((path=="") or (path=="/")): return(self) (front,dummy,rest) = path.lstrip("/").partition("/") for child in self.items: if front in chi...
Traverses children, building a path based on relation <rel>, until given path is found.
def symmetric_difference(self, that): """ Return a new set with elements in either *self* or *that* but not both. """ diff = self._set.symmetric_difference(that) return self._fromset(diff, key=self._key)
Return a new set with elements in either *self* or *that* but not both.
def remove_connection(cls, pid, connection): """Remove a connection from the pool, closing it if is open. :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ ...
Remove a connection from the pool, closing it if is open. :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError
def compare_and_set(self, expected, updated): """ Atomically sets the value to the given updated value only if the current value == the expected value. :param expected: (long), the expected value. :param updated: (long), the new value. :return: (bool), ``true`` if successful; or...
Atomically sets the value to the given updated value only if the current value == the expected value. :param expected: (long), the expected value. :param updated: (long), the new value. :return: (bool), ``true`` if successful; or ``false`` if the actual value was not equal to the expected value...
def get_term_info(year, month, day): """Parse solar term and stem-branch year/month/day from a solar date. (sy, sm, sd) => (term, next_gz_month) term for year 2101,:2101.1.5(初六) 小寒 2101.1.20(廿一) 大寒 """ if year == 2101: days = [5, 20] else: days = T...
Parse solar term and stem-branch year/month/day from a solar date. (sy, sm, sd) => (term, next_gz_month) term for year 2101,:2101.1.5(初六) 小寒 2101.1.20(廿一) 大寒
def lookup_by_name(self, name): """ Function for retrieving the UnicodeCharacter associated with a name. The name lookup uses the loose matching rule UAX44-LM2 for loose matching. See the following for more info: https://www.unicode.org/reports/tr44/#UAX44-LM2 For example: ...
Function for retrieving the UnicodeCharacter associated with a name. The name lookup uses the loose matching rule UAX44-LM2 for loose matching. See the following for more info: https://www.unicode.org/reports/tr44/#UAX44-LM2 For example: ucd = UnicodeData() ucd.lookup_by_nam...
def push_frame(self, offset): """ Pushes a new contextual frame onto the stack with the given offset and a return position at the current cursor position then seeks to the new total offset. """ self._frames.append((offset, self.tell())) self._total_offset += offse...
Pushes a new contextual frame onto the stack with the given offset and a return position at the current cursor position then seeks to the new total offset.
def get_endpoint_resources(self, device_id, **kwargs): # noqa: E501 """List the resources on an endpoint # noqa: E501 The list of resources is cached by Device Management Connect, so this call does not create a message to the device. **Example usage:** curl -X GET https://api.us-east-1.mbedclou...
List the resources on an endpoint # noqa: E501 The list of resources is cached by Device Management Connect, so this call does not create a message to the device. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id} -H 'authorization: Bearer {api-key}' # noqa: E5...
def max(self, default=None): """ Calculate the maximum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`. """ return numpy.asscalar(numpy.max(self.value...
Calculate the maximum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`.
def neval(expression, globals=None, locals=None, **kwargs): """Evaluate *expression* using *globals* and *locals* dictionaries as *global* and *local* namespace. *expression* is transformed using :class:`.NapiTransformer`.""" try: import __builtin__ as builtins except ImportError: ...
Evaluate *expression* using *globals* and *locals* dictionaries as *global* and *local* namespace. *expression* is transformed using :class:`.NapiTransformer`.
def _validate_data(self): """Verifies that the data points contained in the class are valid. """ msg = "Error! Expected {} timestamps, found {}.".format( len(self._data_points), len(self._timestamps)) if len(self._data_points) != len(self._timestamps): raise Monso...
Verifies that the data points contained in the class are valid.
def write_log(self, message): """ Write a line to the VM instruction log file. Args: message (str): string message to write to file. """ if self._is_write_log and self.log_file and not self.log_file.closed: self.log_file.write(message + '\n')
Write a line to the VM instruction log file. Args: message (str): string message to write to file.
def draw(self): """Draws the checkbox.""" if not self.visible: return # Blit the current checkbox's image. if self.isEnabled: if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton: if self.value: ...
Draws the checkbox.
def candidate_priority(candidate_component, candidate_type, local_pref=65535): """ See RFC 5245 - 4.1.2.1. Recommended Formula """ if candidate_type == 'host': type_pref = 126 elif candidate_type == 'prflx': type_pref = 110 elif candidate_type == 'srflx': type_pref = 100 ...
See RFC 5245 - 4.1.2.1. Recommended Formula
def get_stp_mst_detail_output_msti_port_designated_bridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
Auto Generated Code
def option_chooser(options, attr=None): """Given an iterable, enumerate its contents for a user to choose from. If the optional `attr` is not None, that attribute in each iterated object will be printed. This function will exit the program if the user chooses the escape option. """ for num, opt...
Given an iterable, enumerate its contents for a user to choose from. If the optional `attr` is not None, that attribute in each iterated object will be printed. This function will exit the program if the user chooses the escape option.
def tree_prune_rank(self, tree, rank="species"): """Takes a TreeNode tree and prunes off any tips not at the specified rank and backwards up until all of the tips are at the specified rank. Parameters ---------- tree : `skbio.tree.TreeNode` The root node of the tree ...
Takes a TreeNode tree and prunes off any tips not at the specified rank and backwards up until all of the tips are at the specified rank. Parameters ---------- tree : `skbio.tree.TreeNode` The root node of the tree to perform this operation on. rank : {kingdom', 'phy...
def observe(self, stars, unc, ic=None): """Creates and adds appropriate synthetic Source objects for list of stars (max 2 for now) """ if ic is None: ic = get_ichrone('mist') if len(stars) > 2: raise NotImplementedError('No support yet for > 2 synthetic stars') ...
Creates and adds appropriate synthetic Source objects for list of stars (max 2 for now)
def restore(self, training_info: TrainingInfo, local_batch_idx: int, model: Model, hidden_state: dict): """ Restore learning from intermediate state. """ pass
Restore learning from intermediate state.
def format_top(counter, top=3): """ Format a top. """ items = islice(reversed(sorted(counter.iteritems(), key=lambda x: x[1])), 0, top) return u'; '.join(u'{g} ({nb})'.format(g=g, nb=nb) for g, nb in items)
Format a top.
def _set_rules(self, group, rules): """Implementation detail""" group.clear() for rule in rules: self._add_rule(group, *rule) self.invalidate()
Implementation detail
def install(name=None, pkgs=None, sources=None, **kwargs): ''' Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example, Install one package: .. code-block::...
Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example, Install one package: .. code-block:: bash salt '*' pkg.install <package name> CLI Example, In...
def summarize_neural_network_spec(mlmodel_spec): """ Summarize network into the following structure. Args: mlmodel_spec : mlmodel spec Returns: inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob. outputs : list[(str, str)] - a list of two tuple (name, descript...
Summarize network into the following structure. Args: mlmodel_spec : mlmodel spec Returns: inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob. outputs : list[(str, str)] - a list of two tuple (name, descriptor) for each output blob layers : list[(str, list[str...
def data(self, data): """Store a copy of the data.""" self._data = {det: d.copy() for (det, d) in data.items()}
Store a copy of the data.
def __to_browser(self, message_no): """ Write a single message to file and open the file in a browser """ filename = self.__to_file(message_no) try: command = self.config.get('General', 'browser_command') except (ConfigParser.NoOptionError, AttributeError): ...
Write a single message to file and open the file in a browser
def load_data(self, table_name, obj, database=None, **kwargs): """ Wraps the LOAD DATA DDL statement. Loads data into an MapD table by physically moving data files. Parameters ---------- table_name : string obj: pandas.DataFrame or pyarrow.Table database ...
Wraps the LOAD DATA DDL statement. Loads data into an MapD table by physically moving data files. Parameters ---------- table_name : string obj: pandas.DataFrame or pyarrow.Table database : string, default None (optional)
def sky(lon=None,lat=None,size=1): """ Outputs uniform points on sphere from: [0 < lon < 360] & [-90 < lat < 90] """ if lon is None: umin,umax = 0,1 else: lon = np.asarray(lon) lon = np.radians(lon + 360.*(lon<0)) if lon.size==1: umin=umax=lon/(2*np.pi) ...
Outputs uniform points on sphere from: [0 < lon < 360] & [-90 < lat < 90]
def contains(self, key): "Exact matching." index = self.follow_bytes(key, self.ROOT) if index is None: return False return self.has_value(index)
Exact matching.
def missing_whitespace_after_import_keyword(logical_line): r"""Multiple imports in form from x import (a, b, c) should have space between import statement and parenthesised name list. Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz) ...
r"""Multiple imports in form from x import (a, b, c) should have space between import statement and parenthesised name list. Okay: from foo import (bar, baz) E275: from foo import(bar, baz) E275: from importable.module import(bar, baz)
def dictionary(_object, *args): """ Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. n...
Validates a given input is of type dictionary. Example usage:: data = {'a' : {'b': 1}} schema = ('a', dictionary) You can also use this as a decorator, as a way to check for the input before it even hits a validator you may be writing. .. note:: If the argument is a callable,...
def from_array(cls, array, name=None, log_in_history=True): """Return :class:`jicimagelib.image.Image` instance from an array. :param array: :class:`numpy.ndarray` :param name: name of the image :param log_in_history: whether or not to log the creation event ...
Return :class:`jicimagelib.image.Image` instance from an array. :param array: :class:`numpy.ndarray` :param name: name of the image :param log_in_history: whether or not to log the creation event in the image's history :returns: :class:`jicimagelib...
async def remove(gc: GroupControl, slaves): """Remove speakers from group.""" click.echo("Removing from existing group: %s" % slaves) click.echo(await gc.remove(slaves))
Remove speakers from group.
def connect(self, server, port=6667): """Connects to a given IRC server. After the connection is established, it calls the on_connect event handler. """ self.socket.connect((server, port)) self.lines = self._read_lines() for event_handler in list(self.on_connect): ...
Connects to a given IRC server. After the connection is established, it calls the on_connect event handler.
def dysmetria_score(self, data_frame): """ This method calculates accuracy of target taps in pixels :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ds: dysmetria score in pixels :rtype ds: float """ tap_da...
This method calculates accuracy of target taps in pixels :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ds: dysmetria score in pixels :rtype ds: float
def add(repo_path, dest_path): ''' Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted onlin...
Registers a git repository with homely so that it will run its `HOMELY.py` script on each invocation of `homely update`. `homely add` also immediately executes a `homely update` so that the dotfiles are installed straight away. If the git repository is hosted online, a local clone will be created first....
def reset_sum_fluxes(self): """Set the sum of the fluxes calculated so far to zero. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> fluxes.fastaccess._q_sum = 5. >>> model.reset_sum_fluxes() >>> fluxes.fastaccess._q_sum 0.0 """ flux...
Set the sum of the fluxes calculated so far to zero. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> fluxes.fastaccess._q_sum = 5. >>> model.reset_sum_fluxes() >>> fluxes.fastaccess._q_sum 0.0
def merge(d1, d2): """Merge two raw datasets into one. Parameters ---------- d1 : dict d2 : dict Returns ------- dict """ if d1['formula_id2latex'] is None: formula_id2latex = {} else: formula_id2latex = d1['formula_id2latex'].copy() formula_id2latex.upd...
Merge two raw datasets into one. Parameters ---------- d1 : dict d2 : dict Returns ------- dict
def _StartProfiling(self, configuration): """Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration. """ if not configuration: return if configuration.HaveProfileMemoryGuppy(): self._guppy_memory_profiler = profilers.GuppyMemoryProfiler( ...
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration.
def get_context(template, line, num_lines=5, marker=None): ''' Returns debugging context around a line in a given string Returns:: string ''' template_lines = template.splitlines() num_template_lines = len(template_lines) # In test mode, a single line template would return a crazy line num...
Returns debugging context around a line in a given string Returns:: string
def postags(self): """The list of word part-of-speech tags. Ambiguous cases are separated with pipe character by default. Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries. """ if not self.is_tagged(ANALYSIS): se...
The list of word part-of-speech tags. Ambiguous cases are separated with pipe character by default. Use :py:meth:`~estnltk.text.Text.get_analysis_element` to specify custom separator for ambiguous entries.
def mset(self, mapping): """Sets the given keys to their respective values. :meth:`~tredis.RedisClient.mset` replaces existing values with new values, just as regular :meth:`~tredis.RedisClient.set`. See :meth:`~tredis.RedisClient.msetnx` if you don't want to overwrite existing v...
Sets the given keys to their respective values. :meth:`~tredis.RedisClient.mset` replaces existing values with new values, just as regular :meth:`~tredis.RedisClient.set`. See :meth:`~tredis.RedisClient.msetnx` if you don't want to overwrite existing values. :meth:`~tredis.Redis...
def doc(self): """ Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: ...
Formats a table of documentation strings to help users remember variable names, and understand how they are translated into python safe names. Returns ------- docs_df: pandas dataframe Dataframe with columns for the model components: - Real names ...
def create(config, name, group, type): """Create an LDAP user.""" if type not in ('user', 'service'): raise click.BadOptionUsage("--type must be 'user' or 'service'") client = Client() client.prepare_connection() user_api = API(client) group_api = GroupApi(cli...
Create an LDAP user.
def apply_with(self, status=None, raw=None, header=None): """ update header, status code, raw datum, ...etc :param int status: status code :param str raw: body content :param dict header: header section :return: return self for chaining :rtype: Response """ ...
update header, status code, raw datum, ...etc :param int status: status code :param str raw: body content :param dict header: header section :return: return self for chaining :rtype: Response
def pointer_gate(num_qubits, U): """ Make a pointer gate on `num_qubits`. The one-qubit gate U will act on the qubit addressed by the pointer qubits interpreted as an unsigned binary integer. There are P = floor(lg(num_qubits)) pointer qubits, and qubits numbered N - 1 N - 2 ...
Make a pointer gate on `num_qubits`. The one-qubit gate U will act on the qubit addressed by the pointer qubits interpreted as an unsigned binary integer. There are P = floor(lg(num_qubits)) pointer qubits, and qubits numbered N - 1 N - 2 ... N - P are those reserved t...
def hjorth(X, D=None): """ Compute Hjorth mobility and complexity of a time series from either two cases below: 1. X, the time series of type list (default) 2. D, a first order differential sequence of X (if D is provided, recommended to speed up) In case 1, D is computed using N...
Compute Hjorth mobility and complexity of a time series from either two cases below: 1. X, the time series of type list (default) 2. D, a first order differential sequence of X (if D is provided, recommended to speed up) In case 1, D is computed using Numpy's Difference function. ...
def set_card_simple(self, title, content): """Set response card as simple type. title and content cannot exceed 8,000 characters. Args: title: str. Title of Simple or Standard type card. content: str. Content of Simple type card. """ self.response.card.t...
Set response card as simple type. title and content cannot exceed 8,000 characters. Args: title: str. Title of Simple or Standard type card. content: str. Content of Simple type card.
def start_container(self): """Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node. """ self.__container_lengths.append(self.current_container...
Add a node to the tree that represents the start of a container. Until end_container is called, any nodes added through add_scalar_value or start_container will be children of this new node.
def load(abspath, default=None, enable_verbose=True): """Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: defa...
Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: default ``dict()``, if ``abspath`` not exists, return the ...
def has_no_flat_neurites(neuron, tol=0.1, method='ratio'): '''Check that a neuron has no flat neurites Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' \ as described in :meth:`neurom.che...
Check that a neuron has no flat neurites Arguments: neuron(Neuron): The neuron object to test tol(float): tolerance method(string): way of determining flatness, 'tolerance', 'ratio' \ as described in :meth:`neurom.check.morphtree.get_flat_neurites` Returns: CheckResult ...
def fillNoneValues(column): """Fill all NaN/NaT values of a column with an empty string Args: column (pandas.Series): A Series object with all rows. Returns: column: Series with filled NaN values. """ if column.dtype == object: column.fillna('', inplace=True) return col...
Fill all NaN/NaT values of a column with an empty string Args: column (pandas.Series): A Series object with all rows. Returns: column: Series with filled NaN values.
async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: ...
Retrieve messages using before parameter.
def write_average_score_row(fp, score_name, scores): """ Simple utility function that writes an average score row in a file designated by a file pointer. Inputs: - fp: A file pointer. - score_name: What it says on the tin. - scores: An array of average score values corresponding ...
Simple utility function that writes an average score row in a file designated by a file pointer. Inputs: - fp: A file pointer. - score_name: What it says on the tin. - scores: An array of average score values corresponding to each of the training set percentages.
def fit_iSet(Y, U_R=None, S_R=None, covs=None, Xr=None, n_perms=0, Ie=None, strat=False, verbose=True): """ Args: Y: [N, P] phenotype matrix S_R: N vector of eigenvalues of R U_R: [N, N] eigenvector matrix of R covs: [N, K] matrix for K c...
Args: Y: [N, P] phenotype matrix S_R: N vector of eigenvalues of R U_R: [N, N] eigenvector matrix of R covs: [N, K] matrix for K covariates Xr: [N, S] genotype data of the set component n_perms: number of permutations to consider ...
def receive(self, x, mesh_axis, source_pcoord): """Collective receive in groups. Each group contains the processors that differ only in mesh_axis. ```python group_size = self.shape[mesh_axis].size ``` Args: x: a LaidOutTensor mesh_axis: an integer source_pcoord: a list of op...
Collective receive in groups. Each group contains the processors that differ only in mesh_axis. ```python group_size = self.shape[mesh_axis].size ``` Args: x: a LaidOutTensor mesh_axis: an integer source_pcoord: a list of optional integers. Each element is either None or...
def add(self, point, value): """ Assign all self.merge_values to the self._mergeMatrix Get the position/intensity of a value """ # check range for p, r in zip(point, self.range): if p < r[0] or p > r[1]: return # check nan if is...
Assign all self.merge_values to the self._mergeMatrix Get the position/intensity of a value
def expand_elements(compact_el, as_str=False): """ Create a list of integers given a string or list of compacted elements This is partly the opposite of compact_elements, but is more flexible. compact_el can be a list or a string. If compact_el is a list, each element is processed individually as ...
Create a list of integers given a string or list of compacted elements This is partly the opposite of compact_elements, but is more flexible. compact_el can be a list or a string. If compact_el is a list, each element is processed individually as a string (meaning list elements can contain commas, ranges,...
def from_message_and_data(cls, message: str, data: Dict[str, Any] ) -> 'BugZooException': """ Reproduces an exception from the message and data contained in its dictionary-based description. """ ...
Reproduces an exception from the message and data contained in its dictionary-based description.
def run(items): """Run MetaSV if we have enough supported callers, adding output to the set of calls. """ assert len(items) == 1, "Expect one input to MetaSV ensemble calling" data = items[0] work_dir = _sv_workdir(data) out_file = os.path.join(work_dir, "variants.vcf.gz") cmd = _get_cmd() +...
Run MetaSV if we have enough supported callers, adding output to the set of calls.
def _read_configuration_file(self, config_filename): """ Reads parameters from the configuration file. :param str config_filename: The name of the configuration file. """ config = configparser.ConfigParser() config.read(config_filename) self._constants_filename ...
Reads parameters from the configuration file. :param str config_filename: The name of the configuration file.
def swipe_up(self, width: int = 1080, length: int = 1920) -> None: '''Swipe up.''' self.swipe(0.5*width, 0.8*length, 0.5*width, 0.2*length)
Swipe up.
def _bot(self, k): """ Description: Bottom k breaking Parameters: k: the number of alternatives to break from lowest rank """ if k < 2: raise ValueError("k smaller than 2") G = np.ones((self.m, self.m)) np.fill_diagona...
Description: Bottom k breaking Parameters: k: the number of alternatives to break from lowest rank
def get_outer_frame_variables(): """ Get a dict of local and global variables of the first outer frame from another file. """ cur_filename = inspect.getframeinfo(inspect.currentframe()).filename outer_frame = next(f for f in inspect.getouterframes(inspect.currentframe()) ...
Get a dict of local and global variables of the first outer frame from another file.
def atlas_peer_download_zonefile_inventory( my_hostport, peer_hostport, maxlen, bit_offset=0, timeout=None, peer_table={} ): """ Get the zonefile inventory from the remote peer Start from the given bit_offset NOTE: this doesn't update the peer table health by default; you'll have to explicitly pass...
Get the zonefile inventory from the remote peer Start from the given bit_offset NOTE: this doesn't update the peer table health by default; you'll have to explicitly pass in a peer table (i.e. setting to {} ensures that nothing happens).