code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _iterate_fields_cond(self, pkt, val, use_val): """Internal function used by _find_fld_pkt & _find_fld_pkt_val""" # Iterate through the fields for fld, cond in self.flds: if isinstance(cond, tuple): if use_val: if cond[1](pkt, val): ...
Internal function used by _find_fld_pkt & _find_fld_pkt_val
def step_command_output_should_not_contain_log_records_from_categories(context): """ Verifies that the command output contains not log records from the provided log categories (in any order). .. code-block: gherkin Given I define the log record schema: | category | level | message ...
Verifies that the command output contains not log records from the provided log categories (in any order). .. code-block: gherkin Given I define the log record schema: | category | level | message | | root | ERROR | __LOG_MESSAGE__ | Then the command output should n...
def get_assignments_by_sis_course_id(self, sis_course_id): """ Returns assignment data for the given course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_assignments """ url = "/api/v1/courses/%s/analytics/assignments.json" % ( ...
Returns assignment data for the given course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_assignments
def change_bgcolor_enable(self, state): """ This is implementet so column min/max is only active when bgcolor is """ self.dataModel.bgcolor(state) self.bgcolor_global.setEnabled(not self.is_series and state > 0)
This is implementet so column min/max is only active when bgcolor is
def is_valid_callsign(self, callsign, timestamp=timestamp_now): """ Checks if a callsign is valid Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True / False Example: ...
Checks if a callsign is valid Args: callsign (str): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True / False Example: The following checks if "DH1TW" is a valid callsign >>...
def _ending_consonants_only(self, letters: List[str]) -> List[int]: """Return a list of positions for ending consonants.""" reversed_letters = list(reversed(letters)) length = len(letters) for idx, letter in enumerate(reversed_letters): if not self._contains_vowels(letter) an...
Return a list of positions for ending consonants.
def is_active(self): """ Returns True if the logical volume is active, False otherwise. """ self.open() active = lvm_lv_is_active(self.__lvh) self.close() return bool(active)
Returns True if the logical volume is active, False otherwise.
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for messages from '%s' sinc...
Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
def auto_delete_files_on_instance_change( instance: Any, fieldnames: Iterable[str], model_class) -> None: """ Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s. """ if not instance.pk: ...
Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s.
def resync(self): """make sure we can ping the head and assigned node. Possibly after an env.exit()""" success = 0 for head in [True, False]: for _ in range(30): try: self.status(head) success += 1 br...
make sure we can ping the head and assigned node. Possibly after an env.exit()
def _initialize(self): """Initialize transfer.""" payload = { 'apikey': self.session.cookies.get('apikey'), 'source': self.session.cookies.get('source') } if self.fm_user.logged_in: payload['logintoken'] = self.session.cookies.get('logintoken') ...
Initialize transfer.
def show(self): '''Display menus and connect even signals.''' self.parent.addLayout(self._logSelectLayout) self.menuCount += 1 self._connectSlots()
Display menus and connect even signals.
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process.
def parse_series(s): """ Parses things like '1n+2', or 'an+b' generally, returning (a, b) """ if isinstance(s, Element): s = s._format_element() if not s or s == '*': # Happens when there's nothing, which the CSS parser thinks of as * return (0, 0) if isinstance(s, int): ...
Parses things like '1n+2', or 'an+b' generally, returning (a, b)
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn): """ Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. ...
Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. OffsetFetchRequest), all payloads must be for a single group. Arguments: group...
def load_json(path, quiet=False, cli=False): """ Load a json serialized object and ensure it matches to the current Assembly object format """ ## load the JSON string and try with name+.json checkfor = [path+".json", path] for inpath in checkfor: inpath = inpath.replace("~", os.p...
Load a json serialized object and ensure it matches to the current Assembly object format
def heatmap(adata, var_names, groups=None, groupby=None, annotations=None, use_raw=False, layers=['X'], color_map=None, color_map_anno=None, colorbar=True, row_width=None, xlabel=None, title=None, figsize=None, dpi=None, show=True, save=None, ax=None, **kwargs): """\ Plot pseudotimeseri...
\ Plot pseudotimeseries for genes as heatmap. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. var_names: `str`, list of `str` Names of variables to use for the plot. groups: `str`, list of `str` or `None` (default: `None`) Groups selected to...
def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): """Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd...
Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param b...
def linearize_data_types(self): # type: () -> typing.List[UserDefined] """ Returns a list of all data types used in the namespace. Because the inheritance of data types can be modeled as a DAG, the list will be a linearization of the DAG. It's ideal to generate data types in this...
Returns a list of all data types used in the namespace. Because the inheritance of data types can be modeled as a DAG, the list will be a linearization of the DAG. It's ideal to generate data types in this order so that composite types that reference other composite types are defined in ...
def _create(self): """Creates a new and empty database.""" from .tools import makedirs_safe # create directory for sql database makedirs_safe(os.path.dirname(self._database)) # create all the tables Base.metadata.create_all(self._engine) logger.debug("Created new empty database '%s'" % sel...
Creates a new and empty database.
def no(self, text, count=None): """ If count is 0, no, zero or nil, return 'no' followed by the plural of text. If count is one of: 1, a, an, one, each, every, this, that return count followed by text. Otherwise return count follow by the plural of text. ...
If count is 0, no, zero or nil, return 'no' followed by the plural of text. If count is one of: 1, a, an, one, each, every, this, that return count followed by text. Otherwise return count follow by the plural of text. In the return value count is always followed b...
def is_file(cls, file): '''Return whether the file is likely to be HTML.''' peeked_data = wpull.string.printable_bytes( wpull.util.peek_file(file)).lower() if b'<!doctype html' in peeked_data \ or b'<head' in peeked_data \ or b'<title' in peeked_data \ ...
Return whether the file is likely to be HTML.
def get_parent(self, level=1): ''' get parent dir as a `DirectoryInfo`. return `None` if self is top. ''' try: parent_path = self.path.get_parent(level) except ValueError: # abspath cannot get parent return None assert parent_path ...
get parent dir as a `DirectoryInfo`. return `None` if self is top.
def list(self): """List Reserved Capacities""" mask = """mask[availableInstanceCount, occupiedInstanceCount, instances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]""" results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) ...
List Reserved Capacities
def get_arthur_params_from_url(cls, url): """ Get the arthur params given a URL for the data source """ params = {} args = cls.get_perceval_params_from_url(url) parser = GitLabCommand.setup_cmd_parser() parsed_args = parser.parse(*args) params['owner'] = parsed_args.ow...
Get the arthur params given a URL for the data source
def get_triplets_at_q(grid_point, mesh, point_group, # real space point group of space group reciprocal_lattice, # column vectors is_time_reversal=True, swappable=True, stores_triplets_m...
Parameters ---------- grid_point : int A grid point mesh : array_like Mesh numbers dtype='intc' shape=(3,) point_group : array_like Rotation matrices in real space. Note that those in reciprocal space mean these matrices transposed (local terminology). ...
def filter(self, chamber, congress=CURRENT_CONGRESS, **kwargs): """ Takes a chamber and Congress, OR state and district, returning a list of members """ check_chamber(chamber) kwargs.update(chamber=chamber, congress=congress) if 'state' in kwargs and 'district' ...
Takes a chamber and Congress, OR state and district, returning a list of members
def is_older_than_metadata(self): """ Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns False if the time of either can't be determined :param path: Optional extra save path, used in save_path() """ try: ...
Return True if the package save file is older than the metadata. If it is, it should be rebuilt. Returns False if the time of either can't be determined :param path: Optional extra save path, used in save_path()
def mcc(x, axis=0, autocorrect=False): """Matthews correlation Parameters ---------- x : ndarray dataset of binary [0,1] values axis : int, optional Variables as columns is the default (axis=0). If variables are in the rows use axis=1 autocorrect : bool, optional ...
Matthews correlation Parameters ---------- x : ndarray dataset of binary [0,1] values axis : int, optional Variables as columns is the default (axis=0). If variables are in the rows use axis=1 autocorrect : bool, optional If all predictions are True or all are Fals...
def filter_device_by_class(vid, pid, device_class): """! @brief Test whether the device should be ignored by comparing bDeviceClass. This function checks the device's bDeviceClass to determine whether the it is likely to be a CMSIS-DAP device. It uses the vid and pid for device-specific quirks. ...
! @brief Test whether the device should be ignored by comparing bDeviceClass. This function checks the device's bDeviceClass to determine whether the it is likely to be a CMSIS-DAP device. It uses the vid and pid for device-specific quirks. @retval True Skip the device. @retval False The devic...
def svg_data_uri(self, xmldecl=False, encode_minimal=False, omit_charset=False, nl=False, **kw): """\ Converts the QR Code into a SVG data URI. The XML declaration is omitted by default (set ``xmldecl`` to ``True`` to enable it), further the newline is omitted by de...
\ Converts the QR Code into a SVG data URI. The XML declaration is omitted by default (set ``xmldecl`` to ``True`` to enable it), further the newline is omitted by default (set ``nl`` to ``True`` to enable it). Aside from the missing ``out`` parameter and the different ``xmldec...
def load(cls, sc, path): """ Load a model from the given path. """ model = cls._load_java(sc, path) wrapper =\ sc._jvm.org.apache.spark.mllib.api.python.PowerIterationClusteringModelWrapper(model) return PowerIterationClusteringModel(wrapper)
Load a model from the given path.
def _parse_table_name(self, table_id): """Parse a table name in the form of appid_YYYY_MM or YYYY_MM_appid and return a tuple consisting of YYYY-MM and the app id. Returns (None, None) in the event of a name like <desc>_YYYYMMDD_<int> Parameters ---------- table_id : st...
Parse a table name in the form of appid_YYYY_MM or YYYY_MM_appid and return a tuple consisting of YYYY-MM and the app id. Returns (None, None) in the event of a name like <desc>_YYYYMMDD_<int> Parameters ---------- table_id : str The table id as listed by BigQuery ...
def newline(self): """Write eol, then start new line.""" self.write_str(self.eol) self.room = self.maxlinelen
Write eol, then start new line.
def iter_followers(self, login=None, number=-1, etag=None): """If login is provided, iterate over a generator of followers of that login name; otherwise return a generator of followers of the authenticated user. :param str login: (optional), login of the user to check :param int...
If login is provided, iterate over a generator of followers of that login name; otherwise return a generator of followers of the authenticated user. :param str login: (optional), login of the user to check :param int number: (optional), number of followers to return. Default: ...
def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None): """ Retrieves OAuth 2.0 access token using the given grant type. Args: url (str): Oauth2 access token endpoint client_id (str): client ID ...
Retrieves OAuth 2.0 access token using the given grant type. Args: url (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret Kwargs: token_type (str): Type of token to return. Options include bearer and jwt. grant_type (str): O...
def commit(self, message=None, amend=False, stage=True): """Commit any changes, optionally staging all changes beforehand.""" return git_commit(self.repo_dir, message=message, amend=amend, stage=stage)
Commit any changes, optionally staging all changes beforehand.
def cli(env, keyword, package_type): """List packages that can be ordered via the placeOrder API. :: # List out all packages for ordering slcli order package-list # List out all packages with "server" in the name slcli order package-list --keyword server # Select onl...
List packages that can be ordered via the placeOrder API. :: # List out all packages for ordering slcli order package-list # List out all packages with "server" in the name slcli order package-list --keyword server # Select only specifict package types slcli orde...
def objects(self, cls=None): """ Return an iterater over all objects in this directory which are instances of `cls`. By default, iterate over all objects (`cls=None`). Parameters ---------- cls : a class, optional (default=None) If a class is specified, only...
Return an iterater over all objects in this directory which are instances of `cls`. By default, iterate over all objects (`cls=None`). Parameters ---------- cls : a class, optional (default=None) If a class is specified, only iterate over objects that are instan...
def _keys_to_camel_case(self, obj): """ Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary. :param obj: Dictionary to convert keys to camel case. :return: Dictionary with ...
Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary. :param obj: Dictionary to convert keys to camel case. :return: Dictionary with the input values and all keys in camel case
def dispatch(self, method, url, auth=None, params=None, **kwargs): """ Send HTTP request, with given method, credentials and data to the given URL, and return the success and the result on success. """ r = Request( method=method, url=url, ...
Send HTTP request, with given method, credentials and data to the given URL, and return the success and the result on success.
def ppo_atari_base(): """Pong base parameters.""" hparams = ppo_discrete_action_base() hparams.learning_rate_constant = 1e-4 hparams.epoch_length = 200 hparams.gae_gamma = 0.985 hparams.gae_lambda = 0.985 hparams.entropy_loss_coef = 0.003 hparams.value_loss_coef = 1 hparams.optimization_epochs = 3 h...
Pong base parameters.
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variab...
Get The Text Between Two Parts
def _kernel(kernel_spec): """Expands the kernel spec into a length 2 list. Args: kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a list. Returns: A length 2 list. """ if isinstance(kernel_spec, tf.compat.integral_types): return [kernel_spec, kernel_spec] elif len(k...
Expands the kernel spec into a length 2 list. Args: kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a list. Returns: A length 2 list.
def create_question(self, question, type=None, **kwargs): """ Returns a Question of specified type. """ if not type: return Question(question, **kwargs) if type == "choice": return ChoiceQuestion(question, **kwargs) if type == "confirmation": ...
Returns a Question of specified type.
def moveToXY(self, vehID, edgeID, lane, x, y, angle=tc.INVALID_DOUBLE_VALUE, keepRoute=1): '''Place vehicle at the given x,y coordinates and force it's angle to the given value (for drawing). If the angle is set to INVALID_DOUBLE_VALUE, the vehicle assumes the natural angle of the edge o...
Place vehicle at the given x,y coordinates and force it's angle to the given value (for drawing). If the angle is set to INVALID_DOUBLE_VALUE, the vehicle assumes the natural angle of the edge on which it is driving. If keepRoute is set to 1, the closest position within the exist...
def write(*args): """Like print(), but recognizes tensors and arrays and show more details about them. Example: hl.write("My Tensor", my_tensor) Prints: My Tensor float32 (10, 3, 224, 224) min: 0.0 max: 1.0 """ s = "" for a in args: # Convert tensors ...
Like print(), but recognizes tensors and arrays and show more details about them. Example: hl.write("My Tensor", my_tensor) Prints: My Tensor float32 (10, 3, 224, 224) min: 0.0 max: 1.0
def clear(self, asset_manager_id, book_ids=None): """ This method deletes all the data for an asset_manager_id and option book_ids. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete. """ self.logger.info...
This method deletes all the data for an asset_manager_id and option book_ids. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete.
def pick_key(keys, use, alg='', key_type='', kid=''): """ Based on given criteria pick out the keys that fulfill them from a given set of keys. :param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK` instances. :param use: What the key is going to be used for 'sig'/'enc' :par...
Based on given criteria pick out the keys that fulfill them from a given set of keys. :param keys: List of keys. These are :py:class:`cryptojwt.jwk.JWK` instances. :param use: What the key is going to be used for 'sig'/'enc' :param alg: crypto algorithm :param key_type: Type of key 'rsa'/'e...
def select(self, Class, set=None, recursive=True, ignore=True, node=None): """See :meth:`AbstractElement.select`""" if self.include: return self.subdoc.data[0].select(Class,set,recursive, ignore, node) #pass it on to the text node of the subdoc else: return iter([])
See :meth:`AbstractElement.select`
def dict_filter_nones(dict_): r""" Removes None values Args: dict_ (dict): a dictionary Returns: dict: CommandLine: python -m utool.util_dict --exec-dict_filter_nones Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # fails on python ...
r""" Removes None values Args: dict_ (dict): a dictionary Returns: dict: CommandLine: python -m utool.util_dict --exec-dict_filter_nones Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> # fails on python 3 because of dict None order ...
def realtime_observations(cls, buoy, data_type='txt'): """Retrieve the realtime buoy data from NDBC. Parameters ---------- buoy : str Name of buoy data_type : str Type of data requested, must be one of 'txt' standard meteorological data ...
Retrieve the realtime buoy data from NDBC. Parameters ---------- buoy : str Name of buoy data_type : str Type of data requested, must be one of 'txt' standard meteorological data 'drift' meteorological data from drifting buoys and limited ...
def get_ips(self, instance_id): """Retrieves the ip addresses (public) from the cloud provider by the given instance id. :param str instance_id: id of the instance :return: list (ips) :raises: InstanceError if the ip could not be retrieved. """ if not instance_id...
Retrieves the ip addresses (public) from the cloud provider by the given instance id. :param str instance_id: id of the instance :return: list (ips) :raises: InstanceError if the ip could not be retrieved.
def isRef(self, doc, attr): """Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase). """ if doc is None: doc__o = None else: doc__o = doc._o if attr is None: attr__o = ...
Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase).
def _ReadStructureFromFileObject( self, file_object, file_offset, data_type_map): """Reads a structure from a file-like object. If the data type map has a fixed size this method will read the predefined number of bytes from the file-like object. If the data type map has a variable size, depending...
Reads a structure from a file-like object. If the data type map has a fixed size this method will read the predefined number of bytes from the file-like object. If the data type map has a variable size, depending on values in the byte stream, this method will continue to read from the file-like object ...
async def async_oauth_dance(consumer_key, consumer_secret, callback_uri="oob"): """ OAuth dance to get the user's access token Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret callback_uri : str Callback uri, d...
OAuth dance to get the user's access token Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret callback_uri : str Callback uri, defaults to 'oob' Returns ------- dict Access tokens
def _make_pcaps(self): ''' Internal method. Create libpcap devices for every network interface we care about and set them in non-blocking mode. ''' self._pcaps = {} for devname,intf in self._devinfo.items(): if intf.iftype == InterfaceType.Loopback: ...
Internal method. Create libpcap devices for every network interface we care about and set them in non-blocking mode.
def get_buffer(self, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ return self.io.get_buffer(self._get_data(), self.get_header(), format, output=output)
Get image as a buffer in (format). Format should be 'jpeg', 'png', etc.
def save_existing(self, form, instance, commit=True): """ NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object """ self._prepare_multilingual_object(instance, form) retu...
NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object
def check_response(self, resp): """ Checks response after request was made. Checks status of the response, mainly :param resp: :return: """ # For successful API call, response code will be 200 (OK) if resp.ok: json = resp.json() s...
Checks response after request was made. Checks status of the response, mainly :param resp: :return:
def _configure_formatting(self): ''' Configures output formatting, and fitting output to the current terminal width. Returns None. ''' self.format_strings(self.DEFAULT_FORMAT, self.DEFAULT_FORMAT) if self.fit_to_screen: try: import fcntl ...
Configures output formatting, and fitting output to the current terminal width. Returns None.
def graph(self, fnm=None, size=None, fntsz=None, fntfm=None, clrgen=None, rmsz=False, prog='dot'): """ Construct call graph Parameters ---------- fnm : None or string, optional (default None) Filename of graph file to be written. File type is determined b...
Construct call graph Parameters ---------- fnm : None or string, optional (default None) Filename of graph file to be written. File type is determined by the file extentions (e.g. dot for 'graph.dot' and SVG for 'graph.svg'). If None, a file is not written. ...
def process(self, document): """Logging versions of required tools.""" content = json.dumps(document) versions = {} versions.update({'Spline': Version(VERSION)}) versions.update(self.get_version("Bash", self.BASH_VERSION)) if content.find('"docker(container)":') >= 0 or...
Logging versions of required tools.
def _dbdir(): """Returns the path to the directory where acorn DBs are stored. """ global dbdir from os import mkdir, path, getcwd, chdir if dbdir is None: from acorn.config import settings config = settings("acorn") if (config.has_section("database") and con...
Returns the path to the directory where acorn DBs are stored.
def open(self, file, mode='r', perm=0o0644): """ Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write ...
Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write 'x' create if not exist 'a' append :return: a...
def _post_process_yaml_data(self, fixture_data: Dict[str, Dict[str, Any]], relationship_columns: Set[str], ) -> Tuple[Dict[str, Dict[str, Any]], List[str]]: """ Convert and normalize identifier strings to Ide...
Convert and normalize identifier strings to Identifiers, as well as determine class relationships.
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readui...
Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
def _bond_percolation(network, tmask): r""" This private method is called by 'find_clusters' """ # Perform the clustering using scipy.csgraph csr = network.create_adjacency_matrix(weights=tmask, fmt='csr', drop_zeros=True) clusters = sprs.csgraph.connect...
r""" This private method is called by 'find_clusters'
def _subdivide_nodes(nodes): """Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will...
Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Ar...
def magic_memit(self, line=''): """Measure memory usage of a Python statement Usage, in line mode: %memit [-ir<R>t<T>] statement Options: -r<R>: repeat the loop iteration <R> times and take the best result. Default: 1 -i: run the code in the current environment, without forking a new pr...
Measure memory usage of a Python statement Usage, in line mode: %memit [-ir<R>t<T>] statement Options: -r<R>: repeat the loop iteration <R> times and take the best result. Default: 1 -i: run the code in the current environment, without forking a new process. This is required on some Mac...
def get_values(): """ Get dictionary of values from the backend :return: """ # First load a mapping between config name and default value default_initial = ((name, options[0]) for name, options in settings.CONFIG.items()) # Then update the mapping with actually values...
Get dictionary of values from the backend :return:
def disable_digital_reporting(self, pin): """ Disables digital reporting. By turning reporting off for this pin, reporting is disabled for all 8 bits in the "port" - :param pin: Pin and all pins for this port :return: No return value """ port = pin // 8 ...
Disables digital reporting. By turning reporting off for this pin, reporting is disabled for all 8 bits in the "port" - :param pin: Pin and all pins for this port :return: No return value
def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): """Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to ...
Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. Parameters: - baseExpr - expression representing...
def inner(self, x1, x2): """Return the inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `LinearSpaceElement` Elements whose inner product to compute. Returns ------- inner : `LinearSpace.field` element Inner product of `...
Return the inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `LinearSpaceElement` Elements whose inner product to compute. Returns ------- inner : `LinearSpace.field` element Inner product of ``x1`` and ``x2``.
def delete(self, removealien=True): """Delete the current entity. This will also call :meth:`RefobjInterface.get_children_to_delete` and delete these children first by calling :meth:`Reftrack.delete`. To delete the content it will call :meth:`RefobjInterface.delete`. Then the re...
Delete the current entity. This will also call :meth:`RefobjInterface.get_children_to_delete` and delete these children first by calling :meth:`Reftrack.delete`. To delete the content it will call :meth:`RefobjInterface.delete`. Then the refobject will be set to None. If the :class:`Ref...
def reduce_tree(node, parent=None): """ Internal function. Reduces a compiled pattern tree to an intermediate representation suitable for feeding the automaton. This also trims off any optional pattern elements(like [a], a*). """ new_node = None #switch on the node type if node.type...
Internal function. Reduces a compiled pattern tree to an intermediate representation suitable for feeding the automaton. This also trims off any optional pattern elements(like [a], a*).
def add(self, resource, replace=False): """Add just a single resource.""" uri = resource.uri if (uri in self and not replace): raise ResourceSetDupeError( "Attempt to add resource already in this set") self[uri] = resource
Add just a single resource.
def difference(self, second_iterable, selector=identity): '''Returns those elements which are in the source sequence which are not in the second_iterable. This method is equivalent to the Except() LINQ operator, renamed to a valid Python identifier. Note: This method uses defer...
Returns those elements which are in the source sequence which are not in the second_iterable. This method is equivalent to the Except() LINQ operator, renamed to a valid Python identifier. Note: This method uses deferred execution, but as soon as execution commences the ent...
def _register_update(self, fmt={}, replot=False, force=False, todefault=False): """ Register formatoptions for the update Parameters ---------- fmt: dict Keys can be any valid formatoptions with the corresponding values (see the :...
Register formatoptions for the update Parameters ---------- fmt: dict Keys can be any valid formatoptions with the corresponding values (see the :attr:`formatoptions` attribute) replot: bool Boolean that determines whether the data specific formatopti...
def listItem(node): """ An item in a list """ o = nodes.list_item() for n in MarkDown(node): o += n return o
An item in a list
def chunks(self): """Block dimensions for this dataset's data or None if it's not a dask array. """ chunks = {} for v in self.variables.values(): if v.chunks is not None: for dim, c in zip(v.dims, v.chunks): if dim in chunks and c !...
Block dimensions for this dataset's data or None if it's not a dask array.
def update(self, eid, data, token): """ Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception """ final_dict = {"data": {"id": eid, ...
Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception
def _setup_time_axis(self, t_start=None, t_stop=None): """ Setup time axis. """ # now check to see how many integrations requested ii_start, ii_stop = 0, self.n_ints_in_file if t_start: ii_start = t_start if t_stop: ii_stop = t_stop n_ints = ii_s...
Setup time axis.
def _get_windows_console_width() -> int: """ A small utility function for getting the current console window's width, in Windows. :return: The current console window's width. """ from ctypes import byref, windll import pyreadline out = windll.kernel32.GetStdHandle(-11) info = pyreadlin...
A small utility function for getting the current console window's width, in Windows. :return: The current console window's width.
def get_instance(self, payload): """ Build an instance of UsageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.UsageInstance :rtype: twilio.rest.api.v2010.account.usage.UsageInstance """ return UsageInsta...
Build an instance of UsageInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.UsageInstance :rtype: twilio.rest.api.v2010.account.usage.UsageInstance
def list_price(self): """List Price. :return: A tuple containing: 1. Float representation of price. 2. ISO Currency code (string). """ price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount') currency = self._safe_get_el...
List Price. :return: A tuple containing: 1. Float representation of price. 2. ISO Currency code (string).
def get_host(self): """ Gets the host name or IP address. :return: the host name or IP address. """ host = self.get_as_nullable_string("host") host = host if host != None else self.get_as_nullable_string("ip") return host
Gets the host name or IP address. :return: the host name or IP address.
def ndim(n, *args, **kwargs): """ Makes a multi-dimensional array of random floats. (Replaces RandomArray). """ thunk = kwargs.get("thunk", lambda: random.random()) if not args: return [thunk() for i in range(n)] A = [] for i in range(n): A.append( ndim(*args, thunk=thunk) ...
Makes a multi-dimensional array of random floats. (Replaces RandomArray).
def open_resource(name): """Open a resource from the zoneinfo subdir for reading. Uses the pkg_resources module if available and no standard file found at the calculated location. """ name_parts = name.lstrip('/').split('/') for part in name_parts: if part == os.path.pardir or os.path.s...
Open a resource from the zoneinfo subdir for reading. Uses the pkg_resources module if available and no standard file found at the calculated location.
def _init_data_with_tdms(self, tdms_filename): """Initializes the current RT-DC dataset with a tdms file. """ tdms_file = TdmsFile(str(tdms_filename)) # time is always there table = "Cell Track" # Edit naming.dclab2tdms to add features for arg in naming.tdms2dclab...
Initializes the current RT-DC dataset with a tdms file.
def _piped_bamprep_region_gatk(data, region, prep_params, out_file, tmp_dir): """Perform semi-piped BAM preparation using Picard/GATK tools. """ broad_runner = broad.runner_from_config(data["config"]) cur_bam, cl = _piped_input_cl(data, region, tmp_dir, out_file, prep_params) if not prep_params["rea...
Perform semi-piped BAM preparation using Picard/GATK tools.
def cluster_uniform_time(data=None, k=None, stride=1, metric='euclidean', n_jobs=None, chunksize=None, skip=0, **kwargs): r"""Uniform time clustering If given data, performs a clustering that selects data points uniformly in time and then assigns the data using a Voronoi discretiza...
r"""Uniform time clustering If given data, performs a clustering that selects data points uniformly in time and then assigns the data using a Voronoi discretization. Returns a :class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` object that can be used to extract the dis...
def except_keyword(source, start, keyword): """ Returns position after keyword if found else None Note: skips white space""" start = pass_white(source, start) kl = len(keyword) #keyword len if kl + start > len(source): return None if source[start:start + kl] != keyword: retu...
Returns position after keyword if found else None Note: skips white space
def eval_objfn(self): """Compute components of objective function as well as total contribution to objective function. """ fval = self.obfn_f() gval = self.obfn_g(self.obfn_gvar()) obj = fval + gval return (obj, fval, gval)
Compute components of objective function as well as total contribution to objective function.
def ecdsa_private_key(privkey_str=None, compressed=None): """ Make a private key, but enforce the following rule: * unless the key's hex encoding specifically ends in '01', treat it as uncompressed. """ if compressed is None: compressed = False if privkey_str is not None: ...
Make a private key, but enforce the following rule: * unless the key's hex encoding specifically ends in '01', treat it as uncompressed.
def generate_one_of(self): """ Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'ty...
Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ...
def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list``...
Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``...
def _run_ext_wsgiutils(app, config, mode): """Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.""" from wsgidav.server import ext_wsgiutils_server _logger.info( "Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...".format(__version__) ) _logger.warning( "WARNING: Th...
Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.
def apply_corrections(self): """ Method to directly apply the corrections. """ for error in self.errors: for solution in error.scheduler_adapter_solutions: if self.scheduler_adapter is not None: if self.scheduler_adapter.__getattribut__(sol...
Method to directly apply the corrections.
def endpoint_from_name(endpoint_name): """The object used for interacting with the named relations, or None. """ if endpoint_name is None: return None factory = relation_factory(endpoint_name) if factory: return factory.from_name(endpoint_name)
The object used for interacting with the named relations, or None.