code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def destroy(self): """ Cleanup the activty lifecycle listener """ if self.widget: self.set_active(False) super(AndroidBarcodeView, self).destroy()
Cleanup the activty lifecycle listener
def create_context_plot(ra, dec, name="Your object"): """Creates a K2FootprintPlot showing a given position in context with respect to the campaigns.""" plot = K2FootprintPlot() plot.plot_galactic() plot.plot_ecliptic() for c in range(0, 20): plot.plot_campaign_outline(c, facecolor="#666...
Creates a K2FootprintPlot showing a given position in context with respect to the campaigns.
def perr(self, *args, **kwargs): """ Console to STERR """ kwargs['file'] = self.err self.print(*args, **kwargs) sys.stderr.flush()
Console to STERR
def build_sanitiser_node_dict( cfg, sinks_in_file ): """Build a dict of string -> TriggerNode pairs, where the string is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser. Args: cfg(CFG): cfg to traverse. sinks_in_file(list[TriggerNode]): list of TriggerNodes co...
Build a dict of string -> TriggerNode pairs, where the string is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser. Args: cfg(CFG): cfg to traverse. sinks_in_file(list[TriggerNode]): list of TriggerNodes containing the sinks in the ...
def rm_special(user, cmd, special=None, identifier=None): ''' Remove a special cron job for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_special root /usr/bin/foo ''' lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['special']...
Remove a special cron job for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_special root /usr/bin/foo
def send_to_default_exchange(self, sess_id, message=None): """ Send messages through RabbitMQ's default exchange, which will be delivered through routing_key (sess_id). This method only used for un-authenticated users, i.e. login process. Args: sess_id string: Sessi...
Send messages through RabbitMQ's default exchange, which will be delivered through routing_key (sess_id). This method only used for un-authenticated users, i.e. login process. Args: sess_id string: Session id message dict: Message object.
def replace_drive_enclosure(self, information): """ When a drive enclosure has been physically replaced, initiate the replacement operation that enables the new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires specification of both the ser...
When a drive enclosure has been physically replaced, initiate the replacement operation that enables the new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires specification of both the serial numbers of the original drive enclosure and its replacement to b...
def get(issue_id, issue_type_id): """Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None """ return db.Issue.find_one( ...
Return issue by ID Args: issue_id (str): Unique Issue identifier issue_type_id (str): Type of issue to get Returns: :obj:`Issue`: Returns Issue object if found, else None
def get_tan_media(self, media_type = TANMediaType2.ALL, media_class = TANMediaClass4.ALL): """Get information about TAN lists/generators. Returns tuple of fints.formals.TANUsageOption and a list of fints.formals.TANMedia4 or fints.formals.TANMedia5 objects.""" with self._get_dialog() as dialog...
Get information about TAN lists/generators. Returns tuple of fints.formals.TANUsageOption and a list of fints.formals.TANMedia4 or fints.formals.TANMedia5 objects.
def get_previous_tag(cls, el): """Get previous sibling tag.""" sibling = el.previous_sibling while not cls.is_tag(sibling) and sibling is not None: sibling = sibling.previous_sibling return sibling
Get previous sibling tag.
def File(self, path): """Returns a reference to a file with a given path on client's VFS.""" return vfs.FileRef( client_id=self.client_id, path=path, context=self._context)
Returns a reference to a file with a given path on client's VFS.
def num_compositions(m, n): """ The total number of m-part compositions of n, which is equal to (n+m-1) choose (m-1). Parameters ---------- m : scalar(int) Number of parts of composition. n : scalar(int) Integer to decompose. Returns ------- scalar(int) ...
The total number of m-part compositions of n, which is equal to (n+m-1) choose (m-1). Parameters ---------- m : scalar(int) Number of parts of composition. n : scalar(int) Integer to decompose. Returns ------- scalar(int) Total number of m-part compositions of ...
def _get_win_argv(): """Returns a unicode argv under Windows and standard sys.argv otherwise Returns: List[`fsnative`] """ assert is_win argc = ctypes.c_int() try: argv = winapi.CommandLineToArgvW( winapi.GetCommandLineW(), ctypes.byref(argc)) except WindowsErr...
Returns a unicode argv under Windows and standard sys.argv otherwise Returns: List[`fsnative`]
def backup_file(*, file, host): """ Backup a file on S3 :param file: full path to the file to be backed up :param host: this will be used to locate the file on S3 :raises TypeError: if an argument in kwargs does not have the type expected :raises ValueError: if an argument within kwargs has an ...
Backup a file on S3 :param file: full path to the file to be backed up :param host: this will be used to locate the file on S3 :raises TypeError: if an argument in kwargs does not have the type expected :raises ValueError: if an argument within kwargs has an invalid value
def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('setup') setup_parser.add_argument('-e', '--email', dest='email', required=True, help='Email of the Google user.', type=str) setup_parse...
Run the core.
def getTemplates(fnames, blend=True): """ Process all headers to produce a set of combined headers that follows the rules defined by each instrument. """ if not blend: newhdrs = blendheaders.getSingleTemplate(fnames[0]) newtab = None else: # apply rules to create final ...
Process all headers to produce a set of combined headers that follows the rules defined by each instrument.
def make_lat_lons(cvects): """ Convert from directional cosines to latitidue and longitude Parameters ---------- cvects : directional cosine (i.e., x,y,z component) values returns (np.ndarray(2,nsrc)) with the directional cosine (i.e., x,y,z component) values """ lats = np.degrees(np.arcsi...
Convert from directional cosines to latitidue and longitude Parameters ---------- cvects : directional cosine (i.e., x,y,z component) values returns (np.ndarray(2,nsrc)) with the directional cosine (i.e., x,y,z component) values
def import_sqlite(db_file, older_than=None, **kwargs): """Reads the content of the database file and returns imported data.""" conn = _open_sqlite(db_file) cur = conn.cursor() # get rows that were not exported yet select = "SELECT * FROM testcases WHERE exported != 'yes'" if older_than: ...
Reads the content of the database file and returns imported data.
def _backspace(self): """Erase the last character in the snippet command.""" if self.command == ':': return logger.log(5, "Snippet keystroke `Backspace`.") self.command = self.command[:-1]
Erase the last character in the snippet command.
def triple(self): """ This module's target "triple" specification, as a string. """ # LLVMGetTarget() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetTarget(self, outmsg) return str(outmsg)
This module's target "triple" specification, as a string.
def binary_classification_metrics(y_true, y_pred, y_prob): #TODO: update description """classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. ...
classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. y_prob : array-like Predicted probabilities, as returned by a classifier. Retu...
def load_configs(self): """Load configurations for all widgets in General, Scrolling and Appearance tabs from dconf. """ self._load_default_shell_settings() # restore tabs startup value = self.settings.general.get_boolean('restore-tabs-startup') self.get_widget('...
Load configurations for all widgets in General, Scrolling and Appearance tabs from dconf.
def _get_calculated_value(self, value): """ Get's the final value of the field and runs the lambda functions recursively until a final value is derived. :param value: The value to calculate/expand :return: The final value """ if isinstance(value, types.LambdaType...
Get's the final value of the field and runs the lambda functions recursively until a final value is derived. :param value: The value to calculate/expand :return: The final value
def make_seekable(fileobj): """ If the file-object is not seekable, return ArchiveTemp of the fileobject, otherwise return the file-object itself """ if sys.version_info < (3, 0) and isinstance(fileobj, file): filename = fileobj.name fileobj = io.FileIO(fileobj.fileno(), closefd=Fal...
If the file-object is not seekable, return ArchiveTemp of the fileobject, otherwise return the file-object itself
def get_list(self, section, option): """ This allows for loading of Pyramid list style configuration options: [foo] bar = baz qux zap ``get_list('foo', 'bar')`` returns ``['baz', 'qux', 'zap']`` :param str section: ...
This allows for loading of Pyramid list style configuration options: [foo] bar = baz qux zap ``get_list('foo', 'bar')`` returns ``['baz', 'qux', 'zap']`` :param str section: The section to read. :param str option: ...
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
Formula for computing the current backoff :rtype: float
def diff_list(self, list1, list2): """Extracts differences between lists. For debug purposes""" for key in list1: if key in list2 and list2[key] != list1[key]: print key elif key not in list2: print key
Extracts differences between lists. For debug purposes
def warp(self, warp_matrix, img, iflag=cv2.INTER_NEAREST): """ Function to warp input image given an estimated 2D linear transformation :param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images :type warp_matrix: ndarray :param img: Image to be warped with estimated...
Function to warp input image given an estimated 2D linear transformation :param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images :type warp_matrix: ndarray :param img: Image to be warped with estimated transformation :type img: ndarray :param iflag: Interp...
def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2014.1.0 Ensure the value is present in the list-type grain. Note: If the grain that is provided in ``name`` is not present on the system, this new grain will be created with the corresponding provided value. ...
.. versionadded:: 2014.1.0 Ensure the value is present in the list-type grain. Note: If the grain that is provided in ``name`` is not present on the system, this new grain will be created with the corresponding provided value. name The grain name. value The value is present in the...
def get_upgrade(self, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged. """ return self._get_connection(using).indices.get_upgrade(index=self._name, **...
Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_upgrade`` unchanged.
def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer2dAffine'): """Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__. Parameters ---------- U : list of float tensor of inputs [batch, height, width, num_c...
Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__. Parameters ---------- U : list of float tensor of inputs [batch, height, width, num_channels] thetas : list of float a set of transformations for each input [batch,...
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name ...
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path o...
def condition(condition=None, statement=None, _else=None, **kwargs): """ Run an statement if input condition is checked and return statement result. :param condition: condition to check. :type condition: str or dict :param statement: statement to process if condition is checked. :type statement...
Run an statement if input condition is checked and return statement result. :param condition: condition to check. :type condition: str or dict :param statement: statement to process if condition is checked. :type statement: str or dict :param _else: else statement. :type _else: str or dict ...
def patch(self, item, byte_order=BYTEORDER): """ Returns a memory :class:`Patch` for the given *item* that shall be patched in the `data source`. :param item: item to patch. :param byte_order: encoding :class:`Byteorder` for the item. :type byte_order: :class:`Byteorder`, :class...
Returns a memory :class:`Patch` for the given *item* that shall be patched in the `data source`. :param item: item to patch. :param byte_order: encoding :class:`Byteorder` for the item. :type byte_order: :class:`Byteorder`, :class:`str`
def modify_module(channel, module_name, module_state): """ Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current...
Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed
def create_message(self): """Returns a message body to send in this email. Should be from email.mime.*""" body = dedent("""\ Received exception {exception} on {queue} from worker {worker}: {traceback} Payload: {payload} """).format(exception=self._exception, ...
Returns a message body to send in this email. Should be from email.mime.*
def set_encoding(self, encoding): """! @brief Change clusters encoding to specified type (index list, object list, labeling). @param[in] encoding (type_encoding): New type of clusters representation. """ if(encoding == self.__type_representation): ...
! @brief Change clusters encoding to specified type (index list, object list, labeling). @param[in] encoding (type_encoding): New type of clusters representation.
def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error re...
Parse API error responses and raise appropriate exceptions.
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ ...
Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted.
def waliki_box(context, slug, show_edit=True, *args, **kwargs): """ A templatetag to render a wiki page content as a box in any webpage, and allow rapid edition if you have permission. It's inspired in `django-boxes`_ .. _django-boxes: https://github.com/eldarion/django-boxes """ request ...
A templatetag to render a wiki page content as a box in any webpage, and allow rapid edition if you have permission. It's inspired in `django-boxes`_ .. _django-boxes: https://github.com/eldarion/django-boxes
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be le...
Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be less than batch_size, in this case only fi...
def deserialize_assign(self, workflow, start_node): """ Reads the "pre-assign" or "post-assign" tag from the given node. start_node -- the xml node (xml.dom.minidom.Node) """ name = start_node.getAttribute('name') attrib = start_node.getAttribute('field') value =...
Reads the "pre-assign" or "post-assign" tag from the given node. start_node -- the xml node (xml.dom.minidom.Node)
def run(self): """Run the log monitor. This will query Redis once every second to check if there are new log files to monitor. It will also store those log files in Redis. """ while True: self.update_log_filenames() self.open_closed_files() an...
Run the log monitor. This will query Redis once every second to check if there are new log files to monitor. It will also store those log files in Redis.
def fasta_files_equal(seq_file1, seq_file2): """Check equality of a FASTA file to another FASTA file Args: seq_file1: Path to a FASTA file seq_file2: Path to another FASTA file Returns: bool: If the sequences are the same """ # Load already set representative sequence ...
Check equality of a FASTA file to another FASTA file Args: seq_file1: Path to a FASTA file seq_file2: Path to another FASTA file Returns: bool: If the sequences are the same
def ks(self, num_ngrams): # type (int) -> [int] """ Provide a k for each ngram in the field value. :param num_ngrams: number of ngrams in the field value :return: [ k, ... ] a k value for each of num_ngrams such that the sum is exactly num_bits """ if self.num_bit...
Provide a k for each ngram in the field value. :param num_ngrams: number of ngrams in the field value :return: [ k, ... ] a k value for each of num_ngrams such that the sum is exactly num_bits
def _add_in_streams(self, bolt): """Adds inputs to a given protobuf Bolt message""" if self.inputs is None: return # sanitize inputs and get a map <GlobalStreamId -> Grouping> input_dict = self._sanitize_inputs() for global_streamid, gtype in input_dict.items(): in_stream = bolt.inputs....
Adds inputs to a given protobuf Bolt message
def unlocked(self): """ Is the store unlocked so that I can decrypt the content? """ if self.password is not None: return bool(self.password) else: if ( "UNLOCK" in os.environ and os.environ["UNLOCK"] and self.config...
Is the store unlocked so that I can decrypt the content?
def addConstraint(self, constraint, variables=None): """ Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolu...
Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolutions() >>> @param constraint: Constraint to be included...
def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None): """ Plots output of compute_sector_exposures as line graphs Parameters ---------- net_exposures : arrays Arrays of net sector exposures (output of compute_sector_exposures). sector_dict : dict or OrderedDict ...
Plots output of compute_sector_exposures as line graphs Parameters ---------- net_exposures : arrays Arrays of net sector exposures (output of compute_sector_exposures). sector_dict : dict or OrderedDict Dictionary of all sectors - See full description in compute_sector_exposur...
def _check_hint_bounds(self, ds): ''' Checks for variables ending with _bounds, if they are not cell methods, make the recommendation :param netCDF4.Dataset ds: An open netCDF dataset :rtype: list :return: List of results ''' ret_val = [] boundary...
Checks for variables ending with _bounds, if they are not cell methods, make the recommendation :param netCDF4.Dataset ds: An open netCDF dataset :rtype: list :return: List of results
def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str: """ Emit all associations for a focus class. If none are specified, all classes are generated @param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is s...
Emit all associations for a focus class. If none are specified, all classes are generated @param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is specifically requested) @return: YUML representation of the association
def _process_state_final_run(self, job_record): """method takes care of processing job records in STATE_FINAL_RUN state""" uow = self.uow_dao.get_one(job_record.related_unit_of_work) if uow.is_processed: self.update_job(job_record, uow, job.STATE_PROCESSED) elif uow.is_noop: ...
method takes care of processing job records in STATE_FINAL_RUN state
def merge(directory, message, branch_label, rev_id, revisions): """Merge two revisions together, creating a new revision file""" _merge(directory, revisions, message, branch_label, rev_id)
Merge two revisions together, creating a new revision file
def get_core_api(): """ Create instance of Core V1 API of kubernetes: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md :return: instance of client """ global core_api if core_api is None: config.load_kube_config() if API_KEY is not None: ...
Create instance of Core V1 API of kubernetes: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md :return: instance of client
def collect_results(self, data_values): """Receive the data from the consumers polled and process it. :param dict data_values: The poll data returned from the consumer :type data_values: dict """ self.last_poll_results['timestamp'] = self.poll_data['timestamp'] # Get t...
Receive the data from the consumers polled and process it. :param dict data_values: The poll data returned from the consumer :type data_values: dict
def read(filename): """Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data. :returns point_data: Point data read from file. :type point_data: dict :returns field_data: Field data read from file. :t...
Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data. :returns point_data: Point data read from file. :type point_data: dict :returns field_data: Field data read from file. :type field_data: dict
def purge_queue(self, name): """Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": "org.apache.qpid.br...
Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties
def process_point_value(cls, command_type, command, index, op_type): """ A PointValue was received from the Master. Process its payload. :param command_type: (string) Either 'Select' or 'Operate'. :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputIn...
A PointValue was received from the Master. Process its payload. :param command_type: (string) Either 'Select' or 'Operate'. :param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputInt16, etc.). :param index: (integer) DNP3 index of the payload's data definition. ...
def harvest_openaire_projects(source=None, setspec=None): """Harvest grants from OpenAIRE and store as authority records.""" loader = LocalOAIRELoader(source=source) if source \ else RemoteOAIRELoader(setspec=setspec) for grant_json in loader.iter_grants(): register_grant.delay(grant_json)
Harvest grants from OpenAIRE and store as authority records.
def evaluate(self, dataset): """ Evaluates the model on a test dataset. :param dataset: Test dataset to evaluate model on, where dataset is an instance of :py:class:`pyspark.sql.DataFrame` """ if not isinstance(dataset, DataFrame): raise ValueErro...
Evaluates the model on a test dataset. :param dataset: Test dataset to evaluate model on, where dataset is an instance of :py:class:`pyspark.sql.DataFrame`
def fileImport(filepath, ignore=None): """ Imports the module located at the given filepath. :param filepath | <str> ignore | [<str>, ..] || None :return <module> || None """ basepath, package = EnvManager.packageSpli...
Imports the module located at the given filepath. :param filepath | <str> ignore | [<str>, ..] || None :return <module> || None
def get_parent_element(self): """Signatures and Audit elements share sub-elements, we need to know which to set attributes on""" return {AUDIT_REF_STATE: self.context.audit_record, SIGNATURE_REF_STATE: self.context.signature}[self.ref_state]
Signatures and Audit elements share sub-elements, we need to know which to set attributes on
def path(self): """Getter property for the URL path to this Task. :rtype: string :returns: The URL path to this task. """ if not self.id: raise ValueError('Cannot determine path without a task id.') return self.path_helper(self.taskqueue.path, self.id)
Getter property for the URL path to this Task. :rtype: string :returns: The URL path to this task.
def _Resample(self, stats, target_size): """Resamples the stats to have a specific number of data points.""" t_first = stats[0][0] t_last = stats[-1][0] interval = (t_last - t_first) / target_size result = [] current_t = t_first current_v = 0 i = 0 while i < len(stats): stat_...
Resamples the stats to have a specific number of data points.
def console_blit( src: tcod.console.Console, x: int, y: int, w: int, h: int, dst: tcod.console.Console, xdst: int, ydst: int, ffade: float = 1.0, bfade: float = 1.0, ) -> None: """Blit the console src from x,y,w,h to console dst at xdst,ydst. .. deprecated:: 8.5 ...
Blit the console src from x,y,w,h to console dst at xdst,ydst. .. deprecated:: 8.5 Call the :any:`Console.blit` method instead.
def service_list(auth=None, **kwargs): ''' List services CLI Example: .. code-block:: bash salt '*' keystoneng.service_list ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.list_services(**kwargs)
List services CLI Example: .. code-block:: bash salt '*' keystoneng.service_list
def create_key(self, title, key): """Create a new key for the authenticated user. :param str title: (required), key title :param key: (required), actual key contents, accepts path as a string or file-like object :returns: :class:`Key <github3.users.Key>` """ ...
Create a new key for the authenticated user. :param str title: (required), key title :param key: (required), actual key contents, accepts path as a string or file-like object :returns: :class:`Key <github3.users.Key>`
def get_zip_data(self, filename): """Get data from `filename` if it is a zip file path. Returns the string data read from the zip file, or None if no zip file could be found or `filename` isn't in it. The data returned will be an empty string if the file is empty. """ ...
Get data from `filename` if it is a zip file path. Returns the string data read from the zip file, or None if no zip file could be found or `filename` isn't in it. The data returned will be an empty string if the file is empty.
def check_unique_tokens(sender, instance, **kwargs): """ Ensures that mobile and email tokens are unique or tries once more to generate. """ if isinstance(instance, CallbackToken): if CallbackToken.objects.filter(key=instance.key, is_active=True).exists(): instance.key = generate_num...
Ensures that mobile and email tokens are unique or tries once more to generate.
def save_plain_image_as_file(self, filepath, format='png', quality=90): """Used for generating thumbnails. Does not include overlaid graphics. """ pixbuf = self.get_plain_image_as_pixbuf() options, values = [], [] if format == 'jpeg': options.append('quality'...
Used for generating thumbnails. Does not include overlaid graphics.
def parse_wiki_terms(doc): '''who needs an html parser. fragile hax, but checks the result at the end''' results = [] last3 = ['', '', ''] header = True for line in doc.split('\n'): last3.pop(0) last3.append(line.strip()) if all(s.startswith('<td>') and not s == '<td></td>' f...
who needs an html parser. fragile hax, but checks the result at the end
def analyse(file, length=None): """Analyse application layer packets. Keyword arguments: * file -- bytes or file-like object, packet to be analysed * length -- int, length of the analysing packet Returns: * Analysis -- an Analysis object from `pcapkit.analyser` """ if isin...
Analyse application layer packets. Keyword arguments: * file -- bytes or file-like object, packet to be analysed * length -- int, length of the analysing packet Returns: * Analysis -- an Analysis object from `pcapkit.analyser`
def create_session(self): """Create a session. First we look in self.key_file for a path to a json file with the credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'. Next we look at self.profile for a profile name and try to use the Session call to automat...
Create a session. First we look in self.key_file for a path to a json file with the credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'. Next we look at self.profile for a profile name and try to use the Session call to automatically pick up the keys for the profi...
def jdbc(self, url, table, mode=None, properties=None): """Saves the content of the :class:`DataFrame` to an external database table via JDBC. .. note:: Don't create too many partitions in parallel on a large cluster; otherwise Spark might crash your external database systems. :par...
Saves the content of the :class:`DataFrame` to an external database table via JDBC. .. note:: Don't create too many partitions in parallel on a large cluster; otherwise Spark might crash your external database systems. :param url: a JDBC URL of the form ``jdbc:subprotocol:subname`` ...
def fetch(clobber=False): """ Downloads the Marshall et al. (2006) dust map, which is based on 2MASS stellar photometry. Args: clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be overwritten, even if it appears to match. If ``False`` (the default), :o...
Downloads the Marshall et al. (2006) dust map, which is based on 2MASS stellar photometry. Args: clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be overwritten, even if it appears to match. If ``False`` (the default), :obj:`fetch()` will attempt to determine...
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_n...
r"""Big 1-layer LSTMP language model. Both embedding and projection size are 512. Hidden size is 2048. Parameters ---------- dataset_name : str or None, default None The dataset name on which the pre-trained model is trained. Options are 'gbw'. If specified, then the returned vocabular...
def t_php_START_HEREDOC(t): r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n' t.lexer.lineno += t.value.count("\n") t.lexer.push_state('heredoc') t.lexer.heredoc_label = t.lexer.lexmatch.group('label') return t
r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n
def httpapi_request(client, **params) -> 'Response': """Send a request to AniDB HTTP API. https://wiki.anidb.net/w/HTTP_API_Definition """ return requests.get( _HTTPAPI, params={ 'client': client.name, 'clientver': client.version, 'protover': 1, ...
Send a request to AniDB HTTP API. https://wiki.anidb.net/w/HTTP_API_Definition
def posttrans_hook(conduit): """ Hook after the package installation transaction. :param conduit: :return: """ # Integrate Yum with Salt if 'SALT_RUNNING' not in os.environ: with open(CK_PATH, 'w') as ck_fh: ck_fh.write('{chksum} {mtime}\n'.format(chksum=_get_checksum(),...
Hook after the package installation transaction. :param conduit: :return:
def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log('Specify the role with --role') return if ctx.obj['username'] is None: log('Specify the username with --username') return change_user = ctx.obj['db'].objectmodels['user'].find_one({ ...
Grant a role to an existing user
def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.json()
Retrieve the debug information from the charmstore.
def run(items, background=None): """Detect copy number variations from batched set of samples using WHAM. """ if not background: background = [] background_bams = [] paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items) if paired: inputs = [paired.tumor_data] ...
Detect copy number variations from batched set of samples using WHAM.
def load_env_from_file(filename): """ Read an env file into a collection of (name, value) tuples. """ if not os.path.exists(filename): raise FileNotFoundError("Environment file {} does not exist.".format(filename)) with open(filename) as f: for lineno, line in enumerate(f): ...
Read an env file into a collection of (name, value) tuples.
def buildFileListOrig(input, output=None, ivmlist=None, wcskey=None, updatewcs=True, **workinplace): """ Builds a file list which has undergone various instrument-specific checks for input to MultiDrizzle, including splitting STIS associations. Compared to buildFileList, this version ret...
Builds a file list which has undergone various instrument-specific checks for input to MultiDrizzle, including splitting STIS associations. Compared to buildFileList, this version returns the list of the original file names as specified by the user (e.g., before GEIS->MEF, or WAIVER FITS->MEF conversion...
def _build_date_header_string(self, date_value): """Gets the date_value (may be None, basestring, float or datetime.datetime instance) and returns a valid date string as per RFC 2822.""" if isinstance(date_value, datetime): date_value = time.mktime(date_value.timetuple()) if not isinstance(date_value, base...
Gets the date_value (may be None, basestring, float or datetime.datetime instance) and returns a valid date string as per RFC 2822.
def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection], condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]: # pylint: disable=too-many-locals """ Represent function arguments and frame values in the error message on contrac...
Represent function arguments and frame values in the error message on contract breach. :param condition: condition function of the contract :param lambda_inspection: inspected lambda AST node corresponding to the condition function (None if the condition was not given as a lambda function) ...
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj): """One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute a...
One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute assigned to `self._cassette`. This behavior is necessary to properly support nest...
def copy_dir( src_fs, # type: Union[FS, Text] src_path, # type: Text dst_fs, # type: Union[FS, Text] dst_path, # type: Text walker=None, # type: Optional[Walker] on_copy=None, # type: Optional[_OnCopy] workers=0, # type: int ): # type: (...) -> None """Copy a directory from on...
Copy a directory from one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (instance or URL). src_path (str): Path to a directory on the source filesystem. dst_fs (FS or str): Destination filesystem (instance or URL). dst_path (str): Path to a directory on the...
def inverse_transform(self, X): """Transform data back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples in the number of samples ...
Transform data back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples in the number of samples and n_components is the number of componen...
def _sumterm(lexer): """Return a sum term expresssion.""" xorterm = _xorterm(lexer) sumterm_prime = _sumterm_prime(lexer) if sumterm_prime is None: return xorterm else: return ('or', xorterm, sumterm_prime)
Return a sum term expresssion.
def consensus(aln, weights=None, gap_threshold=0.5, simple=False, trim_ends=True): """Get the consensus of an alignment, as a string. Emit gap characters for majority-gap columns; apply various strategies to choose the consensus amino acid type for the remaining columns. Parameters ---------- ...
Get the consensus of an alignment, as a string. Emit gap characters for majority-gap columns; apply various strategies to choose the consensus amino acid type for the remaining columns. Parameters ---------- simple : bool If True, use simple plurality to determine the consensus amino acid...
def save(self): """ Save the current instance to the DB """ with rconnect() as conn: try: self.validate() except ValidationError as e: log.warn(e.messages) raise except ModelValidationError as e: ...
Save the current instance to the DB
def scan_dir(self, path): r"""Scan a directory on disk for color table files and add them to the registry. Parameters ---------- path : str The path to the directory with the color tables """ for fname in glob.glob(os.path.join(path, '*' + TABLE_EXT)): ...
r"""Scan a directory on disk for color table files and add them to the registry. Parameters ---------- path : str The path to the directory with the color tables
def setEmergencyDecel(self, vehID, decel): """setEmergencyDecel(string, double) -> None Sets the maximal physically possible deceleration in m/s^2 for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_EMERGENCY_DECEL, vehID, decel)
setEmergencyDecel(string, double) -> None Sets the maximal physically possible deceleration in m/s^2 for this vehicle.
def index(): """Generate a list of all crawlers, alphabetically, with op counts.""" crawlers = [] for crawler in manager: data = Event.get_counts(crawler) data['last_active'] = crawler.last_run data['total_ops'] = crawler.op_count data['running'] = crawler.is_running ...
Generate a list of all crawlers, alphabetically, with op counts.
def triggered_token(self) -> 'CancelToken': """ Return the token which was triggered. The returned token may be this token or one that it was chained with. """ if self._triggered.is_set(): return self for token in self._chain: if token.triggered: ...
Return the token which was triggered. The returned token may be this token or one that it was chained with.
def cli(ctx): """PyHardLinkBackup""" click.secho("\nPyHardLinkBackup v%s\n" % PyHardLinkBackup.__version__, bg="blue", fg="white", bold=True)
PyHardLinkBackup
def _get_django_queryset(self): """Return Django QuerySet with prefetches properly configured.""" prefetches = [] for field, fprefetch in self.prefetches.items(): has_query = hasattr(fprefetch, 'query') qs = fprefetch.query.queryset if has_query else None pre...
Return Django QuerySet with prefetches properly configured.
def main(): """ Phenologs """ parser = argparse.ArgumentParser(description='Phenologs' """ By default, ontologies are cached locally and synced from a remote sparql endpoint ...
Phenologs
def timescales_from_eigenvalues(evals, tau=1): r"""Compute implied time scales from given eigenvalues Parameters ---------- evals : eigenvalues tau : lag time Returns ------- ts : ndarray The implied time scales to the given eigenvalues, in the same order. """ """Chec...
r"""Compute implied time scales from given eigenvalues Parameters ---------- evals : eigenvalues tau : lag time Returns ------- ts : ndarray The implied time scales to the given eigenvalues, in the same order.