code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _create_client_impl(self, api_version): """ Creates the client implementation corresponding to the specifeid api_version. :param api_version: :return: """ if api_version == v7_0_VERSION: from azure.keyvault.v7_0 import KeyVaultClient as ImplClient ...
Creates the client implementation corresponding to the specifeid api_version. :param api_version: :return:
def to_array(self): """ Serializes this InputMediaDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputMediaDocument, self).to_array() # 'type' given by superclass # 'media' given by superclass ...
Serializes this InputMediaDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict
def vad(self, location=1, normalize=True, activity_threshold=7.0, min_activity_duration=0.25, initial_search_buffer=1.0, max_gap=0.25, initial_pad=0.0): '''Voice Activity Detector. Attempts to trim silence and quiet background sounds from the ends of recordings of speech. The alg...
Voice Activity Detector. Attempts to trim silence and quiet background sounds from the ends of recordings of speech. The algorithm currently uses a simple cepstral power measurement to detect voice, so may be fooled by other things, especially music. The effect can trim only from the fr...
def run_helper_process(python_file, metadata_queue, quit_event, options): """ :param python_file: The absolute path of a python file containing the helper process that should be run. It must define a class which is a subclass of BotHelperProcess. :param metadata_queue: A queue from which the helper proc...
:param python_file: The absolute path of a python file containing the helper process that should be run. It must define a class which is a subclass of BotHelperProcess. :param metadata_queue: A queue from which the helper process will read AgentMetadata updates. :param quit_event: An event which should be s...
def read_segment(self, segment): """Read one memory segment (128 byte). """ log.debug("read segment {0}".format(segment)) if segment < 0 or segment > 15: raise ValueError("invalid segment number") cmd = "\x10" + chr(segment << 4) + 8 * chr(0) + self.uid rsp = ...
Read one memory segment (128 byte).
def make_fil_file(filename,out_dir='./', new_filename=None, max_load = None): ''' Converts file to Sigproc filterbank (.fil) format. Default saves output in current dir. ''' fil_file = Waterfall(filename, max_load = max_load) if not new_filename: new_filename = out_dir+filename.replace('.h5','...
Converts file to Sigproc filterbank (.fil) format. Default saves output in current dir.
def show(self): """Shows the main window and grabs the focus on it. """ self.hidden = False # setting window in all desktops window_rect = RectCalculator.set_final_window_rect(self.settings, self.window) self.window.stick() # add tab must be called before windo...
Shows the main window and grabs the focus on it.
def init_stash(stash_path, passphrase, passphrase_size, backend): r"""Init a stash `STASH_PATH` is the path to the storage endpoint. If this isn't supplied, a default path will be used. In the path, you can specify a name for the stash (which, if omitted, will default to `ghost`) like so: `ghost in...
r"""Init a stash `STASH_PATH` is the path to the storage endpoint. If this isn't supplied, a default path will be used. In the path, you can specify a name for the stash (which, if omitted, will default to `ghost`) like so: `ghost init http://10.10.1.1:8500;stash1`. After initializing a stash, don...
def resolve_to_callable(callable_name): """ Resolve string :callable_name: to a callable. :param callable_name: String representing callable name as registered in ramses registry or dotted import path of callable. Can be wrapped in double curly brackets, e.g. '{{my_callable}}'. """ from...
Resolve string :callable_name: to a callable. :param callable_name: String representing callable name as registered in ramses registry or dotted import path of callable. Can be wrapped in double curly brackets, e.g. '{{my_callable}}'.
def features(sentence, i): """Features for i'th token in sentence. Currently baseline named-entity recognition features, but these can easily be changed to do POS tagging or chunking. """ word = sentence[i] yield "word:{}" + word.lower() if word[0].isupper(): yield "CAP" if ...
Features for i'th token in sentence. Currently baseline named-entity recognition features, but these can easily be changed to do POS tagging or chunking.
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None): ''' Returns the proxy module for this salt-proxy-minion ''' ret = LazyLoader( _module_dirs(opts, 'proxy'), opts, tag='proxy', pack={'__salt__': functions, '__ret__': returners, '__utils__': utils...
Returns the proxy module for this salt-proxy-minion
def p_statement_break(p): '''statement : BREAK SEMI | BREAK expr SEMI''' if len(p) == 3: p[0] = ast.Break(None, lineno=p.lineno(1)) else: p[0] = ast.Break(p[2], lineno=p.lineno(1))
statement : BREAK SEMI | BREAK expr SEMI
def get_top_n_action_types(self, top_n): """Returns the top N actions by count.""" # Count action types action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action_typ...
Returns the top N actions by count.
def create_interface_connection(interface_a, interface_b): ''' .. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion n...
.. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion netbox.create_interface_connection 123 456
def _children_(self): """ get children objects :rtype: a dict of children {child_name: child_object} """ ret = {} names = self._field_names_ def down(name, obj): if isinstance(obj, BaseObj): if not isinstance(obj, weakref.ProxyTypes): ...
get children objects :rtype: a dict of children {child_name: child_object}
def decrypt_file(file_path, recipient_key, *, base64=False): "Returns (filename, file_contents) if successful" crypto.assert_type_and_length('recipient_key', recipient_key, crypto.UserLock) with open(file_path, "rb") as I: contents = I.read() if base64: contents = crypto.b64decod...
Returns (filename, file_contents) if successful
def prefix(self, name): """ :param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None. """ a_node = self.adapter.get_node_attribute_node(self.impl_element, name) if a_node is None: ...
:param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None.
def twitter_credential(name): """ Grab twitter credential from settings """ credential_name = 'TWITTER_' + name.upper() if hasattr(settings, credential_name): return getattr(settings, credential_name) else: raise AttributeError('Missing twitter credential in settings: ' + credential_name...
Grab twitter credential from settings
def _channel_loop(detection, template, min_cc, detection_id, interpolate, i, pre_lag_ccsum=None, detect_chans=0, horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'], debug=0): """ Inner loop for correlating and assigning picks. Utility function ...
Inner loop for correlating and assigning picks. Utility function to take a stream of data for the detected event and write maximum correlation to absolute time as picks in an obspy.core.event.Event object. Only outputs picks for picks above min_cc. :type detection: obspy.core.stream.Stream :pa...
def forgot_password(self): """ View function to request a password recovery email with a reset token. Supports html and json requests. """ form = self._get_form('SECURITY_FORGOT_PASSWORD_FORM') if form.validate_on_submit(): self.security_service.send_reset_pas...
View function to request a password recovery email with a reset token. Supports html and json requests.
def generate(self): ''' Generate noise samples. Returns: `np.ndarray` of samples. ''' generated_arr = np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape) if self.noise_sampler is not None: self.noise_samp...
Generate noise samples. Returns: `np.ndarray` of samples.
def connect_discussion_signals(): """ Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments. """ post_save.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PS_COUNT...
Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments.
def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options): """Record a purchase in Sailthru Arguments: sailthru_client (object): SailthruClient email (str): user's email address item (dict): Sailthru required information about the course purcha...
Record a purchase in Sailthru Arguments: sailthru_client (object): SailthruClient email (str): user's email address item (dict): Sailthru required information about the course purchase_incomplete (boolean): True if adding item to shopping cart message_id (str): Cookie used t...
def debug_command(self, cmd, args=None, progress_callback=None): """Send a debug command to the connected device. This generic method will send a named debug command with the given arguments to the connected device. Debug commands are typically used for things like forcible reflashing ...
Send a debug command to the connected device. This generic method will send a named debug command with the given arguments to the connected device. Debug commands are typically used for things like forcible reflashing of firmware or other, debug-style, operations. Not all transport pr...
def call_actions_future( self, service_name, actions, expansions=None, raise_job_errors=True, raise_action_errors=True, timeout=None, **kwargs ): """ This method is identical in signature and behavior to `call_actions`, except that it s...
This method is identical in signature and behavior to `call_actions`, except that it sends the request and then immediately returns a `FutureResponse` instead of blocking waiting on a response and returning a `JobResponse`. Just call `result(timeout=None)` on the future response to block for an availabl...
def satisfy_one(self, assumptions=None, **params): """ If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None. """ verbosity = params.get('verbosity', 0) default_phase = params.get('default_phase', 2) propagation_limit =...
If the input CNF is satisfiable, return a satisfying input point. A contradiction will return None.
def _bind(self, _descriptor): """ Bind a ResponseObject to a given action descriptor. This updates the default HTTP response code and selects the appropriate content type and serializer for the response. """ # If the method has a default code, use it self._defco...
Bind a ResponseObject to a given action descriptor. This updates the default HTTP response code and selects the appropriate content type and serializer for the response.
def get_person_by_nickname(self, nickname): """Retrieves a person by nickname""" return next((person for person in self.get_all_people() if person.nickname.lower() == nickname.lower()), None)
Retrieves a person by nickname
def loadtxt_str(path:PathOrStr)->np.ndarray: "Return `ndarray` of `str` of lines of text from `path`." with open(path, 'r') as f: lines = f.readlines() return np.array([l.strip() for l in lines])
Return `ndarray` of `str` of lines of text from `path`.
def create_issues_report(self, timeout=-1): """ Creates an unexpected zoning report for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its comp...
Creates an unexpected zoning report for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: list: A list of FCIssueRes...
def phone_number(self, phone_number): """ Sets the phone_number of this OrderFulfillmentRecipient. The phone number of the fulfillment recipient. If provided, overrides the value from customer profile indicated by customer_id. :param phone_number: The phone_number of this OrderFulfillm...
Sets the phone_number of this OrderFulfillmentRecipient. The phone number of the fulfillment recipient. If provided, overrides the value from customer profile indicated by customer_id. :param phone_number: The phone_number of this OrderFulfillmentRecipient. :type: str
def errorhandler(self, code_or_exception): """ Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): retu...
Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also regist...
def lookup(self, auth, type, mapping, defer=False): """ Look up a Resource ID by alias, owned Resource ID, or share activation code under the client specified in <ClientID>. Args: auth: <cik> type: Type of resource to lookup (alias | owner | shared) mapping: ...
Look up a Resource ID by alias, owned Resource ID, or share activation code under the client specified in <ClientID>. Args: auth: <cik> type: Type of resource to lookup (alias | owner | shared) mapping: Based on resource type defined above.
def getOrderVector(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based on th...
Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally.
def defer_function(self, callable): """Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When 'callable' is called, the scope at the time this is called...
Schedule a function handler to be called just before completion. This is used for handling function bodies, which must be deferred because code later in the file might modify the global scope. When 'callable' is called, the scope at the time this is called will be restored, however it will cont...
def compile_migrations(migrator, models, reverse=False): """Compile migrations for given models.""" source = migrator.orm.values() if reverse: source, models = models, source migrations = diff_many(models, source, migrator, reverse=reverse) if not migrations: return False migra...
Compile migrations for given models.
def get_system_uptime_input_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime input = ET.SubElement(get_system_uptime, "input") rbridge_id = ET.SubEle...
Auto Generated Code
def load_variable(self, var=None, start_date=None, end_date=None, time_offset=None, grid_attrs=None, **DataAttrs): """Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------...
Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------- var : Var aospy Var object start_date : datetime.datetime start date for interval end_date : datet...
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): '''Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.''' if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = ('1','2...
Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.
def cnst_A1T(self, Y1): r"""Compute :math:`A_1^T \mathbf{y}_1` component of :math:`A^T \mathbf{y}`. In this case :math:`A_1^T \mathbf{y}_1 = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}_1`. """ Y1f = sl.rfftn(Y1, None, axes=self.cri.axisN) return sl.irfftn(np.conj...
r"""Compute :math:`A_1^T \mathbf{y}_1` component of :math:`A^T \mathbf{y}`. In this case :math:`A_1^T \mathbf{y}_1 = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots) \mathbf{y}_1`.
def _mpda(self, re_grammar, splitstring=0): """ Args: re_grammar (list): A list of grammar rules splitstring (bool): A boolean for enabling or disabling the splitting of symbols using a space Returns: PDA: The generated PDA ...
Args: re_grammar (list): A list of grammar rules splitstring (bool): A boolean for enabling or disabling the splitting of symbols using a space Returns: PDA: The generated PDA
def _exec(self, cmd, url, json_data=None): """ execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be at...
execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be attached to the command
def set_user_access(self, uid, channel=None, callback=False, link_auth=True, ipmi_msg=True, privilege_level='user'): """Set user access :param uid: user number [1:16] :param channel: number [1:7] :parm callback: User Restricted to Callback False = User ...
Set user access :param uid: user number [1:16] :param channel: number [1:7] :parm callback: User Restricted to Callback False = User Privilege Limit is determined by the User Privilege Limit parameter, below, for both callback and non-callback connections. True = ...
def submit(jman, command, arguments, deps=[], array=None): """An easy submission option for grid-enabled scripts. Create the log directories using random hash codes. Use the arguments as parsed by the main script.""" logdir = os.path.join(os.path.realpath(arguments.logdir), tools.random_logdir()) jobn...
An easy submission option for grid-enabled scripts. Create the log directories using random hash codes. Use the arguments as parsed by the main script.
def get_code(module): """ Compile and return a Module's code object. """ fp = open(module.path) try: return compile(fp.read(), str(module.name), 'exec') finally: fp.close()
Compile and return a Module's code object.
def process_event(self, event_name: str, data: dict): """ Process event after epoch Args: event_name: whether event is send after epoch or batch. Set of values: ``"after_epoch", "after_batch"`` data: event data (dictionary) Returns: ...
Process event after epoch Args: event_name: whether event is send after epoch or batch. Set of values: ``"after_epoch", "after_batch"`` data: event data (dictionary) Returns: None
def parse_args(argv): """Parse the command line arguments and return the namespace that was creates by argparse.ArgumentParser.parse_args(). :returns: the namespace parsed from the command line :rtype: argparse.Namespace """ # Create the base argument parser. It will be reused for the first a...
Parse the command line arguments and return the namespace that was creates by argparse.ArgumentParser.parse_args(). :returns: the namespace parsed from the command line :rtype: argparse.Namespace
def parent(self): """Return parent resource :rtype: Resource :raises ResourceNotFound: parent resource doesn't exists :raises ResourceMissing: parent resource is not defined """ try: return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True) ...
Return parent resource :rtype: Resource :raises ResourceNotFound: parent resource doesn't exists :raises ResourceMissing: parent resource is not defined
def fcoe_get_login_input_fcoe_login_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login input = ET.SubElement(fcoe_get_login, "input") fcoe_login_rbridge_id = ET...
Auto Generated Code
def finish(self): """Combines coverage data and sets the list of coverage objects to report on.""" # Combine all the suffix files into the data file. self.cov.stop() self.cov.combine() self.cov.save()
Combines coverage data and sets the list of coverage objects to report on.
def search(self, **kwargs): """ Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param ...
Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override def...
def from_pyfile(self, filename): """ ๅœจไธ€ไธช Python ๆ–‡ไปถไธญ่ฏปๅ–้…็ฝฎใ€‚ :param filename: ้…็ฝฎๆ–‡ไปถ็š„ๆ–‡ไปถๅ :return: ๅฆ‚ๆžœ่ฏปๅ–ๆˆๅŠŸ๏ผŒ่ฟ”ๅ›ž ``True``๏ผŒๅฆ‚ๆžœๅคฑ่ดฅ๏ผŒไผšๆŠ›ๅ‡บ้”™่ฏฏๅผ‚ๅธธ """ d = types.ModuleType('config') d.__file__ = filename with open(filename) as config_file: exec(compile(config_file.r...
ๅœจไธ€ไธช Python ๆ–‡ไปถไธญ่ฏปๅ–้…็ฝฎใ€‚ :param filename: ้…็ฝฎๆ–‡ไปถ็š„ๆ–‡ไปถๅ :return: ๅฆ‚ๆžœ่ฏปๅ–ๆˆๅŠŸ๏ผŒ่ฟ”ๅ›ž ``True``๏ผŒๅฆ‚ๆžœๅคฑ่ดฅ๏ผŒไผšๆŠ›ๅ‡บ้”™่ฏฏๅผ‚ๅธธ
def __initialize_ui(self): """ Initializes the View ui. """ self.viewport().installEventFilter(ReadOnlyFilter(self)) if issubclass(type(self), QListView): super(type(self), self).setUniformItemSizes(True) elif issubclass(type(self), QTreeView): s...
Initializes the View ui.
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False, variables=None): r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho...
r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$ normalized (boolean): Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$ A very simple e...
def createSubtitle(self, fps, section): """Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression.""" matched = self._pattern.search(section) if m...
Returns a correct 'Subtitle' object from a text given in 'section'. If 'section' cannot be parsed, None is returned. By default 'section' is checked against 'subPattern' regular expression.
def write(nml, nml_path, force=False, sort=False): """Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is...
Save a namelist to disk using either a file object or its file path. File object usage: >>> with open(nml_path, 'w') as nml_file: >>> f90nml.write(nml, nml_file) File path usage: >>> f90nml.write(nml, 'data.nml') This function is equivalent to the ``write`` function of the ``Namelist`` ...
def camel_case_to_name(name): """ Used to convert a classname to a lowercase name """ def convert_func(val): return "_" + val.group(0).lower() return name[0].lower() + re.sub(r'([A-Z])', convert_func, name[1:])
Used to convert a classname to a lowercase name
def is_subsequence(needle, haystack): """Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout""" it = iter(haystack) for element in needle: if element not in it: return False return True
Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout
def intcomma(value): """ Borrowed from django.contrib.humanize Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = str(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) if orig == ne...
Borrowed from django.contrib.humanize Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
def area(poly): """Area of a polygon poly""" if len(poly) < 3: # not a plane - no area return 0 total = [0, 0, 0] num = len(poly) for i in range(num): vi1 = poly[i] vi2 = poly[(i+1) % num] prod = np.cross(vi1, vi2) total[0] += prod[0] total[1] += prod[...
Area of a polygon poly
def parse_tasks_file_header(header, input_file_param_util, output_file_param_util): """Parse the header from the tasks file into env, input, output definitions. Elements are formatted similar to their equivalent command-line arguments, but with associated values coming from the data r...
Parse the header from the tasks file into env, input, output definitions. Elements are formatted similar to their equivalent command-line arguments, but with associated values coming from the data rows. Environment variables columns are headered as "--env <name>" Inputs columns are headered as "--input <name>...
def start_module(self): """Wrapper for _main function. Catch and raise any exception occurring in the main function :return: None """ try: self._main() except Exception as exp: logger.exception('%s', traceback.format_exc()) raise Excep...
Wrapper for _main function. Catch and raise any exception occurring in the main function :return: None
def guess_rank(M_E): '''Guess the rank of the incomplete matrix ''' n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1] - S0[1:] S1_ = S1 / np.mean(S1[-10:]) r1 = 0 la...
Guess the rank of the incomplete matrix
def rename(old_name, new_name): """Renames a snapshot""" app = get_app() snapshot = app.get_snapshot(old_name) if not snapshot: click.echo("Couldn't find snapshot %s" % old_name) sys.exit(1) new_snapshot = app.get_snapshot(new_name) if new_snapshot: click.echo("Snapshot...
Renames a snapshot
def from_seedhex_file(path: str) -> SigningKeyType: """ Return SigningKey instance from Seedhex file :param str path: Hexadecimal seed file path """ with open(path, 'r') as fh: seedhex = fh.read() return SigningKey.from_seedhex(seedhex)
Return SigningKey instance from Seedhex file :param str path: Hexadecimal seed file path
def _as_chunk(self): """ A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples. """ if self._chunk...
A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples.
def get_worker(self, *queues): """ Returns an RQ worker instance for the given queue names, e.g.:: configured_worker = rq.get_worker() default_worker = rq.get_worker('default') default_low_worker = rq.get_worker('default', 'low') :param \\*queues: Names of q...
Returns an RQ worker instance for the given queue names, e.g.:: configured_worker = rq.get_worker() default_worker = rq.get_worker('default') default_low_worker = rq.get_worker('default', 'low') :param \\*queues: Names of queues the worker should act on, falls back ...
def split_query(query): """ Handle the query as a WWW HTTP 1630 query, as this is how people usually thinks of URI queries in general. We do not decode anything in split operations, neither percent nor the terrible plus-to-space conversion. Return: >>> split_query("k1=v1&k2=v+2%12&k3=&k4&&&k5...
Handle the query as a WWW HTTP 1630 query, as this is how people usually thinks of URI queries in general. We do not decode anything in split operations, neither percent nor the terrible plus-to-space conversion. Return: >>> split_query("k1=v1&k2=v+2%12&k3=&k4&&&k5==&=k&==") (('k1', 'v1'), ('k2',...
def getXML(self, CorpNum, NTSConfirmNum, UserID=None): """ ์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ ์ƒ์„ธ์ •๋ณด ํ™•์ธ - XML args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ NTSConfirmNum : ๊ตญ์„ธ์ฒญ ์Šน์ธ๋ฒˆํ˜ธ UserID : ํŒ๋นŒํšŒ์› ์•„์ด๋”” return ์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ ์ •๋ณด๊ฐ์ฒด raise PopbillException ...
์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ ์ƒ์„ธ์ •๋ณด ํ™•์ธ - XML args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ NTSConfirmNum : ๊ตญ์„ธ์ฒญ ์Šน์ธ๋ฒˆํ˜ธ UserID : ํŒ๋นŒํšŒ์› ์•„์ด๋”” return ์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ ์ •๋ณด๊ฐ์ฒด raise PopbillException
def update_ref(profile, ref, sha): """Point a ref to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref ...
Point a ref to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref The ref to update, e.g., ``heads/my-...
def heating_level(self): """Return heating level.""" try: if self.side == 'left': level = self.device.device_data['leftHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightHeatingLevel'] return level e...
Return heating level.
def reset(self, id=None): ''' Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected. ''' if id is None: self.ccache.clear() else: self.ccache.pop(id, None) if DEBUG: for route in self.routes...
Reset all routes (force plugins to be re-applied) and clear all caches. If an ID is given, only that specific route is affected.
def treeplot(self, qlist, credible_interval): """Get data for each treeplot for the variable.""" for y, _, label, values, color in self.iterator(): ntiles = np.percentile(values.flatten(), qlist) ntiles[0], ntiles[-1] = hpd(values.flatten(), credible_interval) yield y...
Get data for each treeplot for the variable.
def delete_user(self, user_id, **kwargs): # noqa: E501 """Delete a user. # noqa: E501 An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous ...
Delete a user. # noqa: E501 An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP reque...
def log_predictive_density(self, x_test, y_test, Y_metadata=None): """ Calculation of the log predictive density. Notice we add the jacobian of the warping function here. .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locatio...
Calculation of the log predictive density. Notice we add the jacobian of the warping function here. .. math: p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*}) :param x_test: test locations (x_{*}) :type x_test: (Nx1) array :param y_test: test observations (...
def codebox(msg="", title=" ", text=""): """ Display some text in a monospaced font, with no line wrapping. This function is suitable for displaying code and text that is formatted using spaces. The text parameter should be a string, or a list or tuple of lines to be displayed in the textbox. ...
Display some text in a monospaced font, with no line wrapping. This function is suitable for displaying code and text that is formatted using spaces. The text parameter should be a string, or a list or tuple of lines to be displayed in the textbox. :param str msg: the msg to be displayed :para...
def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false ...
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
def _create_hash_from_doc(doc: Mapping[str, Any]) -> str: """Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash """ doc_string = json.dumps(doc, sort_keys=True) return _create_hash(doc_string)
Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash
def decode_token(encoded_token, csrf_value=None, allow_expired=False): """ Returns the decoded token (python dict) from an encoded JWT. This does all the checks to insure that the decoded token is valid before returning it. :param encoded_token: The encoded JWT to decode into a python dict. :param ...
Returns the decoded token (python dict) from an encoded JWT. This does all the checks to insure that the decoded token is valid before returning it. :param encoded_token: The encoded JWT to decode into a python dict. :param csrf_value: Expected CSRF double submit value (optional) :param allow_expired: ...
def remove_node(cls, cluster_id_label, private_dns, parameters=None): """ Add a node to an existing cluster """ conn = Qubole.agent(version=Cluster.api_version) parameters = {} if not parameters else parameters data = {"private_dns" : private_dns, "parameters" : parameter...
Add a node to an existing cluster
def get_iterator_type(script_settings, subscripts={}): """ figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns: """ if 'iterator_type' in scrip...
figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns:
def get_logs_multipart( w3, startBlock, stopBlock, address, topics, max_blocks): """Used to break up requests to ``eth_getLogs`` The getLog request is partitioned into multiple calls of the max number of blocks ``max_blocks``. """ _block_ranges = bloc...
Used to break up requests to ``eth_getLogs`` The getLog request is partitioned into multiple calls of the max number of blocks ``max_blocks``.
def new_line(self, tokens, line_end, line_start): """a new line has been encountered, process it if necessary""" if _last_token_on_line_is(tokens, line_end, ";"): self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end)) line_num = tokens.start_line(line_start) ...
a new line has been encountered, process it if necessary
def set_info(self, info): """ set my state from the passed info """ idx = info.get(self.name) if idx is not None: self.__dict__.update(idx)
set my state from the passed info
def _calc_sdof_tf(self, osc_freq, damping=0.05): """Compute the transfer function for a single-degree-of-freedom oscillator. The transfer function computes the pseudo-spectral acceleration. Parameters ---------- osc_freq : float natural frequency of the osci...
Compute the transfer function for a single-degree-of-freedom oscillator. The transfer function computes the pseudo-spectral acceleration. Parameters ---------- osc_freq : float natural frequency of the oscillator [Hz] damping : float, optional da...
def to_file(file, array): """Wrapper around ndarray.tofile to support any file-like object""" try: array.tofile(file) except (TypeError, IOError, UnsupportedOperation): # tostring actually returns bytes file.write(array.tostring())
Wrapper around ndarray.tofile to support any file-like object
def example_lab_to_xyz(): """ This function shows a simple conversion of an Lab color to an XYZ color. """ print("=== Simple Example: Lab->XYZ ===") # Instantiate an Lab color object with the given values. lab = LabColor(0.903, 16.296, -2.22) # Show a string representation. print(lab) ...
This function shows a simple conversion of an Lab color to an XYZ color.
def _execute(self, sql, args): """ๆ‰ง่กŒsql่ฏญๅฅ :param sql: sql่ฏญๅฅ :param args: ๅ‚ๆ•ฐ :return: ่ฟ”ๅ›ž็š„้ƒฝๆ˜ฏๆ•ฐ็ป„ๅฏน่ฑก """ sql = sql.lower().strip() args = args or () tmp = sql[:6] with (yield self._pool.Connection()) as conn: try: with conn.cu...
ๆ‰ง่กŒsql่ฏญๅฅ :param sql: sql่ฏญๅฅ :param args: ๅ‚ๆ•ฐ :return: ่ฟ”ๅ›ž็š„้ƒฝๆ˜ฏๆ•ฐ็ป„ๅฏน่ฑก
def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name pattern.""" warnings.warn('find_related_modules has been deprecated.', DeprecationWarning) package_elements = package.rsplit...
Find matching modules using a package and a module name pattern.
def cli(ctx, packages, all, list, force, platform): """Install packages.""" if packages: for package in packages: Installer(package, platform, force).install() elif all: # pragma: no cover packages = Resources(platform).packages for package in packages: Inst...
Install packages.
def _infer_map(node, context): """Infer all values based on Dict.items""" values = {} for name, value in node.items: if isinstance(name, nodes.DictUnpack): double_starred = helpers.safe_infer(value, context) if not double_starred: raise exceptions.InferenceErr...
Infer all values based on Dict.items
def ploidy(args): """ %prog ploidy seqids layout Build a figure that calls graphics.karyotype to illustrate the high ploidy of B. napus genome. """ p = OptionParser(ploidy.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x7") if len(args) != 2: sys.exit(not p.pr...
%prog ploidy seqids layout Build a figure that calls graphics.karyotype to illustrate the high ploidy of B. napus genome.
def disconnect(self, connection): """ Disconnects the given protocol. """ proto = self._protocols.pop(connection) proto.transport = None return {}
Disconnects the given protocol.
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are bot...
Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or float), and they contain fewer than or equal to 5,000 value...
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transf...
Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float toleranc...
def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
def assert_shape_match(shape1, shape2): """Ensure the shape1 match the pattern given by shape2. Ex: assert_shape_match((64, 64, 3), (None, None, 3)) Args: shape1 (tuple): Static shape shape2 (tuple): Dynamic shape (can contain None) """ shape1 = tf.TensorShape(shape1) shape2 = tf.TensorShape(s...
Ensure the shape1 match the pattern given by shape2. Ex: assert_shape_match((64, 64, 3), (None, None, 3)) Args: shape1 (tuple): Static shape shape2 (tuple): Dynamic shape (can contain None)
def update_artifact_cache(self, vts_artifactfiles_pairs): """Write to the artifact cache, if we're configured to. vts_artifactfiles_pairs - a list of pairs (vts, artifactfiles) where - vts is single VersionedTargetSet. - artifactfiles is a list of absolute paths to artifacts for the VersionedTarget...
Write to the artifact cache, if we're configured to. vts_artifactfiles_pairs - a list of pairs (vts, artifactfiles) where - vts is single VersionedTargetSet. - artifactfiles is a list of absolute paths to artifacts for the VersionedTargetSet.
def parse_string_expr(self, string_expr_node): """ Parse a string node content. """ string_expr_node_value = string_expr_node['value'] string_expr_str = string_expr_node_value[1:-1] # Care escaped string literals if string_expr_node_value[0] == "'": string_expr_str =...
Parse a string node content.