code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def cache_control_expires(num_hours): """ Set the appropriate Cache-Control and Expires headers for the given number of hours. """ num_seconds = int(num_hours * 60 * 60) def decorator(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *...
Set the appropriate Cache-Control and Expires headers for the given number of hours.
def to_meshpoint(meshcode, lat_multiplier, lon_multiplier): """地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 5倍(5km四方):5000 4倍(4km四方):4000 2.5倍(...
def MCLA(hdf5_file_name, cluster_runs, verbose = False, N_clusters_max = None): """Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (def...
Meta-CLustering Algorithm for a consensus function. Parameters ---------- hdf5_file_name : file handle or string cluster_runs : array of shape (n_partitions, n_samples) verbose : bool, optional (default = False) N_clusters_max : int, optional (default = None) Returns...
def restore_data(self, data_dict): """ Restore the data dict - update the flask session and this object """ session[self._base_key] = data_dict self._data_dict = session[self._base_key]
Restore the data dict - update the flask session and this object
def add_copies(self, node, parent, elem, minel): """Add appropriate number of `elem` copies to `parent`.""" rep = 0 if minel is None else int(minel.arg) - 1 for i in range(rep): parent.append(copy.deepcopy(elem))
Add appropriate number of `elem` copies to `parent`.
def get_service_status(service): '''Update the status of a particular service in the database. ''' dbs = db.get_session() srvs = dbs.query(db.ServiceStates).filter(db.ServiceStates.type == service) if srvs.count(): return srvs[0].status return db.ServiceStatus.STOPPED
Update the status of a particular service in the database.
def incr(self, field, by=1): """ :see::meth:RedisMap.incr """ return self._client.hincrby(self.key_prefix, field, by)
:see::meth:RedisMap.incr
def decode_address(self, addr): """Initialize the address from a string. Lots of different forms are supported.""" if _debug: Address._debug("decode_address %r (%s)", addr, type(addr)) # start out assuming this is a local station self.addrType = Address.localStationAddr self.ad...
Initialize the address from a string. Lots of different forms are supported.
def get_config_from_file(conf_properties_files): """Reads properties files and saves them to a config object :param conf_properties_files: comma-separated list of properties files :returns: config object """ # Initialize the config object config = ExtendedConfigParser() ...
Reads properties files and saves them to a config object :param conf_properties_files: comma-separated list of properties files :returns: config object
def write_th(self, s, header=False, indent=0, tags=None): """ Method for writting a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside...
Method for writting a formatted <th> cell. If col_space is set on the formatter then that is used for the value of min-width. Parameters ---------- s : object The data to be written inside the cell. header : boolean, default False Set to True if ...
def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self)
Run callback.
def _retrieve_session(self, session_key): """ :type session_key: SessionKey :returns: SimpleSession """ session_id = session_key.session_id if (session_id is None): msg = ("Unable to resolve session ID from SessionKey [{0}]." "Returning null...
:type session_key: SessionKey :returns: SimpleSession
def messages(self): '''a generator yielding the :class:`Message` structures in the index''' # the file contains the fixed-size file header followed by # fixed-size message structures. start after the file header and # then simply return the message structures in sequence until the ...
a generator yielding the :class:`Message` structures in the index
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a SegmentedRegressionModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. ...
Create a SegmentedRegressionModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buf...
def Barr_1981(Re, eD): r'''Calculates Darcy friction factor using the method in Barr (1981) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = -2\log\left\{\frac{\epsilon}{3.7D} + \frac{4.518\log(\frac{Re}{7})}{Re\left[1+\frac{Re^{0.52}}{29} \left(\frac{\epsilon}{D}\right)^{0.7...
r'''Calculates Darcy friction factor using the method in Barr (1981) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = -2\log\left\{\frac{\epsilon}{3.7D} + \frac{4.518\log(\frac{Re}{7})}{Re\left[1+\frac{Re^{0.52}}{29} \left(\frac{\epsilon}{D}\right)^{0.7}\right]}\right\} Para...
def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numb...
Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- ...
def do_mo(self): """ Generate mo files for all po files. """ log.debug("Start updating mo files ...") for po_dir_path in self._iter_po_dir(): po_path = (po_dir_path / self._basename).with_suffix(".po") lc_path = self._mo_path / po_dir_path.name / "LC_MESSA...
Generate mo files for all po files.
def ndfrom2d(xtr, rsi): """Undo the array shape conversion applied by :func:`ndto2d`, returning the input 2D array to its original shape. Parameters ---------- xtr : array_like Two-dimensional input array rsi : tuple A tuple containing the shape of the axis-permuted array and the ...
Undo the array shape conversion applied by :func:`ndto2d`, returning the input 2D array to its original shape. Parameters ---------- xtr : array_like Two-dimensional input array rsi : tuple A tuple containing the shape of the axis-permuted array and the permutation order applied ...
def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9]
Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.
def validated_value(self, raw_value): """Return parsed parameter value and run validation handlers. Error message included in exception will be included in http error response Args: value: raw parameter value to parse validate Returns: None Not...
Return parsed parameter value and run validation handlers. Error message included in exception will be included in http error response Args: value: raw parameter value to parse validate Returns: None Note: Concept of validation for params i...
def inject_settings(mixed: Union[str, Settings], context: MutableMapping[str, Any], fail_silently: bool = False) -> None: """Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python mo...
Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python module or dict-like instance. :param context: Context to assign settings key values. It should support dict-like item assingment. :param fail_silen...
def get_posts_with_limits(self, include_draft=False, **limits): """ Get all posts and filter them as needed. :param include_draft: return draft posts or not :param limits: other limits to the attrs of the result, should be a dict with string or list values ...
Get all posts and filter them as needed. :param include_draft: return draft posts or not :param limits: other limits to the attrs of the result, should be a dict with string or list values :return: an iterable of Post objects
def fol_fc_ask(KB, alpha): """Inefficient forward chaining for first-order logic. [Fig. 9.3] KB is a FolKB and alpha must be an atomic sentence.""" while True: new = {} for r in KB.clauses: ps, q = parse_definite_clause(standardize_variables(r)) raise NotImplementedEr...
Inefficient forward chaining for first-order logic. [Fig. 9.3] KB is a FolKB and alpha must be an atomic sentence.
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) ...
Validate the JSON against a required schema_name.
def release(): """ Release current version to pypi """ with settings(warn_only=True): r = local(clom.git['diff-files']('--quiet', '--ignore-submodules', '--')) if r.return_code != 0: abort('There are uncommitted changes, commit or stash them before releasing') version = open('...
Release current version to pypi
def _iupac_ambiguous_equal(ambig_base, unambig_base): """ Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT """ iupac_translation = { 'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', ...
Tests two bases for equality, accounting for IUPAC ambiguous DNA ambiguous base may be IUPAC ambiguous, unambiguous must be one of ACGT
def predict_epitopes_from_args(args): """ Returns an epitope collection from the given commandline arguments. Parameters ---------- args : argparse.Namespace Parsed commandline arguments for Topiary """ mhc_model = mhc_binding_predictor_from_args(args) variants = variant_collect...
Returns an epitope collection from the given commandline arguments. Parameters ---------- args : argparse.Namespace Parsed commandline arguments for Topiary
def set_h264_frm_ref_mode(self, mode=1, callback=None): ''' Set frame shipping reference mode of H264 encode stream. params: `mode`: see docstr of meth::get_h264_frm_ref_mode ''' params = {'mode': mode} return self.execute_command('setH264FrmRefMode', params, ...
Set frame shipping reference mode of H264 encode stream. params: `mode`: see docstr of meth::get_h264_frm_ref_mode
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT s.id,s.jid, s.full_ret FROM salt_returns s JOIN ( SELECT MAX(jid) AS jid FROM salt_returns GROUP BY fun, id) max ...
Return a dict of the last function called for all minions
def find_pattern_on_line(lines, n, max_wrap_lines): """ Finds a forward/reply pattern within the given lines on text on the given line number and returns a tuple with the type ('reply' or 'forward') and line number of where the pattern ends. The returned line number may be different from the given l...
Finds a forward/reply pattern within the given lines on text on the given line number and returns a tuple with the type ('reply' or 'forward') and line number of where the pattern ends. The returned line number may be different from the given line number in case the pattern wraps over multiple lines. ...
def get_nested_schema_object(self, fully_qualified_parent_name: str, nested_item_name: str) -> Optional['BaseSchema']: """ Used to generate a schema object from the given fully_qualified_parent_name and the nested_item_name. :param fully_qualified_parent_...
Used to generate a schema object from the given fully_qualified_parent_name and the nested_item_name. :param fully_qualified_parent_name: The fully qualified name of the parent. :param nested_item_name: The nested item name. :return: An initialized schema object of the nested item.
def _set_fcoe_intf_enode_bind_type(self, v, load=False): """ Setter method for fcoe_intf_enode_bind_type, mapped from YANG variable /brocade_fcoe_ext_rpc/fcoe_get_interface/output/fcoe_intf_list/fcoe_intf_enode_bind_type (fcoe-binding-type) If this variable is read-only (config: false) in the source YAN...
Setter method for fcoe_intf_enode_bind_type, mapped from YANG variable /brocade_fcoe_ext_rpc/fcoe_get_interface/output/fcoe_intf_list/fcoe_intf_enode_bind_type (fcoe-binding-type) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe_intf_enode_bind_type is considered as a privat...
def validate_blob_uri_contents(contents: bytes, blob_uri: str) -> None: """ Raises an exception if the sha1 hash of the contents does not match the hash found in te blob_uri. Formula for how git calculates the hash found here: http://alblue.bandlem.com/2011/08/git-tip-of-week-objects.html """ bl...
Raises an exception if the sha1 hash of the contents does not match the hash found in te blob_uri. Formula for how git calculates the hash found here: http://alblue.bandlem.com/2011/08/git-tip-of-week-objects.html
def modify_target(self, to_state, to_outcome=None): """Set both to_state and to_outcome at the same time to modify transition target :param str to_state: State id of the target state :param int to_outcome: Outcome id of the target port :raises exceptions.ValueError: If parameters have w...
Set both to_state and to_outcome at the same time to modify transition target :param str to_state: State id of the target state :param int to_outcome: Outcome id of the target port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid
def set_attribute_mapping(resource_attr_a, resource_attr_b, **kwargs): """ Define one resource attribute from one network as being the same as that from another network. """ user_id = kwargs.get('user_id') ra_1 = get_resource_attribute(resource_attr_a) ra_2 = get_resource_attribute(r...
Define one resource attribute from one network as being the same as that from another network.
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these ...
Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these | codes inserted. @param out_st...
def get_endpoint_descriptor(self, dev, ep, intf, alt, config): r"""Return an endpoint descriptor of the given device. The object returned is required to have all the Endpoint Descriptor fields acessible as member variables. They must be convertible (but not required to be equal) to the ...
r"""Return an endpoint descriptor of the given device. The object returned is required to have all the Endpoint Descriptor fields acessible as member variables. They must be convertible (but not required to be equal) to the int type. The ep parameter is the endpoint logical index (not ...
def trainingDataLink(data_1, data_2, common_key, training_size=50000): # pragma: nocover ''' Construct training data for consumption by the ActiveLearning markPairs method from already linked datasets. Arguments : data_1 -- Dictionary of records from first dataset, where the keys ...
Construct training data for consumption by the ActiveLearning markPairs method from already linked datasets. Arguments : data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being fie...
def css( self, filelist ): """This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.""" if isinstance( filelist, basestring ): self.link( href=filelist, rel='stylesheet', type='text/css', media='all' ) else:...
This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.
def check_token(self, respond): """ Check is the user's token is valid """ if respond.status_code == 401: self.credential.obtain_token(config=self.config) return False return True
Check is the user's token is valid
def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on study properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForStudies'.format(p=self.query_prefix) else: uri = '{p}/find_studies'.f...
Query on study properties. See documentation for _OTIWrapper class.
def html_path(builder, pagename=None): """Calculate the relative path to the Slides for pagename.""" return builder.get_relative_uri( pagename or builder.current_docname, os.path.join( builder.app.config.slide_html_relative_path, pagename or builder.current_docname, ...
Calculate the relative path to the Slides for pagename.
def copy_SRM_file(destination=None, config='DEFAULT'): """ Creates a copy of the default SRM table at the specified location. Parameters ---------- destination : str The save location for the SRM file. If no location specified, saves it as 'LAtools_[config]_SRMTable.csv' in the cur...
Creates a copy of the default SRM table at the specified location. Parameters ---------- destination : str The save location for the SRM file. If no location specified, saves it as 'LAtools_[config]_SRMTable.csv' in the current working directory. config : str It's poss...
def create_label(self, label, doc=None, callback=dummy_progress_cb): """ Create a new label Arguments: doc --- first document on which the label must be added (required for now) """ if doc: clone = doc.clone() # make sure it's seriali...
Create a new label Arguments: doc --- first document on which the label must be added (required for now)
def get_operation_full_job_id(op): """Returns the job-id or job-id.task-id for the operation.""" job_id = op.get_field('job-id') task_id = op.get_field('task-id') if task_id: return '%s.%s' % (job_id, task_id) else: return job_id
Returns the job-id or job-id.task-id for the operation.
def log_once(key): """Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement") """ global _last_logged if _disabled: ...
Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement")
def OnNodeSelected(self, event): """We have selected a node with the list control, tell the world""" try: node = self.sorted[event.GetIndex()] except IndexError, err: log.warn(_('Invalid index in node selected: %(index)s'), index=event.GetIndex()) ...
We have selected a node with the list control, tell the world
def parallel_map(func, *arg_iterable, **kwargs): """Apply function to iterable with parallel map, and hence returns results in order. functools.partial is used to freeze func_pre_args and func_kwargs, meaning that the iterable argument must be the last positional argument. Roughly equivalent to ...
Apply function to iterable with parallel map, and hence returns results in order. functools.partial is used to freeze func_pre_args and func_kwargs, meaning that the iterable argument must be the last positional argument. Roughly equivalent to >>> [func(*func_pre_args, x, **func_kwargs) for x in a...
def on_sdl_keydown ( self, event ): "press ESCAPE to quit the application" key = event.key.keysym.sym if key == SDLK_ESCAPE: self.running = False
press ESCAPE to quit the application
def folderitem(self, obj, item, index): """Augment folder listing item """ url = item.get("url") title = item.get("Title") creator = obj.Creator() item["replace"]["Title"] = get_link(url, value=title) item["created"] = self.localize_date(obj.created()) it...
Augment folder listing item
def clear(self, payload): """Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished processes. """ self.logger.rotate(self.queue) self.queue.clear() self.logger.write(self.queue) ...
Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished processes.
def get_all_items_of_credit_note(self, credit_note_id): """ Get all items of credit note This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param credit_note_id: the credit note id ...
Get all items of credit note This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param credit_note_id: the credit note id :return: list
def findAllBycolumn(self, target): """ Returns an array of columns in the region (defined by the raster), each column containing all matches in that column for the target pattern. """ column_matches = [] for column_index in range(self._raster[1]): column = self.getRow(column_...
Returns an array of columns in the region (defined by the raster), each column containing all matches in that column for the target pattern.
def enable_branching_model(self, project, repository): """ Enable branching model by setting it with default configuration :param project: :param repository: :return: """ default_model_data = {'development': {'refId': None, 'useDefault': True}, ...
Enable branching model by setting it with default configuration :param project: :param repository: :return:
def nla_put_nested(msg, attrtype, nested): """Add nested attributes to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L772 Takes the attributes found in the `nested` message and appends them to the message `msg` nested in a container of the type `attrtype`. The `nested` ...
Add nested attributes to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L772 Takes the attributes found in the `nested` message and appends them to the message `msg` nested in a container of the type `attrtype`. The `nested` message may not have a family specific header. ...
def export_html(html, filename, image_tag = None, inline = True): """ Export the contents of the ConsoleWidget as HTML. Parameters: ----------- html : str, A utf-8 encoded Python string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable...
Export the contents of the ConsoleWidget as HTML. Parameters: ----------- html : str, A utf-8 encoded Python string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_im...
def cancel_all_linking(self): """Cancel all linking""" self.logger.info("Cancel_all_linking for device %s", self.device_id) self.hub.direct_command(self.device_id, '02', '65')
Cancel all linking
def switch_from_external_to_main_wf(self): """ Main workflow switcher. This method recreates main workflow from `main wf` dict which was set by external workflow swicther previously. """ # in external assigned as True in switch_to_external_wf. # external_wf sh...
Main workflow switcher. This method recreates main workflow from `main wf` dict which was set by external workflow swicther previously.
def which(name, env_path=ENV_PATH, env_path_ext=ENV_PATHEXT, is_executable_fnc=isexec, path_join_fnc=os.path.join, os_name=os.name): ''' Get command absolute path. :param name: name of executable command :type name: str :param env_path: OS environme...
Get command absolute path. :param name: name of executable command :type name: str :param env_path: OS environment executable paths, defaults to autodetected :type env_path: list of str :param is_executable_fnc: callable will be used to detect if path is executable, de...
def fit(self, X, y): """Fit KimCNNClassifier according to X, y Parameters ---------- X : list of string each item is a raw text y : list of string each item is a label """ #################### # Data Loader ################...
Fit KimCNNClassifier according to X, y Parameters ---------- X : list of string each item is a raw text y : list of string each item is a label
def dispatch(self): """Command-line dispatch.""" parser = argparse.ArgumentParser(description='Run an Inbox server.') parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to') parser.add_argument('port', metavar='port', type=int, help='port to bind to') args...
Command-line dispatch.
def draw(self): """ Draw the elbow curve for the specified scores and values of K. """ # Plot the silhouette score against k self.ax.plot(self.k_values_, self.k_scores_, marker="D") if self.locate_elbow and self.elbow_value_!=None: elbow_label = "$elbow\ at\ k...
Draw the elbow curve for the specified scores and values of K.
def print(*a): """ print just one that returns what you give it instead of None """ try: _print(*a) return a[0] if len(a) == 1 else a except: _print(*a)
print just one that returns what you give it instead of None
def _get (self, timeout): """Non thread-safe utility function of self.get() doing the real work.""" if timeout is None: while self._empty(): self.not_empty.wait() else: if timeout < 0: raise ValueError("'timeout' must be a positive ...
Non thread-safe utility function of self.get() doing the real work.
def snapshot(self, name): """ Create a snapshot of the volume. Args: name: string - a human-readable name for the snapshot """ return self.get_data( "volumes/%s/snapshots/" % self.id, type=POST, params={"name": name} )
Create a snapshot of the volume. Args: name: string - a human-readable name for the snapshot
def cmp(self, other): """*Note: checks Range.start() only* Key: self = [], other = {} * [ {----]----} => -1 * {---[---} ] => 1 * [---] {---} => -1 * [---] same as {---} => 0 * [--{-}--] => -1 """ if isinstance(other, Range):...
*Note: checks Range.start() only* Key: self = [], other = {} * [ {----]----} => -1 * {---[---} ] => 1 * [---] {---} => -1 * [---] same as {---} => 0 * [--{-}--] => -1
def cli(wio, send): ''' Sends a UDP command to the wio device. \b DOES: Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0" "APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n", Note: 1. Ensure your device is Configure Mode. ...
Sends a UDP command to the wio device. \b DOES: Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0" "APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n", Note: 1. Ensure your device is Configure Mode. 2. Change your computer n...
def code(self): """ Removes duplicates values in auto and error list. parameters. """ def uniq(seq): """ Utility function that removes duplicate. """ seen = set() seen_add = seen.add # This way removes dupli...
Removes duplicates values in auto and error list. parameters.
def get_name(self, tag): '''Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its...
Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in the name b...
def keep_negative_mask(X, y, model_generator, method_name, num_fcounts=11): """ Keep Negative (mask) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 5 """ return __run_measure(measures.keep_mask, X, y, model_generator, method_n...
Keep Negative (mask) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 5
def query_cached_package_list(self): """Return list of pickled package names from PYPI""" if self.debug: self.logger.debug("DEBUG: reading pickled cache file") return cPickle.load(open(self.pkg_cache_file, "r"))
Return list of pickled package names from PYPI
def check_parallel_run(self): # pragma: no cover, not with unit tests... """Check (in pid file) if there isn't already a daemon running. If yes and do_replace: kill it. Keep in self.fpid the File object to the pid file. Will be used by writepid. :return: None """ # TODO...
Check (in pid file) if there isn't already a daemon running. If yes and do_replace: kill it. Keep in self.fpid the File object to the pid file. Will be used by writepid. :return: None
def size(ctx, dataset, kwargs): "Show dataset size" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)
Show dataset size
def all(self): """ Return all testcases :return: """ tests = list() for testclass in self.classes: tests.extend(self.classes[testclass].cases) return tests
Return all testcases :return:
def _build_zmat(self, construction_table): """Create the Zmatrix from a construction table. Args: Construction table (pd.DataFrame): Returns: Zmat: A new instance of :class:`Zmat`. """ c_table = construction_table default_cols = ['atom', 'b', 'bo...
Create the Zmatrix from a construction table. Args: Construction table (pd.DataFrame): Returns: Zmat: A new instance of :class:`Zmat`.
def fetch(self, **kwargs) -> 'FetchContextManager': ''' Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.bac...
Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.backend.client.request import Request from ai.backend.client.sess...
def get_geo_info(filename, band=1): ''' Gets information from a Raster data set ''' sourceds = gdal.Open(filename, GA_ReadOnly) ndv = sourceds.GetRasterBand(band).GetNoDataValue() xsize = sourceds.RasterXSize ysize = sourceds.RasterYSize geot = sourceds.GetGeoTransform() projection = osr...
Gets information from a Raster data set
def face_adjacency_radius(self): """ The approximate radius of a cylinder that fits inside adjacent faces. Returns ------------ radii : (len(self.face_adjacency),) float Approximate radius formed by triangle pair """ radii, span = graph.face_adjacency_r...
The approximate radius of a cylinder that fits inside adjacent faces. Returns ------------ radii : (len(self.face_adjacency),) float Approximate radius formed by triangle pair
def sibling(self, offs=1): ''' Return sibling node by relative offset from self. ''' indx = self.pindex + offs if indx < 0: return None if indx >= len(self.parent.kids): return None return self.parent.kids[indx]
Return sibling node by relative offset from self.
def image( self, url, title="", width=800): """*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* ...
*create MMD image link* **Key Arguments:** - ``title`` -- the title for the image - ``url`` -- the image URL - ``width`` -- the width in pixels of the image. Default *800* **Return:** - ``imageLink`` -- the MMD image link **Usage:** ...
def create_identity(user_id, curve_name): """Create GPG identity for hardware device.""" result = interface.Identity(identity_str='gpg://', curve_name=curve_name) result.identity_dict['host'] = user_id return result
Create GPG identity for hardware device.
def compare_mean_curves(calc_ref, calc, nsigma=3): """ Compare the hazard curves coming from two different calculations. """ dstore_ref = datastore.read(calc_ref) dstore = datastore.read(calc) imtls = dstore_ref['oqparam'].imtls if dstore['oqparam'].imtls != imtls: raise RuntimeError...
Compare the hazard curves coming from two different calculations.
def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A response PDU. """ _, address, value = struct.unpack('>BHH', pdu) value = 1 if value == 0xFF00 else value instance = WriteSingleCoil() instance.address = address instan...
Create instance from request PDU. :param pdu: A response PDU.
def execute_wait(self, cmd, walltime=2, envs={}): ''' Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds Kwargs: - envs (dict) : Dictionary of env variables ...
Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds Kwargs: - envs (dict) : Dictionary of env variables Returns: - retcode : Return code from the ex...
def stop_sync(self): """Safely stop this BLED112 instance without leaving it in a weird state""" # Stop to scan if self.scanning: self.stop_scan() # Disconnect all connected devices for connection_id in list(self.connections.get_connections()): self.disco...
Safely stop this BLED112 instance without leaving it in a weird state
def personByEmailAddress(self, address): """ Retrieve the L{Person} item for the given email address (or return None if no such person exists) @type name: C{unicode} """ email = self.store.findUnique(EmailAddress, EmailAddress.addres...
Retrieve the L{Person} item for the given email address (or return None if no such person exists) @type name: C{unicode}
async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None: """ Format a command and send it to the server. """ if self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") self._stream_writer.write(data) async with...
Format a command and send it to the server.
def get_requests_request_name(self, request_name): """GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>` """ query_parameters = {} if request_nam...
GetRequestsRequestName. [Preview API] Get a symbol request by request name. :param str request_name: :rtype: :class:`<Request> <azure.devops.v5_0.symbol.models.Request>`
def logSumExp(A, B, out=None): """ returns log(exp(A) + exp(B)). A and B are numpy arrays""" if out is None: out = numpy.zeros(A.shape) indicator1 = A >= B indicator2 = numpy.logical_not(indicator1) out[indicator1] = A[indicator1] + numpy.log1p(numpy.exp(B[indicator1]-A[indicator1])) out[indicator2] ...
returns log(exp(A) + exp(B)). A and B are numpy arrays
def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a bytes field.""" local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) ...
Returns a decoder for a bytes field.
def graph_query(kind, source, target=None, neighbor_limit=1, database_filter=None): """Perform a graph query on PathwayCommons. For more information on these queries, see http://www.pathwaycommons.org/pc2/#graph Parameters ---------- kind : str The kind of graph query t...
Perform a graph query on PathwayCommons. For more information on these queries, see http://www.pathwaycommons.org/pc2/#graph Parameters ---------- kind : str The kind of graph query to perform. Currently 3 options are implemented, 'neighborhood', 'pathsbetween' and 'pathsfromto'. ...
def add_parameter(self, name, value, meta=None): """Add a parameter to the parameter list. :param name: New parameter's name. :type name: str :param value: New parameter's value. :type value: float :param meta: New parameter's meta property. :type meta: dict ...
Add a parameter to the parameter list. :param name: New parameter's name. :type name: str :param value: New parameter's value. :type value: float :param meta: New parameter's meta property. :type meta: dict
def open_file(self, info): """ Handles the open action. """ if not info.initialized: return # Escape. # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "open", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" ...
Handles the open action.
def _connect(self, database=None): """ Connect to given database """ conn_args = { 'host': self.config['host'], 'user': self.config['user'], 'password': self.config['password'], 'port': self.config['port'], 'sslmode': self.confi...
Connect to given database
def insert_before(self, text): """ Create a new document, with this text inserted before the buffer. It keeps selection ranges and cursor position in sync. """ selection_state = self.selection if selection_state: selection_state = SelectionState( ...
Create a new document, with this text inserted before the buffer. It keeps selection ranges and cursor position in sync.
def trigger_event(self, event, client, args, force_dispatch=False): """Trigger a new event that will be dispatched to all modules.""" self.controller.process_event(event, client, args, force_dispatch=force_dispatch)
Trigger a new event that will be dispatched to all modules.
def rand_bytes(length): """ Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type ...
Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is retu...
def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users pas...
NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data
def clear(self): """ Clear the cache. """ not_removed = [] for fn in os.listdir(self.base): fn = os.path.join(self.base, fn) try: if os.path.islink(fn) or os.path.isfile(fn): os.remove(fn) elif os.path.is...
Clear the cache.
def store_drop(cls, resource: str, session: Optional[Session] = None) -> 'Action': """Store a "drop" event. :param resource: The normalized name of the resource to store Example: >>> from bio2bel.models import Action >>> Action.store_drop('hgnc') """ action = c...
Store a "drop" event. :param resource: The normalized name of the resource to store Example: >>> from bio2bel.models import Action >>> Action.store_drop('hgnc')