code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def groupsFromKey(keyFile='./key.txt'): """ given a groups file, return a dict of groups. Example: ### GROUP: TR 16602083 16608059 ### GROUP: TU 16504000 16507011 """ groups={} thisGroup="?" with open(keyFile) as f: raw=f.read().split("...
given a groups file, return a dict of groups. Example: ### GROUP: TR 16602083 16608059 ### GROUP: TU 16504000 16507011
def get_config(self): """ Returns pickle-serializable configuration struct for storage. """ # Fill this dict with config data return { 'hash_name': self.hash_name, 'dim': self.dim, 'projection_count': self.projection_count, 'normals...
Returns pickle-serializable configuration struct for storage.
def listing(parser, token): """ Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <re...
Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <result> %} Parameters: ======...
def _as_dict(self, r): """Convert the record to a dictionary using field names as keys.""" d = dict() for i, f in enumerate(self._field_names): d[f] = r[i] if i < len(r) else None return d
Convert the record to a dictionary using field names as keys.
def read_from_user(input_type, *args, **kwargs): ''' Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly. ''' def _read_in(*args, **kwargs): while True: try: tmp = raw_inpu...
Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly.
def update(self, process_list): """Update the AMP""" # Get the systemctl status logger.debug('{}: Update stats using systemctl {}'.format(self.NAME, self.get('systemctl_cmd'))) try: res = check_output(self.get('systemctl_cmd').split()) except (OSError, CalledProcessEr...
Update the AMP
def close(self): """Close the poll instance.""" if self._poll is None: return self._poll.close() self._poll = None self._readers = 0 self._writers = 0 self._events = 0 clear_callbacks(self)
Close the poll instance.
def cardInfo(self, resource_id): """Return card info. :params resource_id: Resource id. """ # TODO: add referer to headers (futweb) base_id = baseId(resource_id) if base_id in self.players: return self.players[base_id] else: # not a player? ...
Return card info. :params resource_id: Resource id.
def delete_group_dampening(self, group_id, dampening_id): """ Delete an existing group dampening :param group_id: Group Trigger id to be retrieved :param dampening_id: id of the Dampening to be deleted """ self._delete(self._service_url(['triggers', 'groups', group_id, '...
Delete an existing group dampening :param group_id: Group Trigger id to be retrieved :param dampening_id: id of the Dampening to be deleted
def filename_generate(extension, database_name='', servername=None, content_type='db', wildcard=None): """ Create a new backup filename. :param extension: Extension of backup file :type extension: ``str`` :param database_name: If it is database backup specify its name :type database_name: ``st...
Create a new backup filename. :param extension: Extension of backup file :type extension: ``str`` :param database_name: If it is database backup specify its name :type database_name: ``str`` :param servername: Specify server name or by default ``settings.DBBACKUP_HOSTNAME`` :type servername: ...
def get_page_from_string_or_id(page_string, lang=None): """Return a Page object from a slug or an id.""" if type(page_string) == int: return Page.objects.get(pk=int(page_string)) # if we have a string coming from some templates templates if (isinstance(page_string, SafeText) or isins...
Return a Page object from a slug or an id.
def simxGetObjectIntParameter(clientID, objectHandle, parameterID, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' parameterValue = ct.c_int() return c_GetObjectIntParameter(clientID, objectHandle, parameterID, ct.byref(parameterValue),...
Please have a look at the function description/documentation in the V-REP user manual
def create_qualification_type(self, name, description, status, keywords=None, retry_delay=None, test=None, ...
Create a new Qualification Type. name: This will be visible to workers and must be unique for a given requester. description: description shown to workers. Max 2000 characters. status: 'Active' or 'Inactive' keywords: list of keyword strings or comma separated string. ...
def get_value(self, i, indeps=None): """ access the interpolated value at a give value of i (independent-variable) if indeps is not passed, then the entire range of indeps over all calls is assumed """ if self.value is None: return None if i is None: ...
access the interpolated value at a give value of i (independent-variable) if indeps is not passed, then the entire range of indeps over all calls is assumed
def warning(self, i: int=None) -> str: """ Returns a warning message """ head = "[" + colors.purple("\033[1mwarning") + "]" if i is not None: head = str(i) + " " + head return head
Returns a warning message
def user_verify_password(user_id=None, name=None, password=None, profile=None, **connection_args): ''' Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_pa...
Verify a user's password CLI Examples: .. code-block:: bash salt '*' keystone.user_verify_password name=test password=foobar salt '*' keystone.user_verify_password user_id=c965f79c4f864eaaa9c3b41904e67082 password=foobar
def to_jsondict(self): """ Returns a dict expressing the flow stats. """ body = {"oxs_fields": [ofproto.oxs_to_jsondict(k, uv) for k, uv in self.fields], "length": self.length} return {self.__class__.__name__: body}
Returns a dict expressing the flow stats.
def padnames(names): """ pads names for loci output """ ## get longest name longname_len = max(len(i) for i in names) ## Padding distance between name and seq. padding = 5 ## add pad to names pnames = [name + " " * (longname_len - len(name)+ padding) \ for name in names] s...
pads names for loci output
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60): """ Print STDOUT resulting from a Bash shell command formatted in reStructuredText. :param command: Bash shell command :type command: string :param nindent: Indentation level :type nindent: integer :param env: Environm...
Print STDOUT resulting from a Bash shell command formatted in reStructuredText. :param command: Bash shell command :type command: string :param nindent: Indentation level :type nindent: integer :param env: Environment variable replacement dictionary. The Bash command is pre-proc...
def directory(): """Construct hitman_dir from os name""" home = os.path.expanduser('~') if platform.system() == 'Linux': hitman_dir = os.path.join(home, '.hitman') elif platform.system() == 'Darwin': hitman_dir = os.path.join(home, 'Library', 'Application Support', ...
Construct hitman_dir from os name
def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') ...
Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings
def set_cellpy_datadir(self, directory=None): """Set the directory containing .hdf5-files. Used for setting directory for looking for hdf5-files. A valid directory name is required. Args: directory (str): path to hdf5-directory Example: >>> d = CellpyDa...
Set the directory containing .hdf5-files. Used for setting directory for looking for hdf5-files. A valid directory name is required. Args: directory (str): path to hdf5-directory Example: >>> d = CellpyData() >>> directory = "MyData/HDF5" ...
def record_to_fh(self, f): """Write the record, in filesystem format, to a file handle or file object""" fr = self.record if fr.contents: yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8') fr.source_hash = self.fs_hash fr.mod...
Write the record, in filesystem format, to a file handle or file object
def copy(self, target): """Copies this file the `target`, which might be a directory. The permissions are copied. """ shutil.copy(self.path, self._to_backend(target))
Copies this file the `target`, which might be a directory. The permissions are copied.
def _attempt_slice_recovery(self, shard_state, tstate): """Recover a slice. This is run when a slice had been previously attempted and output may have been written. If an output writer requires slice recovery, we run those logic to remove output duplicates. Otherwise we just retry the slice. I...
Recover a slice. This is run when a slice had been previously attempted and output may have been written. If an output writer requires slice recovery, we run those logic to remove output duplicates. Otherwise we just retry the slice. If recovery is needed, then the entire slice will be dedicated ...
def get_postadres_by_huisnummer(self, huisnummer): ''' Get the `postadres` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `postadres` is wanted. OR A huisnummer id. :rtype: A :class:`str`. ''' try: id = huisn...
Get the `postadres` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `postadres` is wanted. OR A huisnummer id. :rtype: A :class:`str`.
def _read_nowait(self, n: int) -> bytes: """ Read not more than n bytes, or whole buffer is n == -1 """ chunks = [] while self._buffer: chunk = self._read_nowait_chunk(n) chunks.append(chunk) if n != -1: n -= len(chunk) if n ==...
Read not more than n bytes, or whole buffer is n == -1
def dim_iter(self, *dim_strides, **kwargs): """ Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning a tuple of dictionaries describing a dimension update. For example, the following call effectively produces 2 loops over the 'ntime...
Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning a tuple of dictionaries describing a dimension update. For example, the following call effectively produces 2 loops over the 'ntime' and 'nchan' dimensions in chunks of 10 and 4 respectiv...
def oauth_required(f): """ decorator to add to a view to require an oauth user :return: decorated function """ @wraps(f) def decorated_function(*args, **kwargs): if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None: return re...
decorator to add to a view to require an oauth user :return: decorated function
def entities_per_chunk(chunk): """Given a chunk, find all entities (mobs, items, vehicles)""" entities = [] for entity in chunk['Entities']: x,y,z = entity["Pos"] entities.append(Entity(entity["id"].value, (x.value,y.value,z.value))) return entities
Given a chunk, find all entities (mobs, items, vehicles)
def uploadPackages(self, directory): """ Not working. Am not able ot figure out how to upload. IT return status 200OK with this code but do not store the files. In tomcat.log (IM) there?s a complaint about character encoding whn uploading file. Not sure how to rectiy it in requests post ...
Not working. Am not able ot figure out how to upload. IT return status 200OK with this code but do not store the files. In tomcat.log (IM) there?s a complaint about character encoding whn uploading file. Not sure how to rectiy it in requests post call though
def _header_constructor( cls, data_to_print, header_separator="-", column_separator=" " ): """ Construct header of the table according to template. :param data_to_print: The list of data to print into the header of the table. :type data_to_print: list :p...
Construct header of the table according to template. :param data_to_print: The list of data to print into the header of the table. :type data_to_print: list :param header_separator: The separator to use between the table header and our data. :type header_separat...
def remove_mid_line_ifs(self, ifs): """ Go through passed offsets, filtering ifs located somewhere mid-line. """ # FIXME: this doesn't work for Python 3.6+ filtered = [] for i in ifs: # For each offset, if line number of current and next op ...
Go through passed offsets, filtering ifs located somewhere mid-line.
def list(): """List running TensorBoard instances.""" running_list = [] parser = argparse.ArgumentParser() parser.add_argument('--logdir') parser.add_argument('--port') for p in psutil.process_iter(): if p.name() != 'tensorboard' or p.status() == psutil.STATUS_ZOMBIE: continue ...
List running TensorBoard instances.
def get_monochrome_handler( extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: """ Gets a monochrome log handler using a standard format. Args: extranames: additional names to ap...
Gets a monochrome log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log ou...
def _save_feed(cls, conf, benchmarks, data, revisions, revision_to_hash): """ Save the results as an Atom feed """ filename = os.path.join(conf.html_dir, 'regressions.xml') # Determine publication date as the date when the benchmark # was run --- if it is missing, use t...
Save the results as an Atom feed
def as_tuple(self): """Return all of the matrix’s components. :returns: A ``(xx, yx, xy, yy, x0, y0)`` tuple of floats. """ ptr = self._pointer return (ptr.xx, ptr.yx, ptr.xy, ptr.yy, ptr.x0, ptr.y0)
Return all of the matrix’s components. :returns: A ``(xx, yx, xy, yy, x0, y0)`` tuple of floats.
def _parse_response(self, respond): """parse text of response for HTTP errors This parses the text of the response to decide whether to retry request or raise exception. At the moment this only detects an exception condition. Args: respond (Response): requests.Respo...
parse text of response for HTTP errors This parses the text of the response to decide whether to retry request or raise exception. At the moment this only detects an exception condition. Args: respond (Response): requests.Response object Returns: bool: ...
def interlink_removed_content(generator): '''For all contents removed from generation queue update interlinks link to the native location ''' current_lang = generator.settings['DEFAULT_LANG'] for content in _GENERATOR_DB[generator]: url = _NATIVE_CONTENT_URL_DB[content.source_path] ...
For all contents removed from generation queue update interlinks link to the native location
def load_fitsbuf(self, imname, fitsbuf, num_hdu): """Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load th...
Display a FITS file buffer in a remote Ginga reference viewer. Parameters ---------- imname : str A name to use for the image in the reference viewer. chname : str Name of a channel in which to load the image. fitsbuf : str This should be a ...
def load_project(self, filename, overwrite=False): r""" Loads a Project from the specified 'pnm' file The loaded project is added to the Workspace . This will *not* delete any existing Projects in the Workspace and will rename any Projects being loaded if necessary. Par...
r""" Loads a Project from the specified 'pnm' file The loaded project is added to the Workspace . This will *not* delete any existing Projects in the Workspace and will rename any Projects being loaded if necessary. Parameters ---------- filename : string or pat...
def op_cmd(self, command, req_format='text', xpath_expr=""): """ Execute an operational mode command. Purpose: Used to send an operational mode command to the connected | device. This requires and uses a paramiko.SSHClient() as | the handler so that we can easily pass and ...
Execute an operational mode command. Purpose: Used to send an operational mode command to the connected | device. This requires and uses a paramiko.SSHClient() as | the handler so that we can easily pass and allow all pipe | commands to be used. | ...
def _plugin_get(self, plugin_name): """ Find plugins in controller :param plugin_name: Name of the plugin to find :type plugin_name: str | None :return: Plugin or None and error message :rtype: (settable_plugin.SettablePlugin | None, str) """ if not plugi...
Find plugins in controller :param plugin_name: Name of the plugin to find :type plugin_name: str | None :return: Plugin or None and error message :rtype: (settable_plugin.SettablePlugin | None, str)
def major_complex(network, state): """Return the major complex of the network. Args: network (Network): The |Network| of interest. state (tuple[int]): The state of the network (a binary tuple). Returns: SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with maxima...
Return the major complex of the network. Args: network (Network): The |Network| of interest. state (tuple[int]): The state of the network (a binary tuple). Returns: SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with maximal |big_phi|.
def main(): """ NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to sta...
NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to standard output
def setShowSubProgress( self, state ): """ Toggles whether or not the sub progress bar should be visible. :param state | <bool> """ ajax = self.currentMode() == XLoaderWidget.Mode.Spinner self._showSubProgress = state self._subProgressBar.setVisible(...
Toggles whether or not the sub progress bar should be visible. :param state | <bool>
def visit_Call(self, node): """Propagate 'debug' wrapper into inner function calls if needed. Args: node (ast.AST): node statement to surround. """ if self.depth == 0: return node if self.ignore_exceptions is None: ignore_exceptions = ast.Nam...
Propagate 'debug' wrapper into inner function calls if needed. Args: node (ast.AST): node statement to surround.
def create(self, **fields): """Create and return a new record in associated app and return the newly created Record instance Args: **fields: Field names and values to be validated and sent to server with create request Notes: Keyword arguments should be field names with...
Create and return a new record in associated app and return the newly created Record instance Args: **fields: Field names and values to be validated and sent to server with create request Notes: Keyword arguments should be field names with their respective python values ...
def _select_input(self): """Select current line (without selecting console prompt)""" line, index = self.get_position('eof') if self.current_prompt_pos is None: pline, pindex = line, index else: pline, pindex = self.current_prompt_pos self.setSelect...
Select current line (without selecting console prompt)
def to_bytes(self, exclude=tuple(), disable=None, **kwargs): """Serialize the current state to a binary string. exclude (list): Names of components or serialization fields to exclude. RETURNS (bytes): The serialized form of the `Language` object. DOCS: https://spacy.io/api/language#to_...
Serialize the current state to a binary string. exclude (list): Names of components or serialization fields to exclude. RETURNS (bytes): The serialized form of the `Language` object. DOCS: https://spacy.io/api/language#to_bytes
def on_menu_import_meas_file(self, event): """ Open measurement file, reset self.magic_file and self.WD, and reset everything. """ # use new measurement file and corresponding WD meas_file = self.choose_meas_file() WD = os.path.split(meas_file)[0] self.WD ...
Open measurement file, reset self.magic_file and self.WD, and reset everything.
def main(list_ids, model, contact_server, raw_data_id, show_raw, mysql_cfg='mysql_online'): """Main function of view.py.""" if list_ids: preprocessing_desc, _, _ = _get_system(model) raw_datapath = os.path.join(utils.get_project_root(), preprocessing_...
Main function of view.py.
def update_floatingip(floatingip_id, port=None, profile=None): ''' Updates a floatingIP CLI Example: .. code-block:: bash salt '*' neutron.update_floatingip network-name port-name :param floatingip_id: ID of floatingIP :param port: ID or name of port, to associate floatingip to `None...
Updates a floatingIP CLI Example: .. code-block:: bash salt '*' neutron.update_floatingip network-name port-name :param floatingip_id: ID of floatingIP :param port: ID or name of port, to associate floatingip to `None` or do not specify to disassociate the floatingip (Optional) :...
def migrate(module=None): """ Entrypoint to migrate the schema. For the moment only create tables. """ if not module: #Parsing parser = argparse.ArgumentParser() parser.add_argument('-s', '--service', type=str, help='Migrate the module', required=True, ...
Entrypoint to migrate the schema. For the moment only create tables.
def _orbitNumberBreaks(self): """Determine where orbital breaks in a dataset with orbit numbers occur. Looks for changes in unique values. """ if self.orbit_index is None: raise ValueError('Orbit properties must be defined at ' + 'pysat.Instrum...
Determine where orbital breaks in a dataset with orbit numbers occur. Looks for changes in unique values.
def human_duration(t): """ Converts a time duration into a friendly text representation. >>> human_duration("type error") Traceback (most recent call last): ... TypeError: human_duration() argument must be integer or float >>> human_duration(0.01) u'10.0 ms' >>> human_duration(0.9)...
Converts a time duration into a friendly text representation. >>> human_duration("type error") Traceback (most recent call last): ... TypeError: human_duration() argument must be integer or float >>> human_duration(0.01) u'10.0 ms' >>> human_duration(0.9) u'900.0 ms' >>> human_dura...
def _write_model(self, specification): """ This method writes the ouput for a particular specification. """ if specification.allowed_job_commands and not (set(specification.allowed_job_commands).issubset(self.job_commands)): raise Exception("Invalid allowed_job_commands %s s...
This method writes the ouput for a particular specification.
def get_sitej(self, site_index, image_index): """ Assuming there is some value in the connectivity array at indices (1, 3, 12). sitei can be obtained directly from the input structure (structure[1]). sitej can be obtained by passing 3, 12 to this function Args: site_...
Assuming there is some value in the connectivity array at indices (1, 3, 12). sitei can be obtained directly from the input structure (structure[1]). sitej can be obtained by passing 3, 12 to this function Args: site_index (int): index of the site (3 in the example) imag...
def table(self): """ The |Table| object contained in this graphic frame. Raises |ValueError| if this graphic frame does not contain a table. """ if not self.has_table: raise ValueError('shape does not contain a table') tbl = self._element.graphic.graphicData.t...
The |Table| object contained in this graphic frame. Raises |ValueError| if this graphic frame does not contain a table.
def onOpen(self): """ Called when a client has opened a websocket connection """ self.factory.add_client(self) # Publish ON_OPEN message self.factory.mease.publisher.publish( message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage)
Called when a client has opened a websocket connection
def write_event(self, event): """Writes an event proto to disk. This method is threadsafe with respect to invocations of itself. Args: event: The event proto. Raises: IOError: If writing the event proto to disk fails. """ self._lock.acquire() try: self._events_writer.Wri...
Writes an event proto to disk. This method is threadsafe with respect to invocations of itself. Args: event: The event proto. Raises: IOError: If writing the event proto to disk fails.
def shifted_centroid_distance(item_a, time_a, item_b, time_b, max_value): """ Centroid distance with motion corrections. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time...
Centroid distance with motion corrections. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distance value used as sca...
def to_string(self): """ Returns a string with the structure in XSF format See http://www.xcrysden.org/doc/XSF.html """ lines = [] app = lines.append app("CRYSTAL") app("# Primitive lattice vectors in Angstrom") app("PRIMVEC") cell = self....
Returns a string with the structure in XSF format See http://www.xcrysden.org/doc/XSF.html
def ic_pos(self, row1, row2=None): """Calculate the information content of one position. Returns ------- score : float Information content. """ if row2 is None: row2 = [0.25,0.25,0.25,0.25] score = 0 for a,b in zip(row1, row2): ...
Calculate the information content of one position. Returns ------- score : float Information content.
def update_net_info(self, tenant_id, direc, vlan_id, segmentation_id): """Update the DCNM netinfo with vlan and segmentation ID. """ serv_obj = self.get_service_obj(tenant_id) net_dict = self.update_dcnm_net_info(tenant_id, direc, vlan_id, segmentatio...
Update the DCNM netinfo with vlan and segmentation ID.
def EQ107(T, A=0, B=0, C=0, D=0, E=0, order=0): r'''DIPPR Equation #107. Often used in calculating ideal-gas heat capacity. All 5 parameters are required. Also called the Aly-Lee equation. .. math:: Y = A + B\left[\frac{C/T}{\sinh(C/T)}\right]^2 + D\left[\frac{E/T}{ \cosh(E/T)}\right]^2...
r'''DIPPR Equation #107. Often used in calculating ideal-gas heat capacity. All 5 parameters are required. Also called the Aly-Lee equation. .. math:: Y = A + B\left[\frac{C/T}{\sinh(C/T)}\right]^2 + D\left[\frac{E/T}{ \cosh(E/T)}\right]^2 Parameters ---------- T : float ...
def to_b58check(self, testnet=False): """ Generates a Base58Check encoding of this key. Args: testnet (bool): True if the key is to be used with testnet, False otherwise. Returns: str: A Base58Check encoded string representing the key. """ ...
Generates a Base58Check encoding of this key. Args: testnet (bool): True if the key is to be used with testnet, False otherwise. Returns: str: A Base58Check encoded string representing the key.
def _diffrsp_app(self,xmlfile=None, **kwargs): """ Compute the diffuse response """ loglevel = kwargs.get('loglevel', self.loglevel) self.logger.log(loglevel, 'Computing diffuse repsonce for component %s.', self.name) # set the srcmdl sr...
Compute the diffuse response
def _autodiscover(self): """Discovers modules to register from ``settings.INSTALLED_APPS``. This makes sure that the appropriate modules get imported to register themselves with Horizon. """ if not getattr(self, '_registerable_class', None): raise ImproperlyConfigure...
Discovers modules to register from ``settings.INSTALLED_APPS``. This makes sure that the appropriate modules get imported to register themselves with Horizon.
def strip_optional_prefix(string, prefix, log=None): """ >>> strip_optional_prefix('abcdef', 'abc') 'def' >>> strip_optional_prefix('abcdef', '123') 'abcdef' >>> strip_optional_prefix('abcdef', '123', PrintingLogger()) String starts with 'abc', not '123' 'abcdef' """ if string.st...
>>> strip_optional_prefix('abcdef', 'abc') 'def' >>> strip_optional_prefix('abcdef', '123') 'abcdef' >>> strip_optional_prefix('abcdef', '123', PrintingLogger()) String starts with 'abc', not '123' 'abcdef'
def pyang_plugin_init(): """Called by pyang plugin framework at to initialize the plugin.""" # Register the plugin plugin.register_plugin(MDPlugin()) # Register that we handle extensions from the YANG module # 'ietf-yang-metadata' grammar.register_extension_module(md_module_name) # Regist...
Called by pyang plugin framework at to initialize the plugin.
def _set_bit_size(self, size, step=1, auto_align=False): """ Sets the *size* of the `Decimal` field. :param int size: is the *size* of the `Decimal` field in bits, can be between ``1`` and ``64``. :param int step: is the minimal required step *size* for the `Decimal` fie...
Sets the *size* of the `Decimal` field. :param int size: is the *size* of the `Decimal` field in bits, can be between ``1`` and ``64``. :param int step: is the minimal required step *size* for the `Decimal` field in bits. :param bool auto_align: if ``True`` the `Decimal`...
def make_pay_to_address_script(address): """ Takes in an address and returns the script """ hash160 = hexlify(b58check_decode(address)) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex(script_string)
Takes in an address and returns the script
def send_stun(self, message, addr): """ Send a STUN message. """ self.__log_debug('> %s %s', addr, message) self.transport.sendto(bytes(message), addr)
Send a STUN message.
def _get_user_agent(platform=None): """ Convenience function that looks up a user agent string, random if N/A """ if isinstance(platform, ustr): platform = platform.upper() return {"chrome": AGENT_CHROME, "edge": AGENT_EDGE, "ios": AGENT_IOS}.get( platform, random.choice(AGENT_ALL) )
Convenience function that looks up a user agent string, random if N/A
def check_w_normalized(W, N_k, tolerance = 1.0e-4): """Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1 Parameters ---------- W : np.ndarray, shape=(N, K), dtype='float' The normalized weight matrix for snapshots and states...
Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1 Parameters ---------- W : np.ndarray, shape=(N, K), dtype='float' The normalized weight matrix for snapshots and states. W[n, k] is the weight of snapshot n in state k. ...
def setup (self): ''' Runs only the first time SimpleSteem() is instantiated. Prompts user for the values that are then written to config.py ''' mainaccount = self.add_quotes(self.enter_config_value("mainaccount", 'ned')) keys = self.enter_config_value("keys", '[]') ...
Runs only the first time SimpleSteem() is instantiated. Prompts user for the values that are then written to config.py
def get_network_by_tenant(self, tenant_id): """Returns the network of a given tenant. """ ret_net_lst = [] try: net_list = self.neutronclient.list_networks(body={}) for net in net_list.get('networks'): if net.get('tenant_id') == tenant_id: ...
Returns the network of a given tenant.
def are_all_matches_terminal(self, predicate: Callable[[ops.Operation], bool]): """Check whether all of the ops that satisfy a predicate are terminal. Args: predicate: A predicate on ops.Operations which is being checked. Returns: Whether or not all `Operati...
Check whether all of the ops that satisfy a predicate are terminal. Args: predicate: A predicate on ops.Operations which is being checked. Returns: Whether or not all `Operation` s in a circuit that satisfy the given predicate are terminal.
def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._...
Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``.
def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """ if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_u...
A function to generate the top level biggus ufunc wrappers.
def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz): """Calculate a flux density from pure free-free emission. """ hz = ghz * 1e9 eta = calc_freefree_eta(ne, t, hz) kappa = calc_freefree_kappa(ne, t, hz) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs...
Calculate a flux density from pure free-free emission.
def find_repo_urls(session, name, candidates): """ Visits the given URL candidates and searches the page for valid links to a repository. :param session: requests Session instance :param name: str, project name :param candidates: list, list of URL candidates :return: str, URL to a repo """ ...
Visits the given URL candidates and searches the page for valid links to a repository. :param session: requests Session instance :param name: str, project name :param candidates: list, list of URL candidates :return: str, URL to a repo
def measures(self): """Iterate over all measures""" from ambry.valuetype.core import ROLE return [c for c in self.columns if c.role == ROLE.MEASURE]
Iterate over all measures
def included_profiles(self): """Load all profiles.""" profiles = [] for directory in self.tcex_json.get('profile_include_dirs') or []: profiles.extend(self._load_config_include(directory)) return profiles
Load all profiles.
def image_postprocess(imagefile, output, size, crop, render): """ Resize and crop captured image, and saves to output. (can be stream or filename) """ try: from PIL import Image except ImportError: import Image img = Image.open(imagefile) size_crop = None img_resized...
Resize and crop captured image, and saves to output. (can be stream or filename)
def _write_SOCKS5_address(self, addr, file): """ Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object. """ host, port = addr proxy_type, _, _, rdns, username, password = self.proxy family_to_byte = {socket.AF_INET: b"...
Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object.
def parse(self, text): """ Parse a string of SVG <path> data. """ gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) token = next_val_fn() return self.rule_svg_path(next_val_fn, token)
Parse a string of SVG <path> data.
def get_log(self, ti): """ Get Logs of a command from Qubole :param ti: Task Instance of the dag, used to determine the Quboles command id :return: command log as text """ if self.cmd is None: cmd_id = ti.xcom_pull(key="qbol_cmd_id", task_ids=self.task_id) ...
Get Logs of a command from Qubole :param ti: Task Instance of the dag, used to determine the Quboles command id :return: command log as text
def get_integer(prompt): """Gather user input and convert it to an integer Will keep trying till the user enters an interger or until they ^C the program. """ while True: try: return int(input(prompt).strip()) except ValueError: ...
Gather user input and convert it to an integer Will keep trying till the user enters an interger or until they ^C the program.
def iterate_references(config, to=None): """Provides an iterator over references in the given config. Args: config: A dictionary mapping scoped configurable names to argument bindings. to: If supplied, only yield references whose `configurable_fn` matches `to`. Yields: `ConfigurableReference` instan...
Provides an iterator over references in the given config. Args: config: A dictionary mapping scoped configurable names to argument bindings. to: If supplied, only yield references whose `configurable_fn` matches `to`. Yields: `ConfigurableReference` instances within `config`, maybe restricted to those...
def create_new_metadata(self, rsa_public_key): # type: (EncryptionMetadata, # cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey) # -> None """Create new metadata entries for encryption (upload) :param EncryptionMetadata self: this :param cryptograph...
Create new metadata entries for encryption (upload) :param EncryptionMetadata self: this :param cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey: rsa public key
def _rc_smove(self, src, dst, value): """ Move ``value`` from set ``src`` to set ``dst`` not atomic """ if self.type(src) != b("set"): return self.smove(src + "{" + src + "}", dst, value) if self.type(dst) != b("set"): return self.smove(dst + "{" +...
Move ``value`` from set ``src`` to set ``dst`` not atomic
def remove_columns(self, column_names, inplace=False): """ Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- co...
def gaussian_filter(X, M=8, axis=0): """Gaussian filter along the first axis of the feature matrix X.""" for i in range(X.shape[axis]): if axis == 1: X[:, i] = filters.gaussian_filter(X[:, i], sigma=M / 2.) elif axis == 0: X[i, :] = filters.gaussian_filter(X[i, :], sigma=...
Gaussian filter along the first axis of the feature matrix X.
def _pastorestr(ins): ''' Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW inmediate strings for the 2nd parameter, starting with '#'. ''' output = _paddr(ins.quad[1]) t...
Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW inmediate strings for the 2nd parameter, starting with '#'.
def merge(self, other): """ We can merge unless the merge results in an empty set -- a contradiction """ other = self.coerce(other) if self.is_equal(other): # pick among dependencies return self elif self.is_contradictory(other): ...
We can merge unless the merge results in an empty set -- a contradiction
def get_spatial_type(spatial_model): """Translate a spatial model string to a spatial type.""" if spatial_model in ['SkyDirFunction', 'PointSource', 'Gaussian']: return 'SkyDirFunction' elif spatial_model in ['SpatialMap']: return 'SpatialMap' elif spatial_model...
Translate a spatial model string to a spatial type.
def read(library, session, count): """Reads data from device or interface synchronously. Corresponds to viRead function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :re...
Reads data from device or interface synchronously. Corresponds to viRead function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: data read, return value of the libra...
def from_irc(cls, text): """ Create a new instance of ColorString from a mIRC-formatted text :param text: mIRC-formatted text :return: """ from .grammars.irc import parse as parse_irc if isinstance(text, bytes): original_bytes = text text =...
Create a new instance of ColorString from a mIRC-formatted text :param text: mIRC-formatted text :return: