positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def prior_prior_model_name_dict(self): """ Returns ------- prior_prior_model_name_dict: {Prior: str} A dictionary mapping priors to the names of associated prior models. Each prior will only have one prior model name; if a prior is shared by two prior models then ...
Returns ------- prior_prior_model_name_dict: {Prior: str} A dictionary mapping priors to the names of associated prior models. Each prior will only have one prior model name; if a prior is shared by two prior models then one of those prior model's names will be in this ...
def get_meta(self): """Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a ...
Get the metadata object for this Point Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkEx...
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
Read pre-trained word vectors from an eventually compressed text file, possibly contained inside an archive with multiple files. The text file is assumed to be utf-8 encoded with space-separated fields: [word] [dim 1] [dim 2] ... Lines that contain more numerical tokens than ``embedding_dim`` raise a warni...
def setdefault(self, k, d=None): """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ if k not in self._col_dict: self._set_key(k, d) return self._col_dict.get(k)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
def handle_missing(self, instance, ctx): """ Handle a missing attribute on `instance`. This is called whenever no value for the attribute is found during parsing. The call to :meth:`missing` is independent of the value of `required`. If the `missing` callback is not :data:`None`...
Handle a missing attribute on `instance`. This is called whenever no value for the attribute is found during parsing. The call to :meth:`missing` is independent of the value of `required`. If the `missing` callback is not :data:`None`, it is called with the `instance` and the `ctx` as a...
def run(self): """ Run the stats. The source must yield Row proxies. """ self._func, self._func_code = self.build() def process_row(row): try: self._func(self._stats, row) except TypeError as e: raise TypeError("Failed for '{}'; ...
Run the stats. The source must yield Row proxies.
def _explain(self, tree): """ Set up the engine to do a dry run of a query """ self._explaining = True self._call_list = [] old_call = self.connection.call def fake_call(command, **kwargs): """ Replacement for connection.call that logs args """ if command...
Set up the engine to do a dry run of a query
def _lookup_drill(name, rdtype, timeout=None, servers=None, secure=None): ''' Use drill to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: command return timeout :param servers: [] of servers to use :return: [] of records or False if erro...
Use drill to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: command return timeout :param servers: [] of servers to use :return: [] of records or False if error
def handle(self, client, subhooks=()): """Handle a new update. Fetches new data from the client, then compares it to the previous lookup. Returns: (bool, new_data): whether changes occurred, and the new value. """ new_data = self.fetch(client) # Hol...
Handle a new update. Fetches new data from the client, then compares it to the previous lookup. Returns: (bool, new_data): whether changes occurred, and the new value.
def repeat(f, dt=1/60): """ 重复执行函数f,时间间隔dt """ stop(f) pyglet.clock.schedule_interval(f, dt)
重复执行函数f,时间间隔dt
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
Make api fetch request.
def range_monthly(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with MONTHLY stops """ return stops(start=start, stop=stop, freq=MONTHLY, timezone=timezone, count=count)
This an alternative way to generating sets of Delorean objects with MONTHLY stops
def envelope(self, header, body): """ Build the B{<Envelope/>} for a SOAP outbound message. @param header: The SOAP message B{header}. @type header: L{Element} @param body: The SOAP message B{body}. @type body: L{Element} @return: The SOAP envelope containing the...
Build the B{<Envelope/>} for a SOAP outbound message. @param header: The SOAP message B{header}. @type header: L{Element} @param body: The SOAP message B{body}. @type body: L{Element} @return: The SOAP envelope containing the body and header. @rtype: L{Element}
def fit(self, X, y=None): """ Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer. Parameters ---------- X : array-like, shape (n_samples, n_fe...
Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_s...
def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, name=self.name, id=self.id))
Creates the node.
def add(self, *args): """ Add object(s) to the Container. :param *args: Any objects to add to the Container. :returns: full list of Container's child objects """ self.children.extend(args) bump_child_depth(self, self._depth) return self.children
Add object(s) to the Container. :param *args: Any objects to add to the Container. :returns: full list of Container's child objects
def process(self, argv=sys.argv, ifile=sys.stdin, ofile=sys.stdout): """ Process data. :param argv: Command line arguments. :type argv: list or tuple :param ifile: Input data file. :type ifile: file :param ofile: Output data file. :type ofile: file :re...
Process data. :param argv: Command line arguments. :type argv: list or tuple :param ifile: Input data file. :type ifile: file :param ofile: Output data file. :type ofile: file :return: :const:`None` :rtype: NoneType
def confirm_dialog(self, emitter): """event called pressing on OK button. """ #here the user input is transferred to the dict, ready to use self.from_fields_to_dict() return super(ProjectConfigurationDialog,self).confirm_dialog(self)
event called pressing on OK button.
def _tar_and_copy(src_dir, target_dir): """Tar and gzip src_dir and copy to GCS target_dir.""" src_dir = src_dir.rstrip("/") target_dir = target_dir.rstrip("/") tmp_dir = tempfile.gettempdir().rstrip("/") src_base = os.path.basename(src_dir) shell_run( "tar --exclude=.git -zcf {tmp_dir}/{src_base}.tar...
Tar and gzip src_dir and copy to GCS target_dir.
def set_status(self, action, target): """ Sets query status with format: "{domain} ({action}) {target}" """ try: target = unquote(target) except (AttributeError, TypeError): pass status = "%s (%s) %s" % (self.domain, action, target) status...
Sets query status with format: "{domain} ({action}) {target}"
def strip_toplevel_name(filelist): """Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] """ if not filelist: return filelist prefix = ...
Strip toplevel name from a file list. >>> strip_toplevel_name(['a', 'a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d'] >>> strip_toplevel_name(['a/b', 'a/c', 'a/c/d']) ['b', 'c', 'c/d']
def get(cls, **kwargs): """ Generic get() for one item only >>> ec2.instances.get(name='production-web-01') <Instance: ...> """ things = cls.filter(**kwargs) if len(things) > 1: # Raise an exception if more than one object is matched raise...
Generic get() for one item only >>> ec2.instances.get(name='production-web-01') <Instance: ...>
def get_item_with_href(self, href): """ Returns item for defined HREF. >>> book.get_item_with_href('EPUB/document.xhtml') :Args: - href: HREF for the item we are searching for :Returns: Returns item object. Returns None if nothing was found. """ ...
Returns item for defined HREF. >>> book.get_item_with_href('EPUB/document.xhtml') :Args: - href: HREF for the item we are searching for :Returns: Returns item object. Returns None if nothing was found.
def acknowledge_message(self): """Comment provided when acknowledging the alarm.""" if (self.is_acknowledged and self._proto.acknowledgeInfo.HasField('acknowledgeMessage')): return self._proto.acknowledgeInfo.acknowledgeMessage return None
Comment provided when acknowledging the alarm.
def _check_insersection(self, version, ranges): """Check that a version is inside all of a list of ranges""" for ver_range in ranges: if not self._check_ver_range(version, ver_range): return False return True
Check that a version is inside all of a list of ranges
def enforce_periodic_boundary_conditions( self ): """ Ensure that all lattice sites are within the central periodic image of the simulation cell. Sites that are outside the central simulation cell are mapped back into this cell. Args: None Returns: ...
Ensure that all lattice sites are within the central periodic image of the simulation cell. Sites that are outside the central simulation cell are mapped back into this cell. Args: None Returns: None
def get(self, campaign_id, nick=None): '''xxxxx.xxxxx.campaign.area.get =================================== 取得一个推广计划的投放地域设置''' request = TOPRequest('xxxxx.xxxxx.campaign.area.get') request['campaign_id'] = campaign_id if nick!=None: request['nick'] = nick self.cre...
xxxxx.xxxxx.campaign.area.get =================================== 取得一个推广计划的投放地域设置
def decode_pc11_message(raw_string): """Decode PC11 message, which usually contains DX Spots""" data = {} spot = raw_string.split("^") data[const.FREQUENCY] = float(spot[1]) data[const.DX] = spot[2] data[const.TIME] = datetime.fromtimestamp(mktime(strptime(spot[3]+" "+spot[4][:-1], "%d-%b-%Y %H...
Decode PC11 message, which usually contains DX Spots
def get_coverage(config: CoverageConfig) -> 'Coverage': """ Returns a Coverage instance. :param config: Coverage configuration. :return: Instance of Coverage. """ if config.type == C.COVERAGE_COUNT or config.type == C.COVERAGE_FERTILITY: utils.check_condition(config.num_hidden == 1, "Co...
Returns a Coverage instance. :param config: Coverage configuration. :return: Instance of Coverage.
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER)\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters or conversion chains matching the provided query. :param from_type: a required type o...
Utility method to find all converters or conversion chains matching the provided query. :param from_type: a required type of input object, or JOKER for 'wildcard'(*) . WARNING: "from_type=AnyObject/object/Any" means "all converters able to source from anything", which is different from "from_ty...
def _z2deriv(self,R,z,phi=0.,t=0.): """ NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUT...
NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second vertical derivative H...
def size(config, accounts=(), day=None, group=None, human=True, region=None): """size of exported records for a given day.""" config = validate.callback(config) destination = config.get('destination') client = boto3.Session().client('s3') day = parse(day) def export_size(client, account): ...
size of exported records for a given day.
def native(self): """ The native Python datatype representation of this value :return: An OrderedDict or None. If an OrderedDict, all child values are recursively converted to native representation also. """ if self.contents is None: return N...
The native Python datatype representation of this value :return: An OrderedDict or None. If an OrderedDict, all child values are recursively converted to native representation also.
def toarray(vari): """ Convert polynomial array into a numpy.asarray of polynomials. Args: vari (Poly, numpy.ndarray): Input data. Returns: (numpy.ndarray): A numpy array with ``Q.shape==A.shape``. Examples: >>> poly = cp.prange(3) >>> print...
Convert polynomial array into a numpy.asarray of polynomials. Args: vari (Poly, numpy.ndarray): Input data. Returns: (numpy.ndarray): A numpy array with ``Q.shape==A.shape``. Examples: >>> poly = cp.prange(3) >>> print(poly) [1, q0, q0^2] ...
def register(self): """Register spec codec""" # Assume utf8 encoding utf8 = encodings.search_function('utf8') class StreamReader(utf_8.StreamReader): """Used by cPython to deal with a spec file""" def __init__(sr, stream, *args, **kwargs): codecs....
Register spec codec
def _get_item(self, package, flavor): """Returns the item for ordering a dedicated host.""" for item in package['items']: if item['keyName'] == flavor: return item raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor)
Returns the item for ordering a dedicated host.
def find_first_file_with_ext(base_paths, prefix, exts): """Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename p...
Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename prefix of the file for which to search. exts: An ordered...
def main(argv=None): """ A simple command-line interface for the cgroups check of BenchExec. """ if argv is None: argv = sys.argv parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description= """Check whether cgroups are available and can be used for Benc...
A simple command-line interface for the cgroups check of BenchExec.
def _create_temporary_projects(enabled_regions, args): """ Creates a temporary project needed to build an underlying workflow for a global workflow. Returns a dictionary with region names as keys and project IDs as values The regions in which projects will be created can be: i. regions specifie...
Creates a temporary project needed to build an underlying workflow for a global workflow. Returns a dictionary with region names as keys and project IDs as values The regions in which projects will be created can be: i. regions specified in dxworkflow.json "regionalOptions" ii. regions specified as...
def allocation(self, node_id=None, params=None): """ Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-allocation.html>`_ :arg node_id: A comma-separated...
Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-allocation.html>`_ :arg node_id: A comma-separated list of node IDs or names to limit the returned informat...
def resizeToContents(self): """ Resizes the list widget to fit its contents vertically. """ if self.count(): item = self.item(self.count() - 1) rect = self.visualItemRect(item) height = rect.bottom() + 8 height = max(28, height) ...
Resizes the list widget to fit its contents vertically.
def complete_experiment(self, status): """Sends worker status ('worker_complete' or 'worker_failed') to the experiment server. """ url = self.driver.current_url p = urllib.parse.urlparse(url) complete_url = "%s://%s/%s?participant_id=%s" complete_url = complete_ur...
Sends worker status ('worker_complete' or 'worker_failed') to the experiment server.
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(r...
Reads a requirements file. Args: req_file (str): Filename of requirements file
def uploadFiles(self): """ Uploads all the files in 'filesToSync' """ for each_file in self.filesToSync: self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"])
Uploads all the files in 'filesToSync'
def find_metabolites_not_produced_with_open_bounds(model): """ Return metabolites that cannot be produced with open exchange reactions. A perfect model should be able to produce each and every metabolite when all medium components are available. Parameters ---------- model : cobra.Model ...
Return metabolites that cannot be produced with open exchange reactions. A perfect model should be able to produce each and every metabolite when all medium components are available. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns -------...
def clone_parler_translations(self, dst_obj): """ Clone each of the translations from an object and relate them to another. :param self: The object to get the translations from. :param dst_obj: The object to relate the new translations to. :return: None """ ...
Clone each of the translations from an object and relate them to another. :param self: The object to get the translations from. :param dst_obj: The object to relate the new translations to. :return: None
def mutation(self, only_add=False): ''' Mutation for a graph ''' types = [] if self.layer_num() < self.max_layer_num: types.append(0) types.append(1) if self.layer_num() > 5 and only_add is False: types.append(2) types.appen...
Mutation for a graph
def ring_position(self): """The current position of the ring, in degrees counterclockwise from the northern-most point of the ring in the tablet's current logical orientation. If the source is :attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`, libinput sends a terminating event with a ring value of...
The current position of the ring, in degrees counterclockwise from the northern-most point of the ring in the tablet's current logical orientation. If the source is :attr:`~libinput.constant.TabletPadRingAxisSource.FINGER`, libinput sends a terminating event with a ring value of -1 when the finger is lifte...
def get_fault(self, reply): """ Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap ...
Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap reply message. @type reply: str ...
def _check_command_stats(self, conn, tags): """Get command-specific statistics from redis' INFO COMMANDSTATS command """ try: command_stats = conn.info("commandstats") except Exception: self.warning('Could not retrieve command stats from Redis. INFO COMMANDSTATS o...
Get command-specific statistics from redis' INFO COMMANDSTATS command
def insert_value(self, keys, value): """ Insert a value (data item) into this tree node and then its children. This will be called in response to a new data item being inserted into the document. Also updates the tree node's cumulative child count. """ ...
Insert a value (data item) into this tree node and then its children. This will be called in response to a new data item being inserted into the document. Also updates the tree node's cumulative child count.
def unassign_activity_from_objective_bank(self, activity_id, objective_bank_id): """Removes a ``Activity`` from a ``ObjectiveBank``. arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ``ObjectiveBank`` ...
Removes a ``Activity`` from a ``ObjectiveBank``. arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity`` arg: objective_bank_id (osid.id.Id): the ``Id`` of the ``ObjectiveBank`` raise: NotFound - ``activity_id`` or ``objective_bank_id`` not found or ...
def _select_exposures_requiring_dophot_extraction( self, batch=10): """* select exposures requiring dophot extraction* **Key Arguments:** - ``batch`` -- the batch size of dophot file to process **Return:** - ``expnames`` -- the names of the expso...
* select exposures requiring dophot extraction* **Key Arguments:** - ``batch`` -- the batch size of dophot file to process **Return:** - ``expnames`` -- the names of the expsoures in the batch - ``remaining`` -- the number of exposured remainging that require orbfit...
def str_to_two_byte_iter(string): """ Return a iter consisting of two byte chars from a string. """ bstring = string.encode() bytes = bytearray() for char in bstring: bytes.append(char) bytes.append(0) return bytes
Return a iter consisting of two byte chars from a string.
def can_fetch(self, request: Request, file=None) -> bool: '''Return whether the request can fetched. Args: request: Request. file: A file object to where the robots.txt contents are written. Coroutine. ''' try: return self.can_fetch_pool(requ...
Return whether the request can fetched. Args: request: Request. file: A file object to where the robots.txt contents are written. Coroutine.
def on_predicate(wait_gen, predicate=operator.not_, max_tries=None, max_time=None, jitter=full_jitter, on_success=None, on_backoff=None, on_giveup=None, logger='backoff', ...
Returns decorator for backoff and retry triggered by predicate. Args: wait_gen: A generator yielding successive wait times in seconds. predicate: A function which when called on the return value of the target function will trigger backoff when considered truthily...
def key_to_kind(cls, key): """Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key. """ if key.kind() == Kind.KIND_NAME: return key.id() else: return key.parent().id()
Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key.
def from_inline(cls: Type[ESCoreEndpointType], inline: str) -> ESCoreEndpointType: """ Return ESCoreEndpoint instance from endpoint string :param inline: Endpoint string :return: """ m = ESCoreEndpoint.re_inline.match(inline) if m is None: raise Malfo...
Return ESCoreEndpoint instance from endpoint string :param inline: Endpoint string :return:
def nla_put_u16(msg, attrtype, value): """Add 16 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L588 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to sto...
Add 16 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L588 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint16()). Retu...
def resolve_id(resolver, identifier, name='object'): """Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in ...
Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages
def _to_memory_mode(self): """Close the backing file, forget filename, *do* change to memory mode.""" self._adata.__X = self._adata.X[()] self._file.close() self._file = None self._filename = None
Close the backing file, forget filename, *do* change to memory mode.
def is_remote_file_modified(web_file, destination): """ Check if online file has been modified. Args: :web_file: online file to check. :destination: path of the offline file to compare. """ try: # check datetime of last modified in file. last_mod = web_file.headers.ge...
Check if online file has been modified. Args: :web_file: online file to check. :destination: path of the offline file to compare.
def bind(self, name): """ Bind a `Column` object to its name. """ return _BoundColumnDescr( dtype=self.dtype, missing_value=self.missing_value, name=name, doc=self.doc, metadata=self.metadata, )
Bind a `Column` object to its name.
def selected_canvas_explayer(self): """Obtain the canvas exposure layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer """ if self.lstCanvasExpLayers.selectedItems(): item = self.lstCanvasExpLayers.currentItem() ...
Obtain the canvas exposure layer selected by user. :returns: The currently selected map layer in the list. :rtype: QgsMapLayer
def dump_dict(dict_input, indent=4): """ 辞書型変数を文字列に変換して返す """ dict_work = dict(dict_input) """ for key, value in six.iteritems(dict_input): if any([f(value) for f in (is_float, isDict, is_list_or_tuple)]): dict_work[key] = value continue try: ...
辞書型変数を文字列に変換して返す
def counting_sort(arr): """ Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr ...
Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr Complexity: 0(n)
def mavlink_to_json(msg): '''Translate mavlink python messages in json string''' ret = '\"%s\": {' % msg._type for fieldname in msg._fieldnames: data = getattr(msg, fieldname) ret += '\"%s\" : \"%s\", ' % (fieldname, data) ret = ret[0:-2] + '}' return ret
Translate mavlink python messages in json string
def _make_size_legend(self): """ Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric. """ # Compute the size of the markers and scale them to our figure size # NOTE: the marker size is the area...
Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric.
def antoine(target, A, B, C, temperature='pore.temperature'): r""" Uses Antoine equation [1] to estimate vapor pressure of a pure component Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculat...
r""" Uses Antoine equation [1] to estimate vapor pressure of a pure component Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary ther...
def getPhysicalMinimum(self,chn=None): """ Returns the minimum physical value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>>...
Returns the minimum physical value of signal edfsignal. Parameters ---------- chn : int channel number Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getPhysicalMinimum(0)==-1000.0 True >>> ...
def _update_progress_bar(self): # type: (SyncCopy) -> None """Update progress bar :param SyncCopy self: this """ blobxfer.operations.progress.update_progress_bar( self._general_options, 'synccopy', self._synccopy_start_time, self._s...
Update progress bar :param SyncCopy self: this
def RechazarCTG(self, carta_porte, ctg, motivo): "El Destino puede rechazar el CTG a través de la siguiente operatoria" response = self.client.rechazarCTG(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRep...
El Destino puede rechazar el CTG a través de la siguiente operatoria
def _note_reply_pending(self, option, state): """Record the status of requested Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state
Record the status of requested Telnet options.
def _initialize(self, con): """Set up tables in SQL""" if self.initialized: return SQLite3Database()._initialize(con) # ASE db initialization cur = con.execute( 'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"') if cur.fetchone()[0] == 0: # n...
Set up tables in SQL
def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ trace('onEnable') self._disable() self._aio_context.submit(self._aio_recv_block_list) self._rea...
The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations.
def find_element_by_name(self, name, update=False) -> Elements: '''Finds an element by name. Args: name: The name of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Rai...
Finds an element by name. Args: name: The name of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. ...
def ms_panset(self, viewer, event, data_x, data_y, msg=True): """An interactive way to set the pan position. The location (data_x, data_y) will be centered in the window. """ if self.canpan and (event.state == 'down'): self._panset(viewer, data_x, data_y, m...
An interactive way to set the pan position. The location (data_x, data_y) will be centered in the window.
def add_unique_template_variables(self, options): """Update map template variables specific to circle visual""" options.update(dict( geojson_data=json.dumps(self.data, ensure_ascii=False), colorProperty=self.color_property, colorType=self.color_function_type, ...
Update map template variables specific to circle visual
def _dataset_line(args): """Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'. """ if args['command'] == 'list...
Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'.
def set_status(self, status: Status, increment_try_count: bool=True, filename: str=None): '''Mark the item with the given status. Args: status: a value from :class:`Status`. increment_try_count: if True, increment the ``try_count`` value ...
Mark the item with the given status. Args: status: a value from :class:`Status`. increment_try_count: if True, increment the ``try_count`` value
def search_records(self, **kwargs): """ rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields a list of fields to return, specified using the fieldName parameter from Fields with type records ...
rq Search Query in iDigBio Query Format, using Record Query Fields sort field to sort on, pick from Record Query Fields fields a list of fields to return, specified using the fieldName parameter from Fields with type records fields_exclude a list of fields to exclude, specified...
def execute_executable(nova_args, env_vars): """ Executes the executable given by the user. Hey, I know this method has a silly name, but I write the code here and I'm silly. """ process = subprocess.Popen(nova_args, stdout=sys.stdout, ...
Executes the executable given by the user. Hey, I know this method has a silly name, but I write the code here and I'm silly.
def create_window(title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color='#FFFFFF', text_select=False, frameless=False, debug=False): """ Create a web view window using a nat...
Create a web view window using a native GUI. The execution blocks after this function is invoked, so other program logic must be executed in a separate thread. :param title: Window title :param url: URL to load :param width: window width. Default is 800px :param height:window height. Default is 600p...
def parents(self): """ Returns list of parents changesets. """ return [self.repository.get_changeset(parent.rev()) for parent in self._ctx.parents() if parent.rev() >= 0]
Returns list of parents changesets.
def urandom(*args: Any, **kwargs: Any) -> bytes: """Return a bytes object containing random bytes. :return: Bytes. """ return os.urandom(*args, **kwargs)
Return a bytes object containing random bytes. :return: Bytes.
def post_optimization_step(self, batch_info, device, model, rollout): """ Steps to take after optimization has been done""" if batch_info.aggregate_batch_number % self.target_update_frequency == 0: self.target_model.load_state_dict(model.state_dict()) self.target_model.eval()
Steps to take after optimization has been done
def needkwargs(*argnames): """Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call. """ ...
Function decorator which checks that the decorated function is called with a set of required kwargs. Args: *argnames: String keyword argument names. Raises: ValueError: If a required kwarg is missing in the decorated function call.
def sync(self, resolution, limit=None, **kwargs): """ Add current Music library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for detail...
Add current Music library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions. P...
def download_software(name, version=None, synch=False, check=False): ''' Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file fro...
Ensures that a software version is downloaded. name: The name of the module function to execute. version(str): The software version to check. If this version is not already downloaded, it will attempt to download the file from Palo Alto. synch(bool): If true, after downloading the file it will be syn...
def add_star(self, component=None, **kwargs): """ Shortcut to :meth:`add_component` but with kind='star' """ kwargs.setdefault('component', component) return self.add_component('star', **kwargs)
Shortcut to :meth:`add_component` but with kind='star'
def getElementsByClassName(start_node: ParentNode, class_name: str ) -> NodeList: """Get child nodes which has ``class_name`` class attribute.""" classes = set(class_name.split(' ')) return getElementsBy( start_node, lambda node: classes.issubset(set(node.classList...
Get child nodes which has ``class_name`` class attribute.
def start_instance(self, key_name, public_key_path, private_key_path, security_group, flavor, image_id, image_userdata, username=None, node_name=None, **kwargs): """Starts a new instance on the cloud using the given properties. The following tasks are done t...
Starts a new instance on the cloud using the given properties. The following tasks are done to start an instance: * establish a connection to the cloud web service * check ssh keypair and upload it if it does not yet exist. This is a locked process, since this function might be called...
def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all): """ Given the model IDs to sync, fetch all model objects to sync """ model_objs_to_sync = {} for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items(): model_qset = entity_registry.entity_registry.get(ctype.m...
Given the model IDs to sync, fetch all model objects to sync
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins.
def adapter_type(self, adapter_type): """ Sets the adapter type for this VMware VM instance. :param adapter_type: adapter type (string) """ self._adapter_type = adapter_type log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.na...
Sets the adapter type for this VMware VM instance. :param adapter_type: adapter type (string)
def page(self, course): """ Get all data and display the page """ if not self.webdav_host: raise web.notfound() url = self.webdav_host + "/" + course.get_id() username = self.user_manager.session_username() apikey = self.user_manager.session_api_key() return ...
Get all data and display the page
def update(self, other): """ Modify Series in place using non-NA values from passed Series. Aligns on index. Parameters ---------- other : Series Examples -------- >>> s = pd.Series([1, 2, 3]) >>> s.update(pd.Series([4, 5, 6])) >>...
Modify Series in place using non-NA values from passed Series. Aligns on index. Parameters ---------- other : Series Examples -------- >>> s = pd.Series([1, 2, 3]) >>> s.update(pd.Series([4, 5, 6])) >>> s 0 4 1 5 2 ...
def get_weights(self): """ Returns: dict: Model's trained weights. """ if self.is_trained() is False: # print("Model not fitted yet. Use object.fit() to fit the model.") return None var_res = self._var_res weights = self._var_res_to_we...
Returns: dict: Model's trained weights.
def _find_contpix(wl, fluxes, ivars, target_frac): """ Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, par...
Find continuum pix in spec, meeting a set target fraction Parameters ---------- wl: numpy ndarray rest-frame wavelength vector fluxes: numpy ndarray pixel intensities ivars: numpy ndarray inverse variances, parallel to fluxes target_frac: float the fractio...
def get_taf_remarks(txt: str) -> (str, str): # type: ignore """ Returns report and remarks separated if found """ remarks_start = find_first_in_list(txt, TAF_RMK) if remarks_start == -1: return txt, '' remarks = txt[remarks_start:] txt = txt[:remarks_start].strip() return txt, r...
Returns report and remarks separated if found