code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def Log_startViolationsReport(self, config): """ Function path: Log.startViolationsReport Domain: Log Method name: startViolationsReport Parameters: Required arguments: 'config' (type: array) -> Configuration for violations. No return value. Description: start violation reporting. ""...
Function path: Log.startViolationsReport Domain: Log Method name: startViolationsReport Parameters: Required arguments: 'config' (type: array) -> Configuration for violations. No return value. Description: start violation reporting.
def edge_statistics(docgraph): """print basic statistics about an edge, e.g. layer/attribute counts""" print "Edge statistics\n===============" layer_counts = Counter() attrib_counts = Counter() source_counts = Counter() target_counts = Counter() for source, target, edge_attrs in docgraph.ed...
print basic statistics about an edge, e.g. layer/attribute counts
def find_manifest_changes(new_file_state, old_file_state): """ Find what has changed between two sets of files """ prev_state_dict = copy.deepcopy(old_file_state) changed_files = {} # Find files which are new on the server for itm in new_file_state: if itm['path'] in prev_state_dict: ...
Find what has changed between two sets of files
def add_list_blocks_parser(subparsers, parent_parser): """Creates the arg parsers needed for the compare command. """ parser = subparsers.add_parser( 'list-blocks', help='List blocks from different nodes.', formatter_class=argparse.RawDescriptionHelpFormatter, epilog='', ...
Creates the arg parsers needed for the compare command.
def set_notebook(note_store, my_notebook, notebook_id): """ create a notebook """ if notebook_id == 0: new_notebook = Types.Notebook() new_notebook.name = my_notebook new_notebook.defaultNotebook = False notebook_id = note_store.createN...
create a notebook
def open_in_editor(self, cli): """ Open code in editor. :param cli: :class:`~prompt_toolkit.interface.CommandLineInterface` instance. """ if self.read_only(): raise EditReadOnlyBuffer() # Write to temporary file descriptor, filename = tem...
Open code in editor. :param cli: :class:`~prompt_toolkit.interface.CommandLineInterface` instance.
def get_min_muO2(self, min_voltage=None, max_voltage=None): """ Minimum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage for a given step max_voltage: The maximum allowable voltage allowable for a given step ...
Minimum critical oxygen chemical potential along path. Args: min_voltage: The minimum allowable voltage for a given step max_voltage: The maximum allowable voltage allowable for a given step Returns: Minimum critical oxygen chemical of all compounds ...
def __tokenize_segments(self): """ tokenizes every RS3 segment (i.e. an RST nucleus or satellite). for each token, a node is added to the graph, as well as an edge from the segment node to the token node. the token node IDs are also added to ``self.tokens``. """ f...
tokenizes every RS3 segment (i.e. an RST nucleus or satellite). for each token, a node is added to the graph, as well as an edge from the segment node to the token node. the token node IDs are also added to ``self.tokens``.
def __updateJobResults(self): """" Check if this is the best model If so: 1) Write it's checkpoint 2) Record this model as the best 3) Delete the previous best's output cache Otherwise: 1) Delete our output cache """ isSaved = False while True: self._isBestMode...
Check if this is the best model If so: 1) Write it's checkpoint 2) Record this model as the best 3) Delete the previous best's output cache Otherwise: 1) Delete our output cache
def doDelete(self, WHAT={}): """This function will perform the command -delete.""" if hasattr(WHAT, '_modified'): self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif type(WHAT) == dict and WHAT.has_key('RECORDID'): self._addDBParam('RECORDID', WHAT['RECORDID']) else:...
This function will perform the command -delete.
def _update_session_count(self, type=0, actutal_session_count=0): ''' update the session/ascp count 0 : set the number of sessions being used to 1 or number specified in transfer config -1: decrement the session count by one 1: set the session count to param value ''...
update the session/ascp count 0 : set the number of sessions being used to 1 or number specified in transfer config -1: decrement the session count by one 1: set the session count to param value
def lats(self, degrees=True): """ Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row ...
Return the latitudes of each row of the gridded data. Usage ----- lats = x.lats([degrees]) Returns ------- lats : ndarray, shape (nlat) 1-D numpy array of size nlat containing the latitude of each row of the gridded data. Parameters ...
def seqs_from_fastacmd(acc_list, blast_db,is_protein=True): """Get dict of description:seq from fastacmd.""" fasta_cmd_res = fasta_cmd_get_seqs(acc_list, blast_db=blast_db, \ is_protein=is_protein) recs = FastaCmdFinder(fasta_cmd_res['StdOut']) result = {} for rec in recs: try: ...
Get dict of description:seq from fastacmd.
def findMeme(inptStr): ''' inptStr may be a string of the following forms: * 'text0 | text1' * 'text0' Returns None if it can't find find a meme from the list given above ''' global meme_id_dict testStr = inptStr testStr.lower() template_id = 0 ''' meme_id_dict[i] is...
inptStr may be a string of the following forms: * 'text0 | text1' * 'text0' Returns None if it can't find find a meme from the list given above
def angle_as_point(self, angle): ''' Converts a given angle in degrees to the point coordinates on the arc's circle. Inverse of point_to_angle. >>> Arc((1, 1), 1, 0, 0, True).angle_as_point(0) array([ 2., 1.]) >>> Arc((1, 1), 1, 0, 0, True).angle_as_point(90) ...
Converts a given angle in degrees to the point coordinates on the arc's circle. Inverse of point_to_angle. >>> Arc((1, 1), 1, 0, 0, True).angle_as_point(0) array([ 2., 1.]) >>> Arc((1, 1), 1, 0, 0, True).angle_as_point(90) array([ 1., 2.]) >>> Arc((1, 1), 1, 0,...
async def create_link_secret(self, label: str) -> None: """ Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the current link secret does not already correspond to the input link secret label. Raise WalletState if wallet is closed, or any other IndyError caus...
Create link secret (a.k.a. master secret) used in proofs by HolderProver, if the current link secret does not already correspond to the input link secret label. Raise WalletState if wallet is closed, or any other IndyError causing failure to set link secret in wallet. :param label: lab...
def _set_toChange(x): """ set variables in list x toChange """ for key in list(x.keys()): self.toChange[key] = True
set variables in list x toChange
def emit(self): """ Serialize response. :return response: Instance of django.http.Response """ # Skip serialize if not isinstance(self.response, SerializedHttpResponse): return self.response self.response.content = self.serialize(self.response.response) ...
Serialize response. :return response: Instance of django.http.Response
def create_service(cluster=None, serviceName=None, taskDefinition=None, loadBalancers=None, desiredCount=None, clientToken=None, role=None, deploymentConfiguration=None, placementConstraints=None, placementStrategy=None): """ Runs and maintains a desired number of tasks from a specified task definition. If the ...
Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount , Amazon ECS spawns another copy of the task in the specified cluster. To update an existing service, see UpdateService . In addition to maintaining the desired count ...
def get_lru_cache(max_size=5): """ Args: max_size (int): References: https://github.com/amitdev/lru-dict CommandLine: python -m utool.util_cache --test-get_lru_cache Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_cache imp...
Args: max_size (int): References: https://github.com/amitdev/lru-dict CommandLine: python -m utool.util_cache --test-get_lru_cache Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_cache import * # NOQA >>> import utool as u...
def __add_class_views(self): """ Include any custom class views on the Sanic JWT Blueprint """ config = self.config if "class_views" in self.kwargs: class_views = self.kwargs.pop("class_views") for route, view in class_views: if issubclass...
Include any custom class views on the Sanic JWT Blueprint
def _get_condition(self, acceptance_prob, a): """ Temporary method to fix issue in numpy 0.12 #852 """ if a == 1: return (acceptance_prob ** a) > (1/(2**a)) else: return (1/(acceptance_prob ** a)) > (2**(-a))
Temporary method to fix issue in numpy 0.12 #852
def get_site_url(): """Returns a URL for current site. :rtype: str|unicode """ site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None) if site_url is None: site_url = SITE_URL or get_site_url_() setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url) return site_url
Returns a URL for current site. :rtype: str|unicode
def outbox(self): """ :class:`Outbox feed <pypump.models.feed.Outbox>` with all :class:`activities <pypump.models.activity.Activity>` sent by the person. Example: >>> for activity in pump.me.outbox[:2]: ... print(activity) ... pypumptest2 unli...
:class:`Outbox feed <pypump.models.feed.Outbox>` with all :class:`activities <pypump.models.activity.Activity>` sent by the person. Example: >>> for activity in pump.me.outbox[:2]: ... print(activity) ... pypumptest2 unliked a comment in reply to a no...
def scrub(value, scrub_text=_keep_whitespace, scrub_number=_scrub_number): """ REMOVE/REPLACE VALUES THAT CAN NOT BE JSON-IZED """ return _scrub(value, set(), [], scrub_text=scrub_text, scrub_number=scrub_number)
REMOVE/REPLACE VALUES THAT CAN NOT BE JSON-IZED
def is_terminal(self) -> bool: """True if the response contained an untagged ``BYE`` response indicating that the session should be terminated. """ for resp in self._untagged: if resp.is_terminal: return True return False
True if the response contained an untagged ``BYE`` response indicating that the session should be terminated.
def require_boss(self, callback): """\ Decorator to ensure that commands only can come from the boss """ def inner(nick, message, channel, *args, **kwargs): if nick != self.boss: return return callback(nick, message, channel, *args, **...
\ Decorator to ensure that commands only can come from the boss
def item_transaction(self, item) -> Transaction: """Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for performance reasons. All changes to the object are delayed until the transaction state exits. This method is thread safe. ...
Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for performance reasons. All changes to the object are delayed until the transaction state exits. This method is thread safe.
def shorthand(self): """Return the 6-tuple (a,b,c,d,e,f) that describes this matrix""" return (self.a, self.b, self.c, self.d, self.e, self.f)
Return the 6-tuple (a,b,c,d,e,f) that describes this matrix
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get('files') ...
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9
def create_new_grading_standard_courses(self, title, course_id, grading_scheme_entry_name, grading_scheme_entry_value): """ Create a new grading standard. Create a new grading standard If grading_scheme_entry arguments are omitted, then a default grading scheme w...
Create a new grading standard. Create a new grading standard If grading_scheme_entry arguments are omitted, then a default grading scheme will be set. The default scheme is as follows: "A" : 94, "A-" : 90, "B+" : 87, "B" : 84...
def cli(env, account_id): """Detail a CDN Account.""" manager = SoftLayer.CDNManager(env.client) account = manager.get_account(account_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', account['id']]) tabl...
Detail a CDN Account.
def create_xref(self): """ Create Class, Method, String and Field crossreferences for all classes in the Analysis. If you are using multiple DEX files, this function must be called when all DEX files are added. If you call the function after every DEX file, the c...
Create Class, Method, String and Field crossreferences for all classes in the Analysis. If you are using multiple DEX files, this function must be called when all DEX files are added. If you call the function after every DEX file, the crossreferences might be wrong!
def get_bench_logger(name=None, short_name=" ", log_to_file=True): """ Return a logger instance for given name. The logger will be a child of the bench logger, so anything that is logged to it, will be also logged to bench logger. If a logger with the given name doesn't already exist, create it usi...
Return a logger instance for given name. The logger will be a child of the bench logger, so anything that is logged to it, will be also logged to bench logger. If a logger with the given name doesn't already exist, create it using the given parameters. :param name: Name of the logger :param short_n...
def get_node_config(self, jid, node=None): """ Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError...
Request the configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The configuration...
def policy_version_exists(policy_name, version_id, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key...
Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile
def node_to_truncated_gr(node, bin_width=0.1): """ Parses truncated GR node to an instance of the :class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD """ # Parse to float dictionary if not all([node.attrib[key] for key in ["minMag", "maxMag", "aValue", "bValue"]]): ...
Parses truncated GR node to an instance of the :class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD
def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog, output_path=None, overwrite=False, output_format='mgz', create_directory=False): ''' calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth map whose keys are filenames and whose...
calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth map whose keys are filenames and whose values are the interpolated property data. Afferent parameters @ output_path The directory into which the atlas files should be written. If not provided or None t...
def _checkBool(inputvalue, description='inputvalue'): """Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError """ _check...
Check that the given inputvalue is a boolean. Args: * inputvalue (boolean): The value to be checked. * description (string): Used in error messages for the checked inputvalue. Raises: TypeError, ValueError
def transfer_multi(self, transfer_list: list, payer_acct: Account, signers: list, gas_limit: int, gas_price: int): """ This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :p...
This interface is used to call the TransferMulti method in ope4 that allow transfer amount of token from multiple from-account to multiple to-account multiple times. :param transfer_list: a parameter list with each item contains three sub-items: base58 encode transaction sender address,...
def create_credit_card(self, *, customer_id, name, document, number, exp_month, exp_year, type, address): """ Creating a credit card (Token) and assigning it to a user. Args: customer_id: Identifier of the client with whom you are going to associate the token with. name...
Creating a credit card (Token) and assigning it to a user. Args: customer_id: Identifier of the client with whom you are going to associate the token with. name: Full name of the credit card holder as shown in the credit card. Alphanumeric. Min: 1 Max: 255. doc...
def getApplicationKeyByProcessId(self, unProcessId, pchAppKeyBuffer, unAppKeyBufferLen): """ Returns the key of the application for the specified Process Id. The buffer should be at least k_unMaxApplicationKeyLength in order to fit the key. """ fn = self.function_table.getAppli...
Returns the key of the application for the specified Process Id. The buffer should be at least k_unMaxApplicationKeyLength in order to fit the key.
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored """ previous_selection = hou.selectedNodes() t...
Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored
def from_soup(self, tag_prof_header, tag_prof_nav): """ Returns the scraped user data from a twitter user page. :param tag_prof_header: captures the left hand part of user info :param tag_prof_nav: captures the upper part of user info :return: Returns a User object with captured...
Returns the scraped user data from a twitter user page. :param tag_prof_header: captures the left hand part of user info :param tag_prof_nav: captures the upper part of user info :return: Returns a User object with captured data via beautifulsoup
def read_analogy_file(filename): """ Read the analogy task test set from a file. """ section = None with open(filename, 'r') as questions_file: for line in questions_file: if line.startswith(':'): section = line[2:].replace('\n', '') continue...
Read the analogy task test set from a file.
def xslt_transformation(xml, template): """ Transform `xml` using XSLT `template`. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. template (str): Filename or XML string. Don't use ``\\n`` in case of filename. R...
Transform `xml` using XSLT `template`. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. template (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: str: Transformed `xml` as string.
def ne_(self, value): ''' Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value`` ''' if isinstance(value, QueryField): return self.__cached_id != value.__cached_id return self.__comparator(...
Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value``
def done(self, fid=0): """Terminates the fitserver.""" self._checkid(fid) self._fitids[fid] = {} self._fitproxy.done(fid)
Terminates the fitserver.
def has_virtualenv(self): """ Returns true if the virtualenv tool is installed. """ with self.settings(warn_only=True): ret = self.run_or_local('which virtualenv').strip() return bool(ret)
Returns true if the virtualenv tool is installed.
def basic_color(code): """ 16 colors supported """ def inner(text, rl=False): """ Every raw_input with color sequences should be called with rl=True to avoid readline messed up the length calculation """ c = code if rl: return "\001\033[%sm\002%s\001\0...
16 colors supported
def replace_pod_security_policy(self, name, body, **kwargs): # noqa: E501 """replace_pod_security_policy # noqa: E501 replace the specified PodSecurityPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_...
replace_pod_security_policy # noqa: E501 replace the specified PodSecurityPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_pod_security_policy(name, body, async_req=Tr...
def removeRootFromName(string): """Helper function to remove /pub, /files from string.""" global garbageRoots for root in garbageRoots: if root in string: string = string[string.find(root) + len(root):] return string
Helper function to remove /pub, /files from string.
def create_dataset(self, name=None, description=None, public=False): """ Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or ...
Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or not the dataset should be public. :type public: bool :return: The newly c...
def merge_dict(d1,d2): """ d1 <-- d2 """ d=copy.deepcopy(d2) for k,v in list(d1.items()): if k not in d: d[k]=v else: if isinstance(v,dict): d[k]=merge_dict(d1[k],d[k]) return d
d1 <-- d2
def get_objects(self): """Returns a list of objects coming from the "uids" request parameter """ # Create a mapping of source ARs for copy uids = self.request.form.get("uids", "") if not uids: # check for the `items` parammeter uids = self.request.form.get...
Returns a list of objects coming from the "uids" request parameter
def setup_components_and_tf_funcs(self, custom_getter=None): """ Creates and stores Network and Distribution objects. Generates and stores all template functions. """ # Create network before super-call, since non-empty internals_spec attribute (for RNN) is required subsequently. ...
Creates and stores Network and Distribution objects. Generates and stores all template functions.
def add(lhs, rhs): """Returns element-wise sum of the input arrays with broadcasting. Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and ``mx.nd.broadcast_plus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, ...
Returns element-wise sum of the input arrays with broadcasting. Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and ``mx.nd.broadcast_plus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are br...
def run(self): """Start json minimizer and exit when all json files were minimized.""" for rel_path in sorted(self.paths): file_path = join(self.data_dir, rel_path) self.minify(file_path) after = self.size_of(self.after_total) before = self.size_of(self.before_to...
Start json minimizer and exit when all json files were minimized.
def pages_breadcrumb(context, page, url='/'): """ Render a breadcrumb like menu. Override ``pages/breadcrumb.html`` if you want to change the design. :param page: the current page :param url: not used anymore """ lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page...
Render a breadcrumb like menu. Override ``pages/breadcrumb.html`` if you want to change the design. :param page: the current page :param url: not used anymore
def _apply_line_rules(lines, commit, rules, line_nr_start): """ Iterates over the lines in a given list of lines and validates a given list of rules against each line """ all_violations = [] line_nr = line_nr_start for line in lines: for rule in rules: violati...
Iterates over the lines in a given list of lines and validates a given list of rules against each line
def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'): 'causes run to be executed in a newly spawned daemon process' global LAST_PGRP_PATH fork = fork or os.fork open(outfile, 'a').close() # TODO: configurable output file if pgrpfile and os.path.exists(pgrpfile): try: cu...
causes run to be executed in a newly spawned daemon process
def finish(self): """ Finish the compressor. This will emit the remaining output data and transition the compressor to a completed state. The compressor cannot be used again after this point, and must be replaced. """ chunks = [] while lib.BrotliEncoderIsFinished(...
Finish the compressor. This will emit the remaining output data and transition the compressor to a completed state. The compressor cannot be used again after this point, and must be replaced.
def eject_medium(self, attachment): """Tells VBoxSVC that the guest has ejected the medium associated with the medium attachment. in attachment of type :class:`IMediumAttachment` The medium attachment where the eject happened. return new_attachment of type :class:`IMediumAt...
Tells VBoxSVC that the guest has ejected the medium associated with the medium attachment. in attachment of type :class:`IMediumAttachment` The medium attachment where the eject happened. return new_attachment of type :class:`IMediumAttachment` A new reference to the me...
def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None): """Prepares section for PDF output. """ import pylatex as pl if case == 'sectionmain': if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage')) with doc.create(pl.Section(s...
Prepares section for PDF output.
def from_aid(cls, aid): """Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID). """ record = json.loads(request(aid, 'aid', 'assay', 'description').read().decode())['PC_AssayContainer'][0] return cls(record)
Retrieve the Assay record for the specified AID. :param int aid: The PubChem Assay Identifier (AID).
def new(params, event_shape=(), validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'IndependentPoisson', [params, event_shape]): params = tf.convert_to_tensor(value=params, name='params') ...
Create the distribution instance from a `params` vector.
def delete(self): """Delete the workspace from FireCloud. Note: This action cannot be undone. Be careful! """ r = fapi.delete_workspace(self.namespace, self.name) fapi._check_response_code(r, 202)
Delete the workspace from FireCloud. Note: This action cannot be undone. Be careful!
def write(text, delay=0, restore_state_after=True, exact=None): """ Sends artificial keyboard events to the OS, simulating the typing of a given text. Characters not available on the keyboard are typed as explicit unicode characters using OS-specific functionality, such as alt+codepoint. To ensure ...
Sends artificial keyboard events to the OS, simulating the typing of a given text. Characters not available on the keyboard are typed as explicit unicode characters using OS-specific functionality, such as alt+codepoint. To ensure text integrity, all currently pressed keys are released before the text ...
def backbone_wu(CIJ, avgdeg): ''' The network backbone contains the dominant connections in the network and may be used to aid network visualization. This function computes the backbone of a given weighted and undirected connection matrix CIJ, using a minimum-spanning-tree based algorithm. Para...
The network backbone contains the dominant connections in the network and may be used to aid network visualization. This function computes the backbone of a given weighted and undirected connection matrix CIJ, using a minimum-spanning-tree based algorithm. Parameters ---------- CIJ : NxN np.nda...
def load_file(client, bucket, data_file): """Tries to load JSON data from S3.""" logger.debug('Loading item from s3. Bucket: {bucket} Key: {key}'.format( bucket=bucket, key=data_file )) # If the file doesn't exist, then return an empty dict: try: data = _get_from_s3(client, ...
Tries to load JSON data from S3.
def raw_on(serial): """ Puts the device into raw mode. """ def flush_to_msg(serial, msg): """Read the rx serial data until we reach an expected message.""" data = serial.read_until(msg) if not data.endswith(msg): if COMMAND_LINE_FLAG: print(data) ...
Puts the device into raw mode.
def metadata(self, name): """Return value and metadata associated with the named value Parameters ---------- name : str name to retrieve. If the name contains '.'s it will be retrieved recursively Raises ------ KeyError if name is not def...
Return value and metadata associated with the named value Parameters ---------- name : str name to retrieve. If the name contains '.'s it will be retrieved recursively Raises ------ KeyError if name is not defined in the ConfigTree
def add(self, defn): """Adds the given Command Definition to this Command Dictionary.""" self[defn.name] = defn self.opcodes[defn._opcode] = defn
Adds the given Command Definition to this Command Dictionary.
def search(cls, name, lookup=[]): """ Search name in all directories specified in lookup. First without, then with common extensions. Return first hit. """ if os.path.isfile(name): return name for spath in lookup: fname = os.path.join(spath, name) if os.path.isfil...
Search name in all directories specified in lookup. First without, then with common extensions. Return first hit.
def __ensure_provisioning_alarm(table_name, key_name): """ Ensure that provisioning alarm threshold is not exceeded :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name """ lookback_window_start = get_table_op...
Ensure that provisioning alarm threshold is not exceeded :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name
def projects_from_metadata(metadata): """Extract the project dependencies from a metadata spec.""" projects = [] for data in metadata: meta = distlib.metadata.Metadata(fileobj=io.StringIO(data)) projects.extend(pypi.just_name(project) for project in meta.run_requires) return frozenset(ma...
Extract the project dependencies from a metadata spec.
def create_message_set(messages, codec=CODEC_NONE, key=None, compresslevel=None): """Create a message set using the given codec. If codec is CODEC_NONE, return a list of raw Kafka messages. Otherwise, return a list containing a single codec-encoded message. """ if codec == CODEC_NONE: retur...
Create a message set using the given codec. If codec is CODEC_NONE, return a list of raw Kafka messages. Otherwise, return a list containing a single codec-encoded message.
def safe_expand(template, mapping): """ Safe string template expansion. Raises an error if the provided substitution mapping has circularities. """ for _ in range(len(mapping) + 1): _template = template template = string.Template(template).safe_substitute(mapping) if template == ...
Safe string template expansion. Raises an error if the provided substitution mapping has circularities.
def from_hyperplane(basis, origin, point, internal = True): """ Returns a Halfspace defined by a list of vectors parallel to the bounding hyperplane. Args: basis: basis for the hyperplane (array with vector rows) origin: point on the hyperplane point:...
Returns a Halfspace defined by a list of vectors parallel to the bounding hyperplane. Args: basis: basis for the hyperplane (array with vector rows) origin: point on the hyperplane point: point not on the hyperplane internal: whether point is inside the h...
def _write_register(self, reg, value): """Write 16 bit value to register.""" self.buf[0] = reg self.buf[1] = (value >> 8) & 0xFF self.buf[2] = value & 0xFF with self.i2c_device as i2c: i2c.write(self.buf)
Write 16 bit value to register.
def runExperiment( self, e ): """Run an experiment over all the points in the parameter space. The results will be stored in the notebook. :param e: the experiment""" # create the parameter space ps = self.parameterSpace() # run the experiment at each point nb ...
Run an experiment over all the points in the parameter space. The results will be stored in the notebook. :param e: the experiment
def get_apps(self, offset=None, limit=None): """ Retrieves apps in this project. :param offset: Pagination offset. :param limit: Pagination limit. :return: Collection object. """ params = {'project': self.id, 'offset': offset, 'limit': limit} ...
Retrieves apps in this project. :param offset: Pagination offset. :param limit: Pagination limit. :return: Collection object.
def diff(img1, img2, x1y1, x2y2): """Compare two images with given alignments. Returns a difference map. ``x1y1``: a tuple ``(x1, y1)`` to specify the top-left corner of the aligned area with respect to ``img1``. ``x2y2``: a tuple ``(x2, y2)`` to specify the top-left corner of the aligned are...
Compare two images with given alignments. Returns a difference map. ``x1y1``: a tuple ``(x1, y1)`` to specify the top-left corner of the aligned area with respect to ``img1``. ``x2y2``: a tuple ``(x2, y2)`` to specify the top-left corner of the aligned area with respect to ``img2``. Either `...
def secretbox_encrypt(data, **kwargs): ''' Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --loc...
Encrypt data using a secret key generated from `nacl.keygen`. The same secret key can be used to decrypt the data using `nacl.secretbox_decrypt`. CLI Examples: .. code-block:: bash salt-run nacl.secretbox_encrypt datatoenc salt-call --local nacl.secretbox_encrypt datatoenc sk_file=/etc/sa...
def get_prefix_dir(archive): """ Often, all files are in a single directory. If so, they'll all have the same prefix. Determine any such prefix. archive is a ZipFile """ names = archive.namelist() shortest_name = sorted(names, key=len)[0] candidate_prefixes = [ shortest_name[:len...
Often, all files are in a single directory. If so, they'll all have the same prefix. Determine any such prefix. archive is a ZipFile
def submit(self, selector, by=By.CSS_SELECTOR): """ Alternative to self.driver.find_element_by_*(SELECTOR).submit() """ if page_utils.is_xpath_selector(selector): by = By.XPATH element = self.wait_for_element_visible( selector, by=by, timeout=settings.SMALL_TIMEOUT) ...
Alternative to self.driver.find_element_by_*(SELECTOR).submit()
def update_keyboard_mapping(conn, e): """ Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the curren...
Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing of the current keysym table. Indeed, xpybutil will do this for you automatically. Moreover, if something is changed that affects the current keygrabs, xpybutil will initiate a regrab wi...
def _encode_time(self, value): """Convert datetime to base64 or plaintext string""" if self._kp.version >= (4, 0): diff_seconds = int( ( self._datetime_to_utc(value) - datetime( year=1, m...
Convert datetime to base64 or plaintext string
def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, ...
Show the extent selector widget for defining analysis extents.
def _fake_setqualifier(self, namespace, **params): """ Implements a server responder for :meth:`pywbem.WBEMConnection.SetQualifier`. Create or modify a qualifier declaration in the local repository of this class. This method will create a new namespace for the qualifier ...
Implements a server responder for :meth:`pywbem.WBEMConnection.SetQualifier`. Create or modify a qualifier declaration in the local repository of this class. This method will create a new namespace for the qualifier if none is defined. Raises: CIMError: CIM_ERR_IN...
def text_has_changed(self, text): """Line edit's text has changed""" text = to_text_string(text) if text: self.lineno = int(text) else: self.lineno = None
Line edit's text has changed
def dec(self,*args,**kwargs): """ NAME: dec PURPOSE: return the declination INPUT: t - (optional) time at which to get dec (can be Quantity) obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity) (defa...
NAME: dec PURPOSE: return the declination INPUT: t - (optional) time at which to get dec (can be Quantity) obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity) (default=[8.0,0.,0.]) OR Orbit object that corresponds ...
def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: ...
Reload Remind files if the mtime is newer
def store(self, image, file): """Stores the actual data ``file`` of the given ``image``. :: with open(imagefile, 'rb') as f: store.store(image, f) :param image: the image to store its actual data file :type image: :class:`sqlalchemy_imageattach.entity.Image`...
Stores the actual data ``file`` of the given ``image``. :: with open(imagefile, 'rb') as f: store.store(image, f) :param image: the image to store its actual data file :type image: :class:`sqlalchemy_imageattach.entity.Image` :param file: the image file to p...
def update(self): """Update cameras and motion settings with latest from API.""" cameras = self._api.camera_list() self._cameras_by_id = {v.camera_id: v for i, v in enumerate(cameras)} motion_settings = [] for camera_id in self._cameras_by_id.keys(): motion_setting =...
Update cameras and motion settings with latest from API.
def updateQueue(destinationRoot, queueDict, debug=False): """ With a dictionary that represents a queue entry, update the queue entry with the values """ attrDict = bagatom.AttrDict(queueDict) url = urlparse.urljoin(destinationRoot, "APP/queue/" + attrDict.ark + "/") queueXML = bagatom.queu...
With a dictionary that represents a queue entry, update the queue entry with the values
def get_board(self, **query_params): ''' Get board information for this card. Returns a Board object. Returns: Board: The board this card is attached to ''' board_json = self.get_board_json(self.base_uri, query_params=query_pa...
Get board information for this card. Returns a Board object. Returns: Board: The board this card is attached to
def numpy_random_seed(seed=42): """ sets the random seed of numpy within the context. Example ------- >>> import numpy as np >>> with numpy_random_seed(seed=0): ... np.random.randint(1000) 684 """ old_state = np.random.get_state() np.random.seed(seed) try: yield ...
sets the random seed of numpy within the context. Example ------- >>> import numpy as np >>> with numpy_random_seed(seed=0): ... np.random.randint(1000) 684
def dispatch_with_args(self, body, argMap): 'Perform callback dispatching, with enhanced arguments and recording of response' inputs = body.get('inputs', []) state = body.get('state', []) output = body['output'] try: output_id = output['id'] output_proper...
Perform callback dispatching, with enhanced arguments and recording of response
def get_vpc_overview(con, vpc_id, region_name): """ Retrieve information for the specified VPC. If no VPC ID was specified then just pick the first VPC we find. Returns a dict with the VPC's zones, subnets, route tables and instances. """ logging.debug("Retrieving information for VPC '%s'...
Retrieve information for the specified VPC. If no VPC ID was specified then just pick the first VPC we find. Returns a dict with the VPC's zones, subnets, route tables and instances.