code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def flatten(iterable): """convenience tool to flatten any nested iterable example: flatten([[[],[4]],[[[5,[6,7, []]]]]]) >>> [4, 5, 6, 7] flatten('hello') >>> 'hello' Parameters ---------- iterable Returns ------- flattened object """ if isite...
convenience tool to flatten any nested iterable example: flatten([[[],[4]],[[[5,[6,7, []]]]]]) >>> [4, 5, 6, 7] flatten('hello') >>> 'hello' Parameters ---------- iterable Returns ------- flattened object
def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): """ Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_re...
Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing...
def container_remove_objects(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /container-xxxx/removeObjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveObjects """ return DXHTTP...
Invokes the /container-xxxx/removeObjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveObjects
def _strip_zoom(input_string, strip_string): """Return zoom level as integer or throw error.""" try: return int(input_string.strip(strip_string)) except Exception as e: raise MapcheteConfigError("zoom level could not be determined: %s" % e)
Return zoom level as integer or throw error.
def solar_position(moment, latitude, longitude, Z=0.0, T=298.15, P=101325.0, atmos_refract=0.5667): r'''Calculate the position of the sun in the sky. It is defined in terms of two angles - the zenith and the azimith. The azimuth tells where a sundial would see the sun as coming f...
r'''Calculate the position of the sun in the sky. It is defined in terms of two angles - the zenith and the azimith. The azimuth tells where a sundial would see the sun as coming from; the zenith tells how high in the sky it is. The solar elevation angle is returned for convinience; it is the complimen...
def xpose6(m): """ Transpose a 6x6 matrix http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html :param m: Matrix to be transposed :type m: list[6][6] :return: Transposed matrix :rtype: list[6][6] """ m = stypes.toDoubleMatrix(m) mout = stypes.emptyDoubleMatrix(...
Transpose a 6x6 matrix http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html :param m: Matrix to be transposed :type m: list[6][6] :return: Transposed matrix :rtype: list[6][6]
def cumulative_window(group_by=None, order_by=None): """Create a cumulative window for use with aggregate window functions. All window frames / ranges are inclusive. Parameters ---------- group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : exp...
Create a cumulative window for use with aggregate window functions. All window frames / ranges are inclusive. Parameters ---------- group_by : expressions, default None Either specify here or with TableExpr.group_by order_by : expressions, default None For analytic functions requir...
def download_file(url, filename=None, show_progress=draw_pbar): ''' Download a file and show progress url: the URL of the file to download filename: the filename to download it to (if not given, uses the url's filename part) show_progress: callback function to update a progress bar the show_pr...
Download a file and show progress url: the URL of the file to download filename: the filename to download it to (if not given, uses the url's filename part) show_progress: callback function to update a progress bar the show_progress function shall take two parameters: `seen` and `size`, and return...
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(Ini...
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
def closeEvent(self, event): """ things to be done when gui closes, like save the settings """ self.script_thread.quit() self.read_probes.quit() if self.config_filename: fname = self.config_filename self.save_config(fname) event.accept() ...
things to be done when gui closes, like save the settings
def set_send_enable(self, setting): """ Set the send enable setting on the watch """ self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting)))
Set the send enable setting on the watch
def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: context.trace_id, SPAN_ID_HEADER: context.span_id, FLAGS_HEADER: '0', SAMPLED_ID_HEADER: '1' if context.sampled else '0', ...
Creates dict with zipkin headers from supplied trace context.
async def get_scene(self, scene_id, from_cache=True) -> Scene: """Get a scene resource instance. :raises a ResourceNotFoundException when no scene found. :raises a PvApiError when something is wrong with the hub. """ if not from_cache: await self.get_scenes() ...
Get a scene resource instance. :raises a ResourceNotFoundException when no scene found. :raises a PvApiError when something is wrong with the hub.
def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" if zeroconf_tag and self.zeroconf_enable_tag: self.listener.set_server(server_pos, key, value)
Set the key to the value for the server_pos (position in the list).
def cmprss(delim, n, instr, lenout=_default_len_out): """ Compress a character string by removing occurrences of more than N consecutive occurrences of a specified character. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html :param delim: Delimiter to be compressed. :ty...
Compress a character string by removing occurrences of more than N consecutive occurrences of a specified character. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html :param delim: Delimiter to be compressed. :type delim: str :param n: Maximum consecutive occurrences of del...
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache __register_features () # Stores ...
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'.
def get_subdomain_history_neighbors(self, cursor, subdomain_rec): """ Given a subdomain record, get its neighbors. I.e. get all of the subdomain records with the previous sequence number, and get all of the subdomain records with the next sequence number Returns {'prev': [...bloc...
Given a subdomain record, get its neighbors. I.e. get all of the subdomain records with the previous sequence number, and get all of the subdomain records with the next sequence number Returns {'prev': [...blockchain order...], 'cur': [...blockchain order...], 'fut': [...blockchain order...]}
def getTransitionProbabilities(state, action): """ Parameters ---------- state : tuple The state action : int The action Returns ------- s1, p, r : tuple of two lists and an int s1 are the next states, p are the probabilities, and r is the reward """...
Parameters ---------- state : tuple The state action : int The action Returns ------- s1, p, r : tuple of two lists and an int s1 are the next states, p are the probabilities, and r is the reward
def nuc_v(msg): """Calculate NUCv, Navigation Uncertainty Category - Velocity (ADS-B version 1) Args: msg (string): 28 bytes hexadecimal message string, Returns: int or string: 95% Horizontal Velocity Error int or string: 95% Vertical Velocity Error """ tc = typecode(msg) ...
Calculate NUCv, Navigation Uncertainty Category - Velocity (ADS-B version 1) Args: msg (string): 28 bytes hexadecimal message string, Returns: int or string: 95% Horizontal Velocity Error int or string: 95% Vertical Velocity Error
def clean_caches(path): """ Removes all python cache files recursively on a path. :param path: the path :return: None """ for dirname, subdirlist, filelist in os.walk(path): for f in filelist: if f.endswith('pyc'): try: os.remove(os.path...
Removes all python cache files recursively on a path. :param path: the path :return: None
def sync(to_install, to_uninstall, verbose=False, dry_run=False, install_flags=None): """ Install and uninstalls the given sets of modules. """ if not to_uninstall and not to_install: click.echo("Everything up-to-date") pip_flags = [] if not verbose: pip_flags += ['-q'] if ...
Install and uninstalls the given sets of modules.
def user_data_dir(appname, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for t...
r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. "appauthor" (only required and used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. ...
def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'e...
Upgrade database.
def build(self, pre=None, shortest=False): """Build this rule definition :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ if pre is None: pre...
Build this rule definition :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
def connect(self, name, func, sender=None, dispatch_uid=None): """ Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sen...
Connects a function to a hook.\ Creates the hook (name) if it does not exists :param str name: The hook name :param callable func: A function reference used as a callback :param class sender: Optional sender __class__ to which the\ func should respond. Default will match all ...
def pretty_size(value): """Convert a number of bytes into a human-readable string. Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU. """ exp = int(math.log(value, 1024)) if value > 0 else 0 unit = 'bkMGTPEZY'[exp] if exp == 0: return ...
Convert a number of bytes into a human-readable string. Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU.
def _cmptimestamps(self, filest1, filest2): """ Compare time stamps of two files and return True if file1 (source) is more recent than file2 (target) """ mtime_cmp = int((filest1.st_mtime - filest2.st_mtime) * 1000) > 0 if self._use_ctime: return mtime_cmp or \ ...
Compare time stamps of two files and return True if file1 (source) is more recent than file2 (target)
def delete(self, id): """DELETE /mapfiles/id: Delete an existing mapfile owned by the current user. Deletion of the map entry in db and remove mapfile from filesystem. """ map = self._delete_map_from_user_by_id(c.user, id) if map is None: abort(404) if os.path.exists(...
DELETE /mapfiles/id: Delete an existing mapfile owned by the current user. Deletion of the map entry in db and remove mapfile from filesystem.
def _Open(self, path_spec, mode='rb'): """Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to ...
Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: if th...
def file_delete(context, id, file_id): """file_delete(context, id, path) Delete a component file >>> dcictl component-file-delete [OPTIONS] :param string id: ID of the component to delete file [required] :param string file_id: ID for the file to delete [required] """ component.file_delete...
file_delete(context, id, path) Delete a component file >>> dcictl component-file-delete [OPTIONS] :param string id: ID of the component to delete file [required] :param string file_id: ID for the file to delete [required]
def build_path(graph, node1, node2, path=None): """ Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path. """ if path is None: path = [] ...
Build the path from node1 to node2. The path is composed of all the nodes between node1 and node2, node1 excluded. Although if there is a loop starting from node1, it will be included in the path.
def attention_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.lea...
Set of hyperparameters.
def copy( self, name, start_codons=None, stop_codons=None, codon_table=None, codon_table_changes=None): """ Make copy of this GeneticCode object with optional replacement values for all fields. """ new_start_...
Make copy of this GeneticCode object with optional replacement values for all fields.
def usage(): """ Illustrate what the various input flags are and the options should be. :return: none """ global g_script_name # name of the script being run. print("") print("Usage: " + g_script_name + " [...options...]") print("") print(" --help print out this help menu a...
Illustrate what the various input flags are and the options should be. :return: none
def _extract_symbols(self, symbols, default=None): """! @brief Fill 'symbols' field with required flash algo symbols""" to_ret = {} for symbol in symbols: symbolInfo = self.elf.symbol_decoder.get_symbol_for_name(symbol) if symbolInfo is None: if default is...
! @brief Fill 'symbols' field with required flash algo symbols
def add_values_to_bundle_safe(connection, bundle, values): """ Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, ...
Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, that should be added in bundle. Raises: YouTrackException:...
def get(self, key): """Get a document by id.""" doc = self._collection.find_one({'_id': key}) if doc: doc.pop('_id') return doc
Get a document by id.
def infos(self): ''' dict: The summation of all data available about the extracted article Note: Read only ''' data = { "meta": { "description": self.meta_description, "lang": self.meta_lang, "keywords": self.meta_k...
dict: The summation of all data available about the extracted article Note: Read only
def direction_vector(self, angle): ''' Returns a unit vector, pointing in the arc's movement direction at a given (absolute) angle (in degrees). No check is made whether angle lies within the arc's span (the results for angles outside of the arc's span ) Returns a 2x1 numpy array. ...
Returns a unit vector, pointing in the arc's movement direction at a given (absolute) angle (in degrees). No check is made whether angle lies within the arc's span (the results for angles outside of the arc's span ) Returns a 2x1 numpy array. >>> a = Arc((0, 0), 1, 0, 90, True) ...
def pop(self, pair, default=None): """ Removes the **pair** from the Kerning and returns the value as an ``int``. If no pair is found, **default** is returned. **pair** is a ``tuple`` of two :ref:`type-string`\s. This must return either **default** or a :ref:`type-int-float`. ...
Removes the **pair** from the Kerning and returns the value as an ``int``. If no pair is found, **default** is returned. **pair** is a ``tuple`` of two :ref:`type-string`\s. This must return either **default** or a :ref:`type-int-float`. >>> font.kerning.pop(("A", "V")) ...
def char_between(lower, upper, func_name): '''return current char and step if char is between lower and upper, where @test: a python function with one argument, which tests on one char and return True or False @test must be registered with register_function''' function = register_function(func_na...
return current char and step if char is between lower and upper, where @test: a python function with one argument, which tests on one char and return True or False @test must be registered with register_function
def returnValueList(self, key_list, last=False): '''Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of u...
Return a list of key values for the first entry in the current list. If 'last=True', then the last entry is referenced." Returns None is the list is empty. If a key is missing, then that entry in the list is None. Example of use: >>> test = [ ... {"name": "Jim", "...
def apply_new_scoped_variable_type(self, path, new_variable_type_str): """Applies the new data type of the scoped variable defined by path :param str path: The path identifying the edited variable :param str new_variable_type_str: New data type as str """ data_port_id = self.lis...
Applies the new data type of the scoped variable defined by path :param str path: The path identifying the edited variable :param str new_variable_type_str: New data type as str
def normalize_sort(sort=None): """ CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE """ if not sort: return Null output = FlatList() for s in listwrap(sort): if is_text(s) or mo_math.is_integer(s): output.append({"value": s, "sort": 1}) elif not s.f...
CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE
def zpk2tf(z, p, k): r"""Return polynomial transfer function representation from zeros and poles :param ndarray z: Zeros of the transfer function. :param ndarray p: Poles of the transfer function. :param float k: System gain. :return: b : ndarray Numerator polynomial. a : ndarray N...
r"""Return polynomial transfer function representation from zeros and poles :param ndarray z: Zeros of the transfer function. :param ndarray p: Poles of the transfer function. :param float k: System gain. :return: b : ndarray Numerator polynomial. a : ndarray Numerator and denominator ...
def start_trace(reset=True, filter_func=None, time_filter_func=None): """Begins a trace. Setting reset to True will reset all previously recorded trace data. filter_func needs to point to a callable function that accepts the parameters (call_stack, module_name, class_name, func_name, full_name). Every c...
Begins a trace. Setting reset to True will reset all previously recorded trace data. filter_func needs to point to a callable function that accepts the parameters (call_stack, module_name, class_name, func_name, full_name). Every call will be passed into this function and it is up to the function to dec...
def count_if(predicate, seq): """Count the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2 """ f = lambda count, x: count + (not not predicate(x)) return reduce(f, seq, 0)
Count the number of elements of seq for which the predicate is true. >>> count_if(callable, [42, None, max, min]) 2
def _gather_all_deps(self, args, kwargs): """Count the number of unresolved futures on which a task depends. Args: - args (List[args]) : The list of args list to the fn - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn Returns: - count, [list...
Count the number of unresolved futures on which a task depends. Args: - args (List[args]) : The list of args list to the fn - kwargs (Dict{kwargs}) : The dict of all kwargs passed to the fn Returns: - count, [list of dependencies]
def register(self, what, obj): """ Registering a plugin Params ------ what: Nature of the plugin (backend, instrumentation, repo) obj: Instance of the plugin """ # print("Registering pattern", name, pattern) name = obj.name version = obj.v...
Registering a plugin Params ------ what: Nature of the plugin (backend, instrumentation, repo) obj: Instance of the plugin
def validate_xml_text(text): """validates XML text""" bad_chars = __INVALID_XML_CHARS & set(text) if bad_chars: for offset,c in enumerate(text): if c in bad_chars: raise RuntimeError('invalid XML character: ' + repr(c) + ' at offset ' + str(offset))
validates XML text
def get_feature_by_path(self, locus, term, rank, accession, **kwargs): """ Retrieve an enumerated sequence feature This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when recei...
Retrieve an enumerated sequence feature This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(resp...
def _reaction_po_to_dict(tokens) -> Reaction: """Convert a reaction parse object to a DSL. :type tokens: ParseResult """ return Reaction( reactants=_reaction_part_po_to_dict(tokens[REACTANTS]), products=_reaction_part_po_to_dict(tokens[PRODUCTS]), )
Convert a reaction parse object to a DSL. :type tokens: ParseResult
def _radec(self,*args,**kwargs): """Calculate ra and dec""" lbd= self._lbd(*args,**kwargs) return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None)
Calculate ra and dec
def configureIAMCredentials(self, AWSAccessKeyID, AWSSecretAccessKey, AWSSessionToken=""): """ **Description** Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect. **Syntax** .. code:: python ...
**Description** Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureIAMCredentials(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSess...
def _invalid_implementation(self, t, missing, mistyped, mismatched): """ Make a TypeError explaining why ``t`` doesn't implement our interface. """ assert missing or mistyped or mismatched, "Implementation wasn't invalid." message = "\nclass {C} failed to implement interface {I}...
Make a TypeError explaining why ``t`` doesn't implement our interface.
def redistribute_threads(blockdimx, blockdimy, blockdimz, dimx, dimy, dimz): """ Redistribute threads from the Z dimension towards the X dimension. Also clamp number of threads to the problem dimension size, if necessary """ # Shift threads from the z dimension # into the y dimension ...
Redistribute threads from the Z dimension towards the X dimension. Also clamp number of threads to the problem dimension size, if necessary
def set_dimmer_start_time(self, hour, minute): """Set start time for task (hh:mm) in iso8601. NB: dimmer starts 30 mins before time in app """ # This is to calculate the difference between local time # and the time in the gateway d1 = self._gateway.get_gateway_info().c...
Set start time for task (hh:mm) in iso8601. NB: dimmer starts 30 mins before time in app
def create(*context, **kwargs): """ Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instanc...
Build a ContextStack instance from a sequence of context-like items. This factory-style method is more general than the ContextStack class's constructor in that, unlike the constructor, the argument list can itself contain ContextStack instances. Here is an example illustrating various...
def _make_r_patches(data, K_g, critical_r, indices, approx): '''Helper function for :py:func:`.make_r_gaussmix` and :py:func:`.make_r_tmix`. Group the ``data`` according to the R value and split each group into ``K_g`` patches. Return the patch means and covariances. For details see the docstrings of th...
Helper function for :py:func:`.make_r_gaussmix` and :py:func:`.make_r_tmix`. Group the ``data`` according to the R value and split each group into ``K_g`` patches. Return the patch means and covariances. For details see the docstrings of the above mentioned functions.
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None): """ Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finally load the snapsh...
Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finally load the snapshot.
def enter_eventloop(self): """enter eventloop""" self.log.info("entering eventloop") # restore default_int_handler signal(SIGINT, default_int_handler) while self.eventloop is not None: try: self.eventloop(self) except KeyboardInterrupt: ...
enter eventloop
def cleanup_unreachable(rdf): """Remove triples which cannot be reached from the concepts by graph traversal.""" all_subjects = set(rdf.subjects()) logging.debug("total subject resources: %d", len(all_subjects)) reachable = find_reachable(rdf, SKOS.Concept) nonreachable = all_subjects - reach...
Remove triples which cannot be reached from the concepts by graph traversal.
def resample_signal(self, data_frame): """ Convenience method for frequency conversion and resampling of data frame. Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum acceleration values and the x,y,z values of the data fra...
Convenience method for frequency conversion and resampling of data frame. Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum acceleration values and the x,y,z values of the data frame acceleration :param data_frame: the data frame ...
def _stripslashes(s): '''Removes trailing and leading backslashes from string''' r = re.sub(r"\\(n|r)", "\n", s) r = re.sub(r"\\", "", r) return r
Removes trailing and leading backslashes from string
def _set_status(self, status, message=''): """ Updates the status and message on all supported IM apps. `status` Status type (See ``VALID_STATUSES``). `message` Status message. """ message = message.strip() # fetch away messa...
Updates the status and message on all supported IM apps. `status` Status type (See ``VALID_STATUSES``). `message` Status message.
def from_bytes(cls, b): """Create an APNG from raw bytes. :arg bytes b: The raw bytes of the APNG file. :rtype: APNG """ hdr = None head_chunks = [] end = ("IEND", make_chunk("IEND", b"")) frame_chunks = [] frames = [] num_plays = 0 frame_has_head_chunks = False control = None for ...
Create an APNG from raw bytes. :arg bytes b: The raw bytes of the APNG file. :rtype: APNG
def is_same(type1, type2): """returns True, if type1 and type2 are same types""" nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
returns True, if type1 and type2 are same types
def _get_log_model_class(self): """Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class. """ if self.log_model_class is not ...
Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class.
def shelter_listbybreed(self, **kwargs): """ shelter.listByBreed wrapper. Given a breed and an animal type, list the shelter IDs with pets of said breed. :rtype: generator :returns: A generator of shelter IDs that have breed matches. """ root = self._do_api_call...
shelter.listByBreed wrapper. Given a breed and an animal type, list the shelter IDs with pets of said breed. :rtype: generator :returns: A generator of shelter IDs that have breed matches.
def move(zone, zonepath): ''' Move zone to new zonepath. zone : string name or uuid of the zone zonepath : string new zonepath CLI Example: .. code-block:: bash salt '*' zoneadm.move meave /sweetwater/meave ''' ret = {'status': True} ## verify zone re...
Move zone to new zonepath. zone : string name or uuid of the zone zonepath : string new zonepath CLI Example: .. code-block:: bash salt '*' zoneadm.move meave /sweetwater/meave
def get_profile(session): """Get profile data.""" response = session.get(PROFILE_URL, allow_redirects=False) if response.status_code == 302: raise USPSError('expired session') parsed = BeautifulSoup(response.text, HTML_PARSER) profile = parsed.find('div', {'class': 'atg_store_myProfileInfo'}...
Get profile data.
def add_interactions_from(self, ebunch, t=None, e=None): """Add all the interaction in ebunch at time t. Parameters ---------- ebunch : container of interaction Each interaction given in the container will be added to the graph. The interaction must be given as a...
Add all the interaction in ebunch at time t. Parameters ---------- ebunch : container of interaction Each interaction given in the container will be added to the graph. The interaction must be given as as 2-tuples (u,v) or 3-tuples (u,v,d) where d is a dictio...
def imagecapture(self, window_name=None, x=0, y=0, width=None, height=None): """ Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type win...
Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: int @param y: y co-ordinate value ...
def set_stack_address_mapping(self, absolute_address, region_id, related_function_address=None): """ Create a new mapping between an absolute address (which is the base address of a specific stack frame) and a region ID. :param absolute_address: The absolute memory address. :par...
Create a new mapping between an absolute address (which is the base address of a specific stack frame) and a region ID. :param absolute_address: The absolute memory address. :param region_id: The region ID. :param related_function_address: Related function address.
def s15f16l(s): """Convert sequence of ICC s15Fixed16 to list of float.""" # Note: As long as float has at least 32 bits of mantissa, all # values are preserved. n = len(s) // 4 t = struct.unpack('>%dl' % n, s) return map((2**-16).__mul__, t)
Convert sequence of ICC s15Fixed16 to list of float.
def _get(self, key, what): """Generic getter magic method. The node with the nearest but not less hash value is returned. :param key: the key to look for. :param what: the information to look for in, allowed values: - instance (default): associated node instance ...
Generic getter magic method. The node with the nearest but not less hash value is returned. :param key: the key to look for. :param what: the information to look for in, allowed values: - instance (default): associated node instance - nodename: node name - p...
def checkBinary(name, bindir=None): """ Checks for the given binary in the places, defined by the environment variables SUMO_HOME and <NAME>_BINARY. """ if name == "sumo-gui": envName = "GUISIM_BINARY" else: envName = name.upper() + "_BINARY" env = os.environ join = os.pa...
Checks for the given binary in the places, defined by the environment variables SUMO_HOME and <NAME>_BINARY.
def OnPadIntCtrl(self, event): """Pad IntCtrl event handler""" self.attrs["pad"] = event.GetValue() post_command_event(self, self.DrawChartMsg)
Pad IntCtrl event handler
def _get_remote(self, cached=True): ''' Helper function to determine remote :param cached: Use cached values or query remotes ''' return self.m( 'getting current remote', cmdd=dict( cmd='git remote show %s' % ('-n' if cached e...
Helper function to determine remote :param cached: Use cached values or query remotes
def from_conll(this_class, stream): """Construct a Corpus. stream is an iterable over strings where each string is a line in CoNLL-X format.""" stream = iter(stream) corpus = this_class() while 1: # read until we get an empty sentence sentence = Sentence.f...
Construct a Corpus. stream is an iterable over strings where each string is a line in CoNLL-X format.
def remove(path): '''Remove a cached environment. Removed paths will no longer be able to be activated by name''' r = cpenv.resolve(path) if isinstance(r.resolved[0], cpenv.VirtualEnvironment): EnvironmentCache.discard(r.resolved[0]) EnvironmentCache.save()
Remove a cached environment. Removed paths will no longer be able to be activated by name
def sample_slice(args): """ Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `...
Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) ...
def _execute(self, cursor, statements): """" Executes a list of statements, returning an iterator of results sets. Each statement should be a tuple of (statement, params). """ payload = [{'statement': s, 'parameters': p, 'resultDataContents':['rest']} for (s, p) in statements] ...
Executes a list of statements, returning an iterator of results sets. Each statement should be a tuple of (statement, params).
def list(self, search_opts=None): """Get a list of Plugins.""" query = base.get_query_string(search_opts) return self._list('/plugins%s' % query, 'plugins')
Get a list of Plugins.
def get_ball_by_ball(self, match_key, over_key=None): """ match_key: key of the match over_key : key of the over Return: json data: """ if over_key: ball_by_ball_url = "{base_path}match/{match_key}/balls/{over_key}/".format(base_path=self....
match_key: key of the match over_key : key of the over Return: json data:
def check_applied(result): """ Raises LWTException if it looks like a failed LWT request. A LWTException won't be raised in the special case in which there are several failed LWT in a :class:`~cqlengine.query.BatchQuery`. """ try: applied = result.was_applied except Exception: ...
Raises LWTException if it looks like a failed LWT request. A LWTException won't be raised in the special case in which there are several failed LWT in a :class:`~cqlengine.query.BatchQuery`.
def updateSocialTone(user, socialTone, maintainHistory): """ updateSocialTone updates the user with the social tones interpreted based on the specified thresholds @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param socialTo...
updateSocialTone updates the user with the social tones interpreted based on the specified thresholds @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param socialTone a json object containing the social tones in the payload retur...
def _set_system_description(self, v, load=False): """ Setter method for system_description, mapped from YANG variable /protocol/lldp/system_description (string) If this variable is read-only (config: false) in the source YANG file, then _set_system_description is considered as a private method. Back...
Setter method for system_description, mapped from YANG variable /protocol/lldp/system_description (string) If this variable is read-only (config: false) in the source YANG file, then _set_system_description is considered as a private method. Backends looking to populate this variable should do so via ca...
def mode(data): """Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters -------...
Compute an intelligent value for the mode The most common value in experimental is not very useful if there are a lot of digits after the comma. This method approaches this issue by rounding to bin size that is determined by the Freedman–Diaconis rule. Parameters ---------- data: 1d ndarra...
def add_enclave_tag(self, report_id, name, enclave_id, id_type=None): """ Adds a tag to a specific report, for a specific enclave. :param report_id: The ID of the report :param name: The name of the tag to be added :param enclave_id: ID of the enclave where the tag will be added...
Adds a tag to a specific report, for a specific enclave. :param report_id: The ID of the report :param name: The name of the tag to be added :param enclave_id: ID of the enclave where the tag will be added :param id_type: indicates whether the ID internal or an external ID provided by t...
def primary_avatar(user, size=AVATAR_DEFAULT_SIZE): """ This tag tries to get the default avatar for a user without doing any db requests. It achieve this by linking to a special view that will do all the work for us. If that special view is then cached by a CDN for instance, we will avoid many db ...
This tag tries to get the default avatar for a user without doing any db requests. It achieve this by linking to a special view that will do all the work for us. If that special view is then cached by a CDN for instance, we will avoid many db calls.
def delete(self, personId): """Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams ...
Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
def parse_args(self): """Parse CLI args.""" self.tcex.log.info('Parsing Args.') Args(self.tcex.parser) self.args = self.tcex.args
Parse CLI args.
def send_data_to_server(self, data, time_out=5): """ Sends given data to the Server. :param data: Data to send. :type data: unicode :param time_out: Connection timeout in seconds. :type time_out: float :return: Method success. :rtype: bool """ ...
Sends given data to the Server. :param data: Data to send. :type data: unicode :param time_out: Connection timeout in seconds. :type time_out: float :return: Method success. :rtype: bool
def terminate(self): '''Kills the work unit. This is called by the standard worker system, but only in response to an operating system signal. If the job does setup such as creating a child process, its terminate function should kill that child process. More specifically, this...
Kills the work unit. This is called by the standard worker system, but only in response to an operating system signal. If the job does setup such as creating a child process, its terminate function should kill that child process. More specifically, this function requires the w...
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
Set of hyperparameters.
def field_value(key, label, color, padding): """ Print a specific field's stats. """ if not clr.has_colors and padding > 0: padding = 7 if color == "bright gray" or color == "dark gray": bright_prefix = "" else: bright_prefix = "bright " field = clr.stringc(key, "{0...
Print a specific field's stats.
def write_configuration(self, out, secret_attrs=False): """Generic configuration, may be overridden by type-specific version""" key_order = ['name', 'path', 'git_dir', 'doc_dir', 'assumed_doc_version', 'git_ssh', 'pkey', 'has_aliases', 'number of collections'] cd = self.get_...
Generic configuration, may be overridden by type-specific version
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False): """Execute several cleanup tasks as part of the cleanup. REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. :param ctx: Context object for the tasks. :param cleanup_tasks: Collection of cleanup tasks (as Colle...
Execute several cleanup tasks as part of the cleanup. REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. :param ctx: Context object for the tasks. :param cleanup_tasks: Collection of cleanup tasks (as Collection). :param dry_run: Indicates dry-run mode (bool)
def make_transformer(self, decompose='svd', decompose_by=50, tsne_kwargs={}): """ Creates an internal transformer pipeline to project the data set into 2D space using TSNE, applying an pre-decomposition technique ahead of embedding if necessary. This method will reset the transformer on ...
Creates an internal transformer pipeline to project the data set into 2D space using TSNE, applying an pre-decomposition technique ahead of embedding if necessary. This method will reset the transformer on the class, and can be used to explore different decompositions. Parameters ...