code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pwgen(length=None): """Generate a random pasword.""" if length is None: # A random length is ok to use a weak PRNG length = random.choice(range(35, 45)) alphanumeric_chars = [ l for l in (string.ascii_letters + string.digits) if l not in 'l0QD1vAEIOUaeiou'] # Use a cr...
Generate a random pasword.
def set_urlroute_rules(rules=None): """ rules should be (pattern, replace) e.g.: ('/admin', '/demo') """ global __url_route_rules__ __url_route_rules__ = [] for k, v in (rules or {}).values(): __url_route_rules__.append((re.compile(k), v))
rules should be (pattern, replace) e.g.: ('/admin', '/demo')
def fcs(bits): ''' Append running bitwise FCS CRC checksum to end of generator ''' fcs = FCS() for bit in bits: yield bit fcs.update_bit(bit) # test = bitarray() # for byte in (digest & 0xff, digest >> 8): # print byte # for i in range(8): # b = (byte >> i) & 1 == 1 # test.append(b) # yield b # appe...
Append running bitwise FCS CRC checksum to end of generator
def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance): """Get the current chaperone bounds draw color and brightness""" fn = self.function_table.getBoundsColor pOutputColorArray = HmdColor_t() pOutputCameraColor = HmdColor_t() fn(byref(pOutputColorArray), nNu...
Get the current chaperone bounds draw color and brightness
def query_tag_values(self, metric_type=None, **tags): """ Query for possible tag values. :param metric_type: A MetricType to be queried. If left to None, matches all the MetricTypes :param tags: A dict of tag key/value pairs. Uses Hawkular-Metrics tag query language for syntax "...
Query for possible tag values. :param metric_type: A MetricType to be queried. If left to None, matches all the MetricTypes :param tags: A dict of tag key/value pairs. Uses Hawkular-Metrics tag query language for syntax
def from_exception(cls, exc): """ Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` ...
Construct a new :class:`Error` payload from the attributes of the exception. :param exc: The exception to convert :type exc: :class:`aioxmpp.errors.XMPPError` :result: Newly constructed error payload :rtype: :class:`Error` .. versionchanged:: 0.10 The :attr...
def _get_tensor_like_attributes(): """Returns `Tensor` attributes related to shape and Python builtins.""" # Enable "Tensor semantics" for distributions. # See tensorflow/python/framework/ops.py `class Tensor` for details. attrs = dict() # Setup overloadable operators and white-listed members / properties. ...
Returns `Tensor` attributes related to shape and Python builtins.
def create_conversation(self, body, recipients, attachment_ids=None, context_code=None, filter=None, filter_mode=None, group_conversation=None, media_comment_id=None, media_comment_type=None, mode=None, scope=None, subject=None, user_note=None): """ Create a conversation. Create a new conve...
Create a conversation. Create a new conversation with one or more recipients. If there is already an existing private conversation with the given recipients, it will be reused.
def open_editor(self, data=''): """ Open a file for editing using the system's default editor. After the file has been altered, the text will be read back and the HTML comment tag <!--INSRUCTIONS --> will be stripped. If an error occurs inside of the context manager, the file wi...
Open a file for editing using the system's default editor. After the file has been altered, the text will be read back and the HTML comment tag <!--INSRUCTIONS --> will be stripped. If an error occurs inside of the context manager, the file will be preserved so users can recover their d...
def switch_onoff(self, device, status): """Switch a Socket""" if status == 1 or status == True or status == '1': return self.switch_on(device) else: return self.switch_off(device)
Switch a Socket
def _replace_element_by_own_content(self, element): """ Replace the element by own text content. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ # pylint: disable=no-self-use if element.has_children_elements(): ...
Replace the element by own text content. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement
def display(self): """Virtual keyborad may get small d.info['displayHeight'] """ for line in self.adb_shell('dumpsys display').splitlines(): m = _DISPLAY_RE.search(line, 0) if not m: continue w = int(m.group('width')) h = int(m.grou...
Virtual keyborad may get small d.info['displayHeight']
def agent_intents(self): """Returns a list of intent json objects""" endpoint = self._intent_uri() intents = self._get(endpoint) # should be list of dicts if isinstance(intents, dict): # if error: intents = {status: {error}} raise Exception(intents["status"]) retur...
Returns a list of intent json objects
def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative mes...
Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext le...
def get_campaign_name_list(self): """ Returns a list of all valid campaign names Returns: List of strings containing all valid campaign names """ campaigns = self.find('campaigns', {}) campaign_names = [] for campaign in campaigns: if 'nam...
Returns a list of all valid campaign names Returns: List of strings containing all valid campaign names
def _insert_defaults(self): """ Inserts default values from :attr:`StructuredDictMixin.structure` to `self` by merging the two structures (see :func:`monk.manipulation.merge_defaults`). """ merged = merge_defaults(self.structure, self) self.update(merged)
Inserts default values from :attr:`StructuredDictMixin.structure` to `self` by merging the two structures (see :func:`monk.manipulation.merge_defaults`).
def download(url, target, headers=None, trackers=()): """Download a file using requests. This is like urllib.request.urlretrieve, but: - requests validates SSL certificates by default - you can pass tracker objects to e.g. display a progress bar or calculate a file hash. """ if headers i...
Download a file using requests. This is like urllib.request.urlretrieve, but: - requests validates SSL certificates by default - you can pass tracker objects to e.g. display a progress bar or calculate a file hash.
def _write_max_gradient(self)->None: "Writes the maximum of the gradients to Tensorboard." max_gradient = max(x.data.max() for x in self.gradients) self._add_gradient_scalar('max_gradient', scalar_value=max_gradient)
Writes the maximum of the gradients to Tensorboard.
def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: return json.dumps(self.json_repr(minimal=True), cls=Marathon...
Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str
def present(email, profile="splunk", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure example test user 1: splunk.user_present: - realname: 'Example TestUser1' - name: 'exampleuser' - email: 'example@domain.com' ...
Ensure a user is present .. code-block:: yaml ensure example test user 1: splunk.user_present: - realname: 'Example TestUser1' - name: 'exampleuser' - email: 'example@domain.com' - roles: ['user'] The following parameters are...
def _write_header(f, version, flags, stream_id, opcode, length): """ Write a CQL protocol frame header. """ pack = v3_header_pack if version >= 3 else header_pack f.write(pack(version, flags, stream_id, opcode)) write_int(f, length)
Write a CQL protocol frame header.
def pop_data_point(self, n): """ This will remove and return the n'th data point (starting at 0) from all columns. Parameters ---------- n Index of data point to pop. """ # loop over the columns and pop the data popped = [] ...
This will remove and return the n'th data point (starting at 0) from all columns. Parameters ---------- n Index of data point to pop.
def _find_step_node(self, step_text): """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.call.value[0].value if step == step_text: ...
Find the ast node which contains the text.
async def get_info(self): ''' Retrieves a brief information about the compute session. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key rqst = Request(self.session, 'GET', '/kernel/{}'.format(s...
Retrieves a brief information about the compute session.
def create_cmdclass(develop_wrappers=None, distribute_wrappers=None, data_dirs=None): """Create a command class with the given optional wrappers. Parameters ---------- develop_wrapper: list(str), optional The cmdclass names to run before running other commands distribute_wrappers: list(str),...
Create a command class with the given optional wrappers. Parameters ---------- develop_wrapper: list(str), optional The cmdclass names to run before running other commands distribute_wrappers: list(str), optional The cmdclass names to run before running other commands data_dirs: list...
def post_customer_preferences(self, **kwargs): # noqa: E501 """Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api....
Update selected fields of customer preferences # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_customer_preferences(async_req=True) >>> result = thread.ge...
def is_rpm_installed(): """Tests if the rpm command is present.""" try: version_result = subprocess.run(["rpm", "--usage"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rpm_installed = not version_result.returncod...
Tests if the rpm command is present.
async def create( cls, name: str, architecture: str, content: io.IOBase, *, title: str = "", filetype: BootResourceFileType = BootResourceFileType.TGZ, chunk_size=(1 << 22), progress_callback=None): """Create a `BootResource`. Creates an uploaded boot res...
Create a `BootResource`. Creates an uploaded boot resource with `content`. The `content` is uploaded in chunks of `chunk_size`. `content` must be seekable as the first pass through the `content` will calculate the size and sha256 value then the second pass will perform the actual upload...
def _format_lat(self, lat): ''' Returned a formated latitude format for the file ''' if self.ppd in [4, 16, 64, 128]: return None else: if lat < 0: return map(lambda x: "{0:0>2}" .format(int(np.abs(x))) + 'S', self._map_center('l...
Returned a formated latitude format for the file
def set_conn(self, **kwargs): """ takes a connection and creates the connection """ # log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise Nam...
takes a connection and creates the connection
def message(msg, *args): '''Program message output.''' clear_progress() text = (msg % args) sys.stdout.write(text + '\n')
Program message output.
def check_log_files_and_publish_updates(self): """Get any changes to the log files and push updates to Redis. Returns: True if anything was published and false otherwise. """ anything_published = False for file_info in self.open_file_infos: assert not fil...
Get any changes to the log files and push updates to Redis. Returns: True if anything was published and false otherwise.
def segment_to_line(document, coords): "polyline with 2 vertices using <line> tag" return setattribs( document.createElement('line'), x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3], )
polyline with 2 vertices using <line> tag
def restore_type(self, type): """Restore type from BigQuery """ # Mapping mapping = { 'BOOLEAN': 'boolean', 'DATE': 'date', 'DATETIME': 'datetime', 'INTEGER': 'integer', 'FLOAT': 'number', 'STRING': 'string', ...
Restore type from BigQuery
def get_common_prefix(z): """Get common directory in a zip file if any.""" name_list = z.namelist() if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]): return name_list[0] return None
Get common directory in a zip file if any.
def get_codes(): """ >> get_codes() ISO ISO3 ISO-Numeric fips Country Capital Area(in sq km) Population Continent tld CurrencyCode CurrencyName Phone Postal Code Format Postal Code Regex Languages geonameid neighbours EquivalentFipsCode """ cache_filename = os.path.join(os.path.dirname(__file__), 'd...
>> get_codes() ISO ISO3 ISO-Numeric fips Country Capital Area(in sq km) Population Continent tld CurrencyCode CurrencyName Phone Postal Code Format Postal Code Regex Languages geonameid neighbours EquivalentFipsCode
def _parse_request_arguments(self, request): """Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters """ inference_addresses = ...
Parses comma separated request arguments Args: request: A request that should contain 'inference_address', 'model_name', 'model_version', 'model_signature'. Returns: A tuple of lists for model parameters
def general_attention(key, context, hidden_size, projected_align=False): """ It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper: https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation" Args: key: A t...
It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper: https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation" Args: key: A tensorflow tensor with dimensionality [None, None, key_size] context: A te...
def rollforward(self, date): """Roll date forward to nearest end of year""" if self.onOffset(date): return date else: return date + YearEnd(month=self.month)
Roll date forward to nearest end of year
def get_path_for_core_element(self, core_element_id): """Get path to the row representing core element described by handed core_element_id :param list core_element_id: Core element identifier used in the respective list store column :rtype: tuple :return: path """ def ch...
Get path to the row representing core element described by handed core_element_id :param list core_element_id: Core element identifier used in the respective list store column :rtype: tuple :return: path
def _clone(self, **kwargs): """ Create a clone of this collection. The only param in the initial collection is the filter context. Each chainable filter is added to the clone and returned to preserve previous iterators and their returned elements. :return: :class...
Create a clone of this collection. The only param in the initial collection is the filter context. Each chainable filter is added to the clone and returned to preserve previous iterators and their returned elements. :return: :class:`.ElementCollection`
def unscale_dict(C): """Undo the scaling applied in `scale_dict`.""" C_out = {k: _scale_dict[k] * v for k, v in C.items()} for k in C_symm_keys[8]: C_out['qqql'] = unscale_8(C_out['qqql']) return C_out
Undo the scaling applied in `scale_dict`.
def spectral_contrast(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, fmin=200.0, n_bands=6, quantile=0.02, linear=False): '''Compute spectral contrast [1]_ .. [1]...
Compute spectral contrast [1]_ .. [1] Jiang, Dan-Ning, Lie Lu, Hong-Jiang Zhang, Jian-Hua Tao, and Lian-Hong Cai. "Music type classification by spectral contrast feature." In Multimedia and Expo, 2002. ICME'02. Proceedings. 2002 IEEE International Conference on, vol. 1, ...
def identifiers(dataset_uri): """List the item identifiers in the dataset.""" dataset = dtoolcore.DataSet.from_uri(dataset_uri) for i in dataset.identifiers: click.secho(i)
List the item identifiers in the dataset.
def _dist_to_trans(self, dist): """Convert mouse x, y movement into x, y, z translations""" rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180 sro, saz, sel = np.sin(rae) cro, caz, cel = np.cos(rae) dx = (+ dist[0] * (cro * caz + sro * sel * saz) ...
Convert mouse x, y movement into x, y, z translations
def list_of_lists_to_dict(l): """ Convert list of key,value lists to dict [['id', 1], ['id', 2], ['id', 3], ['foo': 4]] {'id': [1, 2, 3], 'foo': [4]} """ d = {} for key, val in l: d.setdefault(key, []).append(val) return d
Convert list of key,value lists to dict [['id', 1], ['id', 2], ['id', 3], ['foo': 4]] {'id': [1, 2, 3], 'foo': [4]}
def resolve_weak_types(storage, debug=False): """Reslove weak type rules W1 - W3. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types """ for run in storage['runs']: prev_strong = prev_type = run['sor'] start, length = run['start'], run['length'] chars = storage['chars']...
Reslove weak type rules W1 - W3. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
def parse_mcast_grps(family, grp_attr): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L64. Positional arguments: family -- genl_family class instance. grp_attr -- nlattr class instance. Returns: 0 on success or a negative error code. """ remaining = c_int() i...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L64. Positional arguments: family -- genl_family class instance. grp_attr -- nlattr class instance. Returns: 0 on success or a negative error code.
def play_NoteContainer(self, nc, channel=1, velocity=100): """Play the Notes in the NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel, 'velocity': velocity}) if nc is None: return True for note in nc: if not ...
Play the Notes in the NoteContainer nc.
def _publisher_callback(self, publish_ack): """ publisher callback that grpc and web socket can pass messages to address the received message onto the queue :param publish_ack: EventHub_pb2.Ack the ack received from either wss or grpc :return: None """ logging.deb...
publisher callback that grpc and web socket can pass messages to address the received message onto the queue :param publish_ack: EventHub_pb2.Ack the ack received from either wss or grpc :return: None
def ANNASSIGN(self, node): """ Annotated assignments don't have annotations evaluated on function scope, hence the custom implementation. Compared to the pyflakes version, we defer evaluation of the annotations (and values on module level). """ if node.value: ...
Annotated assignments don't have annotations evaluated on function scope, hence the custom implementation. Compared to the pyflakes version, we defer evaluation of the annotations (and values on module level).
def safe_file(path, suffix=None, cleanup=True): """A with-context that copies a file, and copies the copy back to the original file on success. This is useful for doing work on a file but only changing its state on success. :param str suffix: Use this suffix to create the copy. Otherwise use a random string. ...
A with-context that copies a file, and copies the copy back to the original file on success. This is useful for doing work on a file but only changing its state on success. :param str suffix: Use this suffix to create the copy. Otherwise use a random string. :param bool cleanup: Whether or not to clean up the c...
def _suppressed(self, filename, line, code): """Return true if linter error code is suppressed inline. The suppression format is suppress(CODE1,CODE2,CODE3) etc. """ if code in self.suppress_codes: return True lines = self._file_lines(filename) # File is ze...
Return true if linter error code is suppressed inline. The suppression format is suppress(CODE1,CODE2,CODE3) etc.
def exec_resize(self, exec_id, height=None, width=None): """ Resize the tty session used by the specified exec command. Args: exec_id (str): ID of the exec instance height (int): Height of tty session width (int): Width of tty session """ if ...
Resize the tty session used by the specified exec command. Args: exec_id (str): ID of the exec instance height (int): Height of tty session width (int): Width of tty session
def has_parent_bins(self, bin_id): """Tests if the ``Bin`` has any parents. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the bin has parents, ``false`` otherwise raise: NotFound - ``bin_id`` is not found raise: NullArgument -...
Tests if the ``Bin`` has any parents. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the bin has parents, ``false`` otherwise raise: NotFound - ``bin_id`` is not found raise: NullArgument - ``bin_id`` is ``null`` raise: Operat...
def get_remote_client(self, target_name, user=None, password=None): """ Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client """ if user: base = self.g...
Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client
def prefetch_relations(weak_queryset): """ FROM: https://djangosnippets.org/snippets/2492/ Consider such a model class:: class Action(models.Model): actor_content_type = models.ForeignKey(ContentType,related_name='actor') actor_object_id = models.PositiveIntegerField() ...
FROM: https://djangosnippets.org/snippets/2492/ Consider such a model class:: class Action(models.Model): actor_content_type = models.ForeignKey(ContentType,related_name='actor') actor_object_id = models.PositiveIntegerField() actor = GenericForeignKey('actor_content_ty...
def create_database_session(engine): """Connect to the database""" try: Session = sessionmaker(bind=engine) return Session() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
Connect to the database
def _update_property_from_dict(self, section, option, new_properties): """ Update a config property value with a new property value Property name must be equal to 'Section_option' of config property :param section: config section :param option: config option :param new_propertie...
Update a config property value with a new property value Property name must be equal to 'Section_option' of config property :param section: config section :param option: config option :param new_properties: dict with new properties values
def handle(self, *args, **kwargs): """Run the executor listener. This method never returns.""" listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {})) def _killer(signum, frame): """Kill the listener on receipt of a signal.""" ...
Run the executor listener. This method never returns.
def _check_cats(cats, vtypes, df, prep, callers): """Only include categories in the final output if they have values. """ out = [] for cat in cats: all_vals = [] for vtype in vtypes: vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers) all_vals.ex...
Only include categories in the final output if they have values.
def next_population(self, population, fitnesses): """Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: lis...
Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions.
def get_path(brain_or_object): """Calculate the physical path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the object :rtype: string """ if is_brain(brain_or_...
Calculate the physical path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the object :rtype: string
def plugins_post_process(self, retcode): """ Call post_process() on all plugins """ logger.info("Post-processing test...") self.publish("core", "stage", "post_process") for plugin in self.plugins.values(): logger.debug("Post-process %s", plugin) tr...
Call post_process() on all plugins
def _add_snps( self, snps, discrepant_snp_positions_threshold, discrepant_genotypes_threshold, save_output, ): """ Add SNPs to this Individual. Parameters ---------- snps : SNPs SNPs to add discrepant_snp_positions_threshol...
Add SNPs to this Individual. Parameters ---------- snps : SNPs SNPs to add discrepant_snp_positions_threshold : int see above discrepant_genotypes_threshold : int see above save_output see above Returns ---...
def t_heredoc(self, t): r'<<\S+\r?\n' t.lexer.is_tabbed = False self._init_heredoc(t) t.lexer.begin('heredoc')
r'<<\S+\r?\n
def untlpy2etd_ms(untl_elements, **kwargs): """Convert the UNTL elements structure into an ETD_MS structure. kwargs can be passed to the function for certain effects. """ degree_children = {} date_exists = False seen_creation = False # Make the root element. etd_ms_root = ETD_MS_CONVERS...
Convert the UNTL elements structure into an ETD_MS structure. kwargs can be passed to the function for certain effects.
def set_restricted(self, obj, restricted): """Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted...
Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted: True, if you want to restrict the object. :t...
def update_col(self, column_name, series): """ Add or replace a column in the underlying DataFrame. Parameters ---------- column_name : str Column to add or replace. series : pandas.Series or sequence Column data. """ logger.debug...
Add or replace a column in the underlying DataFrame. Parameters ---------- column_name : str Column to add or replace. series : pandas.Series or sequence Column data.
def setOverlayTransformOverlayRelative(self, ulOverlayHandle, ulOverlayHandleParent): """Sets the transform to relative to the transform of the specified overlay. This overlays visibility will also track the parents visibility""" fn = self.function_table.setOverlayTransformOverlayRelative pmatP...
Sets the transform to relative to the transform of the specified overlay. This overlays visibility will also track the parents visibility
async def teardown_conn(self, context): """Teardown a connection from a client.""" client_id = context.user_data self._logger.info("Tearing down client connection: %s", client_id) if client_id not in self.clients: self._logger.warning("client_id %s did not exist in teardown...
Teardown a connection from a client.
def train_model(best_processed_path, weight_path='../weight/model_weight.h5', verbose=2): """ Given path to processed BEST dataset, train CNN model for words beginning alongside with character label encoder and character type label encoder Input ===== best_processed_path: str, path to proce...
Given path to processed BEST dataset, train CNN model for words beginning alongside with character label encoder and character type label encoder Input ===== best_processed_path: str, path to processed BEST dataset weight_path: str, path to weight path file verbose: int, verbost option for ...
def get_args( self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace", ) -> RequestParameters: """ Method to parse `query_string` using `urllib.parse.parse_qs`. This methods is used by `args...
Method to parse `query_string` using `urllib.parse.parse_qs`. This methods is used by `args` property. Can be used directly if you need to change default parameters. :param keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank s...
def wrap(self, row: Union[Mapping[str, Any], Sequence[Any]]): """Return row tuple for row.""" return ( self.dataclass( **{ ident: row[column_name] for ident, column_name in self.ids_and_column_names.items() } ...
Return row tuple for row.
def do_bc(self, arg): """ [~process] bc <address> - clear a code breakpoint [~thread] bc <address> - clear a hardware breakpoint [~process] bc <address-address> - clear a memory breakpoint [~process] bc <address> <size> - clear a memory breakpoint """ token_list =...
[~process] bc <address> - clear a code breakpoint [~thread] bc <address> - clear a hardware breakpoint [~process] bc <address-address> - clear a memory breakpoint [~process] bc <address> <size> - clear a memory breakpoint
def set_authoring_nodes(self, editor): """ Sets the Model authoring Nodes using given editor. :param editor: Editor to set. :type editor: Editor :return: Method success. :rtype: bool """ project_node = self.default_project_node file_node = self.r...
Sets the Model authoring Nodes using given editor. :param editor: Editor to set. :type editor: Editor :return: Method success. :rtype: bool
def _boundary(self): """ Returns a random string to use as the boundary for a message. Returns: string. Boundary """ boundary = None try: import uuid boundary = uuid.uuid4().hex except ImportError: import random, sh...
Returns a random string to use as the boundary for a message. Returns: string. Boundary
def payload(self): """ Renders the resource payload. :returns: a dict representing the object to be used as payload for a request """ payload = {'type': self.resource_type(), 'attributes': self.attributes} if self.id: payload['id'] = self.id return pay...
Renders the resource payload. :returns: a dict representing the object to be used as payload for a request
def _print_napps(cls, napp_list): """Format the NApp list to be printed.""" mgr = NAppsManager() enabled = mgr.get_enabled() installed = mgr.get_installed() napps = [] for napp, desc in sorted(napp_list): status = 'i' if napp in installed else '-' ...
Format the NApp list to be printed.
def get_2d_local_memory_v2(x, query_shape, memory_flange): """Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges are half of query sizes. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d...
Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges are half of query sizes. Args: x: a [batch, height, width, depth tensor] query_shape: 2-d integer list of query shape memory_flange: 2-d integer list of memory flanges Returns: x: A [batch, num...
def close(self): """Close and remove hooks.""" if not self.closed: self._ipython.events.unregister('post_run_cell', self._fill) self._box.close() self.closed = True
Close and remove hooks.
def visit(self, node): """Visit a node. This method is largely modelled after the ast.NodeTransformer class. Args: node: The node to visit. Returns: A tuple of the primal and adjoint, each of which is a node or a list of nodes. """ method = 'visit_' + node.__class__.__name__...
Visit a node. This method is largely modelled after the ast.NodeTransformer class. Args: node: The node to visit. Returns: A tuple of the primal and adjoint, each of which is a node or a list of nodes.
def get(self, session): '''taobao.aftersale.get 查询用户售后服务模板 查询用户设置的售后服务模板,仅返回标题和id''' request = TOPRequest('taobao.aftersale.get') self.create(self.execute(request, session)) return self.after_sales
taobao.aftersale.get 查询用户售后服务模板 查询用户设置的售后服务模板,仅返回标题和id
def subtract(self, years=0, months=0, weeks=0, days=0): """ Remove duration from the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int ...
Remove duration from the instance. :param years: The number of years :type years: int :param months: The number of months :type months: int :param weeks: The number of weeks :type weeks: int :param days: The number of days :type days: int :rty...
def rewrite_update(clauseelement, multiparams, params): """ change the params to enable partial updates sqlalchemy by default only supports updates of complex types in the form of "col = ?", ({"x": 1, "y": 2} but crate supports "col['x'] = ?, col['y'] = ?", (1, 2) by using the `Crat...
change the params to enable partial updates sqlalchemy by default only supports updates of complex types in the form of "col = ?", ({"x": 1, "y": 2} but crate supports "col['x'] = ?, col['y'] = ?", (1, 2) by using the `Craty` (`MutableDict`) type. The update statement is only rewrit...
def copy(self): '''Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA ''' # Significant performance improvements by skipping alphabet check features_copy = [feature.copy() for feature in self.features] ...
Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA
def sort_item(iterable, number, reverse=False): """Sort the itertable according to the given number item.""" return sorted(iterable, key=itemgetter(number), reverse=reverse)
Sort the itertable according to the given number item.
def b58decode(val, charset=DEFAULT_CHARSET): """Decode base58check encoded input to original raw bytes. :param bytes val: The value to base58cheeck decode. :param bytes charset: (optional) The character set to use for decoding. :return: the decoded bytes. :rtype: bytes Usage:: >>> impor...
Decode base58check encoded input to original raw bytes. :param bytes val: The value to base58cheeck decode. :param bytes charset: (optional) The character set to use for decoding. :return: the decoded bytes. :rtype: bytes Usage:: >>> import base58check >>> base58check.b58decode('\x00v...
def Validate(self, value, **_): """Check that value is a valid enum.""" if value is None: return return rdfvalue.RDFBool(super(ProtoBoolean, self).Validate(value))
Check that value is a valid enum.
def autobuild_docproject(): """Autobuild a project that only contains documentation""" try: #Build only release information family = utilities.get_family('module_settings.json') autobuild_release(family) autobuild_documentation(family.tile) except unit_test.IOTileException a...
Autobuild a project that only contains documentation
def merge_rest_api_config(configs): """ Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority). """ bind = None connect = None timeout = None opentsdb_url = None opentsdb_db = None opentsd...
Given a list of PathConfig objects, merges them into a single PathConfig, giving priority in the order of the configs (first has highest priority).
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix them where possible. ''' super(MapRegisterMessage, self).sanitize() # P: This is the proxy-map-reply bit, when set to 1 an ETR sends a Map- # Register message request...
Check if the current settings conform to the LISP specifications and fix them where possible.
def addAEMOD(rh): """ Send an Activation Modification Script to the virtual machine. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'AEMOD' userid - userid of the virtual machine parms['aeScript'] - File spec...
Send an Activation Modification Script to the virtual machine. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'AEMOD' userid - userid of the virtual machine parms['aeScript'] - File specification of the AE script ...
def set_axis_labels(self, x_var=None, y_var=None): """Set axis labels on the left column and bottom row of the grid.""" if x_var is not None: if x_var in self.data.coords: self._x_var = x_var self.set_xlabels(label_from_attrs(self.data[x_var])) els...
Set axis labels on the left column and bottom row of the grid.
def tabular(client, records): """Format dataset files with a tabular output. :param client: LocalClient instance. :param records: Filtered collection. """ from renku.models._tabulate import tabulate echo_via_pager( tabulate( records, headers=OrderedDict(( ...
Format dataset files with a tabular output. :param client: LocalClient instance. :param records: Filtered collection.
def CreateReply(self, **attributes): """Create a new packet as a reply to this one. This method makes sure the authenticator and secret are copied over to the new instance. """ return Packet(id=self.id, secret=self.secret, authenticator=self.authenticator, d...
Create a new packet as a reply to this one. This method makes sure the authenticator and secret are copied over to the new instance.
def clone(self, run=True): """ Clone task :param run: run task after cloning :return: Task object. """ params = {} if run: params.update({'action': 'run'}) extra = { 'resource': self.__class__.__name__, 'query': {'id': ...
Clone task :param run: run task after cloning :return: Task object.
def pdb_downloader_and_metadata(self, outdir=None, pdb_file_type=None, force_rerun=False): """Download ALL mapped experimental structures to the protein structures directory. Args: outdir (str): Path to output directory, if protein structures directory not set or other output directory is ...
Download ALL mapped experimental structures to the protein structures directory. Args: outdir (str): Path to output directory, if protein structures directory not set or other output directory is desired pdb_file_type (str): Type of PDB file to download, if not already s...
def superclasses(self, inherited=False): """Iterate over the superclasses of the class. This function is the Python equivalent of the CLIPS class-superclasses command. """ data = clips.data.DataObject(self._env) lib.EnvClassSuperclasses( self._env, self._cl...
Iterate over the superclasses of the class. This function is the Python equivalent of the CLIPS class-superclasses command.
def pngout(ext_args): """Run the external program pngout on the file.""" args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
Run the external program pngout on the file.