code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def process_response(self, req, resp, resource): """ Post-processing of the response (after routing). Some fundamental errors can't be intercepted any other way in Falcon. These include 404 when the route isn't found & 405 when the method is bunk. Falcon will try to send its own...
Post-processing of the response (after routing). Some fundamental errors can't be intercepted any other way in Falcon. These include 404 when the route isn't found & 405 when the method is bunk. Falcon will try to send its own errors. In these cases, intercept them & replace th...
def search(searchList, matchStr, numSyllables=None, wordInitial='ok', wordFinal='ok', spanSyllable='ok', stressedSyllable='ok', multiword='ok', pos=None): ''' Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllabl...
Searches for matching words in the dictionary with regular expressions wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword can take three different values: 'ok', 'only', or 'no'. pos: a tag in the Penn Part of Speech tagset see isletool.posList for the full list of possible...
def cut_action_callback(self, *event): """Add a copy and cut all selected row dict value pairs to the clipboard""" if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None: _, dict_paths = self.get_view_selection() stored_data_list = [] ...
Add a copy and cut all selected row dict value pairs to the clipboard
def _merge_relative_path(dst_path, rel_path): """Merge a relative tar file to a destination (which can be "gs://...").""" # Convert rel_path to be relative and normalize it to remove ".", "..", "//", # which are valid directories in fileystems like "gs://". norm_rel_path = os.path.normpath(rel_path.lstrip("/"))...
Merge a relative tar file to a destination (which can be "gs://...").
def groupIcon( cls, groupName, default = None ): """ Returns the icon for the inputed group name. :param groupName | <str> default | <str> || None :return <str> """ if ( cls._groupIcons is None ): cls....
Returns the icon for the inputed group name. :param groupName | <str> default | <str> || None :return <str>
def _get_stddevs(self, stddev_types, pgv): """ Return standard deviations as defined in equation 3.5.5-1 page 151 """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(pgv) std[pgv <...
Return standard deviations as defined in equation 3.5.5-1 page 151
def preview(klass, account, **kwargs): """ Returns an HTML preview of a tweet, either new or existing. """ params = {} params.update(kwargs) # handles array to string conversion for media IDs if 'media_ids' in params and isinstance(params['media_ids'], list): ...
Returns an HTML preview of a tweet, either new or existing.
def lookup_symbols(self, symbols, as_of_date, fuzzy=False, country_code=None): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbol...
Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------- symbols : sequence[str] Sequence of ticker symbols to reso...
def convert_label_indexer(index, label, index_name='', method=None, tolerance=None): """Given a pandas.Index and labels (e.g., from __getitem__) for one dimension, return an indexer suitable for indexing an ndarray along that dimension. If `index` is a pandas.MultiIndex and dependi...
Given a pandas.Index and labels (e.g., from __getitem__) for one dimension, return an indexer suitable for indexing an ndarray along that dimension. If `index` is a pandas.MultiIndex and depending on `label`, return a new pandas.Index or pandas.MultiIndex (otherwise return None).
def field(self): """ Returns the field name that this column will have inside the database. :return <str> """ if not self.__field: default_field = inflection.underscore(self.__name) if isinstance(self, orb.ReferenceColumn): default_fie...
Returns the field name that this column will have inside the database. :return <str>
def sim_strcmp95(src, tar, long_strings=False): """Return the strcmp95 similarity of two strings. This is a wrapper for :py:meth:`Strcmp95.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison long_strings : bool S...
Return the strcmp95 similarity of two strings. This is a wrapper for :py:meth:`Strcmp95.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison long_strings : bool Set to True to increase the probability of a match when ...
def render_requests_data_to_html(self, data, file_name, context={}): """Render to HTML file""" file_path = os.path.join(self.html_dir, file_name) logger.info('Rendering HTML file %s...' % file_path) data = format_data(data) data.update(context) data.update(domain=self.dom...
Render to HTML file
def ready_print(worker, output, error): # pragma : no cover """Local test helper.""" global COUNTER COUNTER += 1 print(COUNTER, output, error)
Local test helper.
def is_holiday(now=None, holidays="/etc/acct/holidays"): """is_holiday({now}, {holidays="/etc/acct/holidays"}""" now = _Time(now) # Now, parse holiday file. if not os.path.exists(holidays): raise Exception("There is no holidays file: %s" % holidays) f = open(holidays, "r") # First, read...
is_holiday({now}, {holidays="/etc/acct/holidays"}
def ProcessResponse(self, client_id, response): """Actually processes the contents of the response.""" precondition.AssertType(client_id, Text) downsampled = rdf_client_stats.ClientStats.Downsampled(response) if data_store.AFF4Enabled(): urn = rdf_client.ClientURN(client_id).Add("stats") w...
Actually processes the contents of the response.
def get_members(pkg_name, module_filter = None, member_filter = None): """ 返回包中所有符合条件的模块成员。 参数: pkg_name 包名称 module_filter 模块名过滤器 def (module_name) member_filter 成员过滤器 def member_filter(module_member_object) """ modules = get_modules(p...
返回包中所有符合条件的模块成员。 参数: pkg_name 包名称 module_filter 模块名过滤器 def (module_name) member_filter 成员过滤器 def member_filter(module_member_object)
def authenticationAndCipheringRequest( AuthenticationParameterRAND_presence=0, CiphKeySeqNr_presence=0): """AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9""" a = TpPd(pd=0x3) b = MessageType(mesType=0x12) # 00010010 d = Cip...
AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9
def list_nodes(conn=None, call=None): ''' Return a list of VMs CLI Example .. code-block:: bash salt-cloud -f list_nodes myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes function must be called with -f or --function.' ) r...
Return a list of VMs CLI Example .. code-block:: bash salt-cloud -f list_nodes myopenstack
def perform(self): """ Performs all stored actions. """ if self._driver.w3c: self.w3c_actions.perform() else: for action in self._actions: action()
Performs all stored actions.
def is_json(value, schema = None, json_serializer = None, **kwargs): """Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the ...
Indicate whether ``value`` is a valid JSON object. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using a ``$schema`` property, the schema will be assumed to conform to Draft 7. :param value: The value to evaluate. :param schema...
def get_connected_components_as_subgraphs(graph): """Finds all connected components of the graph. Returns a list of graph objects, each representing a connected component. Returns an empty list for an empty graph. """ components = get_connected_components(graph) list_of_graphs = [] for c i...
Finds all connected components of the graph. Returns a list of graph objects, each representing a connected component. Returns an empty list for an empty graph.
def equal(self, cwd): """ Returns True if left and right are equal """ cmd = ["diff"] cmd.append("-q") cmd.append(self.left.get_name()) cmd.append(self.right.get_name()) try: Process(cmd).run(cwd=cwd, suppress_output=True) except SubprocessErr...
Returns True if left and right are equal
def register_form_factory(Form): """Factory for creating an extended user registration form.""" class CsrfDisabledProfileForm(ProfileForm): """Subclass of ProfileForm to disable CSRF token in the inner form. This class will always be a inner form field of the parent class `Form`. The pa...
Factory for creating an extended user registration form.
def merge(cls, source_blocks): """Merge multiple SourceBlocks together""" if len(source_blocks) == 1: return source_blocks[0] source_blocks.sort(key=operator.attrgetter('start_line_number')) main_block = source_blocks[0] boot_lines = main_block.boot_lines so...
Merge multiple SourceBlocks together
async def _get_entity_from_string(self, string): """ Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side eff...
Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side effect of adding the found users to the session database, so it ...
def new_worker_pool(self, name: str, min_workers: int = 0, max_workers: int = 1, max_seconds_idle: int = DEFAULT_WORKER_POOL_MAX_SECONDS_IDLE): """ Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool. """ if not sel...
Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool.
def send(self, envelope): """Sends an *envelope*.""" if not self.is_connected: self._connect() msg = envelope.to_mime_message() to_addrs = [envelope._addrs_to_header([addr]) for addr in envelope._to + envelope._cc + envelope._bcc] return self._conn.sendmail(msg['Fro...
Sends an *envelope*.
def exit_if_path_exists(self): """ Exit early if the path cannot be found. """ if os.path.exists(self.output_path): ui.error(c.MESSAGES["path_exists"], self.output_path) sys.exit(1)
Exit early if the path cannot be found.
def parse_rules(self): """ Add a set of rules to the app, dividing between filter and other rule set """ # Load patterns: an app is removed when has no defined patterns. try: rule_options = self.config.items('rules') except configparser.NoSectionError: ...
Add a set of rules to the app, dividing between filter and other rule set
def serial_udb_extra_f6_encode(self, sue_PITCHGAIN, sue_PITCHKD, sue_RUDDER_ELEV_MIX, sue_ROLL_ELEV_MIX, sue_ELEVATOR_BOOST): ''' Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (floa...
Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (float) sue_PITCHKD : Serial UDB Extra Pitch Rate Control (float) sue_RUDDER_ELEV_MIX : Serial UDB Extra Rudder to...
def supports_string_match_type(self, string_match_type=None): """Tests if the given string match type is supported. arg: string_match_type (osid.type.Type): a string match type return: (boolean) - ``true`` if the given string match type Is supported, ``false`` otherwise ...
Tests if the given string match type is supported. arg: string_match_type (osid.type.Type): a string match type return: (boolean) - ``true`` if the given string match type Is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``STRING`` raise: Null...
def patch(): """ Patch startService and stopService so that they check the previous state first. (used for debugging only) """ from twisted.application.service import Service old_startService = Service.startService old_stopService = Service.stopService def startService(self): ...
Patch startService and stopService so that they check the previous state first. (used for debugging only)
def download_apk(self, path='.'): """ Download Android .apk @type path: @param path: """ apk_fd, apk_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.apk') os.close(apk_fd) try: _download_url(self.artifact_url('apk'), apk_fn) sh...
Download Android .apk @type path: @param path:
def __default(self, ast_token): """Handle tokens inside the list or outside the list.""" if self.list_level == 1: if self.list_entry is None: self.list_entry = ast_token elif not isinstance(ast_token, type(self.list_entry)): self.final_ast_tokens.a...
Handle tokens inside the list or outside the list.
def head(self, rows): """ Return a Series of the first N rows :param rows: number of rows :return: Series """ rows_bool = [True] * min(rows, len(self._index)) rows_bool.extend([False] * max(0, len(self._index) - rows)) return self.get(indexes=rows_bool)
Return a Series of the first N rows :param rows: number of rows :return: Series
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices ...
Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False.
def export_to_dom(self): """ Exports this model to a DOM. """ namespaces = 'xmlns="http://www.neuroml.org/lems/%s" ' + \ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + \ 'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"' ...
Exports this model to a DOM.
def prepare_child_message(self, gas: int, to: Address, value: int, data: BytesOrView, code: bytes, **kwargs: Any) -> Message: """ ...
Helper method for creating a child computation.
def extend(self, source, new_image_name, s2i_args=None): """ extend this s2i-enabled image using provided source, raises ConuException if `s2i build` fails :param source: str, source used to extend the image, can be path or url :param new_image_name: str, name of the new, extend...
extend this s2i-enabled image using provided source, raises ConuException if `s2i build` fails :param source: str, source used to extend the image, can be path or url :param new_image_name: str, name of the new, extended image :param s2i_args: list of str, additional options and argumen...
def to_markdown(self): """Converts to markdown :return: item in markdown format """ if self.type == "text": return self.text elif self.type == "url" or self.type == "image": return "[" + self.text + "](" + self.attributes["ref"] + ")" elif self.typ...
Converts to markdown :return: item in markdown format
def dumpindented(self, pn, indent=0): """ Dump all nodes of the current page with keys indented, showing how the `indent` feature works """ page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") ...
Dump all nodes of the current page with keys indented, showing how the `indent` feature works
def authenticate(self, username, password): """ Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response ...
Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response access token is saved in self.access_token refre...
def p_function_body(p): '''function_body : shell_command | shell_command redirection_list''' assert p[1].kind == 'compound' p[0] = p[1] if len(p) == 3: p[0].redirects.extend(p[2]) assert p[0].pos[0] < p[0].redirects[-1].pos[1] p[0].pos = (p[0].pos[0], p[0].r...
function_body : shell_command | shell_command redirection_list
def settle(ctx, symbol, amount, account): """ Fund the fee pool of an asset """ print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account))
Fund the fee pool of an asset
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: """Return a data structure evaluated as a reader macro from the input stream.""" start = ctx.reader.advance() assert start == "#" token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": ...
Return a data structure evaluated as a reader macro from the input stream.
def create(cls, photo, title, description=''): """Create a new photoset. photo - primary photo """ if not isinstance(photo, Photo): raise TypeError, "Photo expected" method = 'flickr.photosets.create' data = _dopost(method, auth=True, title=title,\ ...
Create a new photoset. photo - primary photo
def check(f): """ Wraps the function with a decorator that runs all of the pre/post conditions. """ if hasattr(f, 'wrapped_fn'): return f else: @wraps(f) def decorated(*args, **kwargs): return check_conditions(f, args, kwargs) decorated.wrapped_fn = f ...
Wraps the function with a decorator that runs all of the pre/post conditions.
def _scalar_pattern_uniform_op_left(func): """Decorator for operator overloading when ScalarPatternUniform is on the left.""" @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: ...
Decorator for operator overloading when ScalarPatternUniform is on the left.
def pdf(self): r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = ...
r""" Generate the vector of probabilities for the Beta-binomial (n, a, b) distribution. The Beta-binomial distribution takes the form .. math:: p(k \,|\, n, a, b) = {n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)}, \qquad k = 0, \ldots, n, ...
def flatten_egginfo_json( pkg_names, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): """ A shorthand calling convention where the package name is supplied instead of a distribution. Originally written for this: Generate a flattened package.json with packages `pkg_names` that a...
A shorthand calling convention where the package name is supplied instead of a distribution. Originally written for this: Generate a flattened package.json with packages `pkg_names` that are already installed within the current Python environment (defaults to the current global working_set which s...
def _set_tasks_state(self, value): """ Purpose: Set state of all tasks of the current stage. :arguments: String """ if value not in states.state_numbers.keys(): raise ValueError(obj=self._uid, attribute='set_tasks_state', ...
Purpose: Set state of all tasks of the current stage. :arguments: String
def _collect_config(self): """Collects all info from three sections""" kwargs = {} sections = ('storage_service', 'trajectory', 'environment') for section in sections: kwargs.update(self._collect_section(section)) return kwargs
Collects all info from three sections
def create_mv_rule(tensorprod_rule, dim): """Convert tensor product rule into a multivariate quadrature generator.""" def mv_rule(order, sparse=False, part=None): """ Multidimensional integration rule. Args: order (int, numpy.ndarray) : order of integration rule. If numpy.nd...
Convert tensor product rule into a multivariate quadrature generator.
def get_item_content(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs): """GetItemContent. Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content ...
GetItemContent. Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download. :param str path: Version contr...
def get_meta_data_editor(self, for_gaphas=True): """Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts ...
Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default...
def _compare_frame_rankings(ref, est, transitive=False): '''Compute the number of ranking disagreements in two lists. Parameters ---------- ref : np.ndarray, shape=(n,) est : np.ndarray, shape=(n,) Reference and estimate ranked lists. `ref[i]` is the relevance score for point `i`. ...
Compute the number of ranking disagreements in two lists. Parameters ---------- ref : np.ndarray, shape=(n,) est : np.ndarray, shape=(n,) Reference and estimate ranked lists. `ref[i]` is the relevance score for point `i`. transitive : bool If true, all pairs of reference le...
def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None): '''Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators >>> from django.contrib.auth.models import Permission >>> import math >>> p = Perm...
Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators >>> from django.contrib.auth.models import Permission >>> import math >>> p = Permission.objects.all()[0] >>> follow_double_underscores(p, 'content_type__name') == p.content_type.name True >>> ...
def _process_mrk_acc_view(self): """ Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return: """ # make a pass through the table first, # to create the mapping between the e...
Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return:
def map_indices(fn, iterable, indices): r""" Map a function across indices of an iterable. Notes ----- Roughly equivalent to, though more efficient than:: lambda fn, iterable, *indices: (fn(arg) if i in indices else arg for i, arg in enumerate(iterab...
r""" Map a function across indices of an iterable. Notes ----- Roughly equivalent to, though more efficient than:: lambda fn, iterable, *indices: (fn(arg) if i in indices else arg for i, arg in enumerate(iterable)) Examples -------- >>> a =...
def process_chat(self, chat: types.Chat): """ Generate chat data :param chat: :return: """ if not chat: return yield 'chat_id', chat.id yield 'chat_type', chat.type if self.include_content: yield 'chat_title', chat.full_na...
Generate chat data :param chat: :return:
def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): """Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _we...
Installs the ansible package. By default it is installed from the `PPA`_ linked from the ansible `website`_ or from a ppa specified by a charm config.. .. _PPA: https://launchpad.net/~rquillo/+archive/ansible .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu ...
def create_model(self, parent, name, multiplicity='ZERO_MANY', **kwargs): """Create a new child model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve perfo...
Create a new child model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronten...
def get_image(self, filename: str=None) -> None: """Download the photo associated with a Savings Goal.""" if filename is None: filename = "{0}.png".format(self.name) endpoint = "/account/{0}/savings-goals/{1}/photo".format( self._account_uid, self.uid ...
Download the photo associated with a Savings Goal.
def reset(): """ full reset of matplotlib default style and colors """ colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, .75, 0.), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)] for code, color in zip("bgrmyck", colors): rgb = mpl.colors.colorConverter.to_rgb(color) mp...
full reset of matplotlib default style and colors
def local_rfcformat(dt): """Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset. """ weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()] month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'...
Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset.
def source_sum_err(self): """ The uncertainty of `~photutils.SourceProperties.source_sum`, propagated from the input ``error`` array. ``source_sum_err`` is the quadrature sum of the total errors over the non-masked pixels within the source segment: .. math:: \\Delta F =...
The uncertainty of `~photutils.SourceProperties.source_sum`, propagated from the input ``error`` array. ``source_sum_err`` is the quadrature sum of the total errors over the non-masked pixels within the source segment: .. math:: \\Delta F = \\sqrt{\\sum_{i \\in S} \\s...
def create_request_url(self, interface, method, version, parameters): """Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the me...
Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the method.
def _create_inbound_stream(self, config=None): """ Creates an inbound stream from its config. Params: config: stream configuration as read by ait.config Returns: stream: a Stream Raises: ValueError: if any of the required config ...
Creates an inbound stream from its config. Params: config: stream configuration as read by ait.config Returns: stream: a Stream Raises: ValueError: if any of the required config values are missing
def _string_width(self, s): """Get width of a string in the current font""" s = str(s) w = 0 for char in s: char = ord(char) w += self.character_widths[char] return w * self.font_size / 1000.0
Get width of a string in the current font
def all(self, archived=False, limit=None, page=None): """get all adapter data.""" path = partial(_path, self.adapter) if not archived: path = _path(self.adapter) else: path = _path(self.adapter, 'archived') return self._get(path, limit=limit, page=page)
get all adapter data.
def parse(self, vd, extent_loc): # type: (bytes, int) -> None ''' Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing....
Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing.
def random_dna(n): '''Generate a random DNA sequence. :param n: Output sequence length. :type n: int :returns: Random DNA sequence of length n. :rtype: coral.DNA ''' return coral.DNA(''.join([random.choice('ATGC') for i in range(n)]))
Generate a random DNA sequence. :param n: Output sequence length. :type n: int :returns: Random DNA sequence of length n. :rtype: coral.DNA
def numbered_syllable_to_accented(syllable): """Convert a numbered pinyin syllable to an accented pinyin syllable. Implements the following algorithm, modified from https://github.com/tsroten/zhon: 1. If the syllable has an 'a' or 'e', put the tone over that vowel. 2. If the syllable has 'ou', ...
Convert a numbered pinyin syllable to an accented pinyin syllable. Implements the following algorithm, modified from https://github.com/tsroten/zhon: 1. If the syllable has an 'a' or 'e', put the tone over that vowel. 2. If the syllable has 'ou', place the tone over the 'o'. 3. Otherwise, p...
def sort_url_qsl(cls, raw_url, **kwargs): """Do nothing but sort the params of url. raw_url: the raw url to be sorted; kwargs: (optional) same kwargs for ``sorted``. """ parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) return cls._join_ur...
Do nothing but sort the params of url. raw_url: the raw url to be sorted; kwargs: (optional) same kwargs for ``sorted``.
def rpc_get_name_at( self, name, block_height, **con_info ): """ Get all the states the name was in at a particular block height. Does NOT work on expired names. Return {'status': true, 'record': ...} """ if not check_name(name): return {'error': 'invalid name...
Get all the states the name was in at a particular block height. Does NOT work on expired names. Return {'status': true, 'record': ...}
def _parse_bug(self, data): """ param data: dict of data from XML-RPC server, representing a bug. returns: AttrDict """ if 'id' in data: data['weburl'] = self.url.replace('xmlrpc.cgi', str(data['id'])) bug = AttrDict(data) return bug
param data: dict of data from XML-RPC server, representing a bug. returns: AttrDict
def update_trigger(self, trigger): """ Updates on the Alert API the trigger record having the ID of the specified Trigger object: the remote record is updated with data from the local Trigger object. :param trigger: the Trigger with updated data :type trigger: `pyowm.alertapi30....
Updates on the Alert API the trigger record having the ID of the specified Trigger object: the remote record is updated with data from the local Trigger object. :param trigger: the Trigger with updated data :type trigger: `pyowm.alertapi30.trigger.Trigger` :return: ``None`` if update is...
def add_identity(db, source, email=None, name=None, username=None, uuid=None): """Add an identity to the registry. This function adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. When 'uuid' parameter is set, it creates a new id...
Add an identity to the registry. This function adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. When 'uuid' parameter is set, it creates a new identity that will be associated to the unique identity defined by 'uuid' that alrea...
def is_glacier(s3_client, bucket, prefix): """Check if prefix is archived in Glacier, by checking storage class of first object inside that prefix Arguments: s3_client - boto3 S3 client (not service) bucket - valid extracted bucket (without protocol and prefix) example: sowplow-events-...
Check if prefix is archived in Glacier, by checking storage class of first object inside that prefix Arguments: s3_client - boto3 S3 client (not service) bucket - valid extracted bucket (without protocol and prefix) example: sowplow-events-data prefix - valid S3 prefix (usually, run_id...
def make_unary(lineno, operator, operand, func=None, type_=None): """ Wrapper: returns a Unary node """ return symbols.UNARY.make_node(lineno, operator, operand, func, type_)
Wrapper: returns a Unary node
def axpy(x, y, a=1.0): """Quick level-1 call to BLAS y = a*x+y. Parameters ---------- x : array_like nx1 real or complex vector y : array_like nx1 real or complex vector a : float real or complex scalar Returns ------- y : array_like Input variable y...
Quick level-1 call to BLAS y = a*x+y. Parameters ---------- x : array_like nx1 real or complex vector y : array_like nx1 real or complex vector a : float real or complex scalar Returns ------- y : array_like Input variable y is rewritten Notes -...
def extract_ipfs_path_from_uri(value: str) -> str: """ Return the path from an IPFS URI. Path = IPFS hash & following path. """ parse_result = parse.urlparse(value) if parse_result.netloc: if parse_result.path: return "".join((parse_result.netloc, parse_result.path.rstrip("/...
Return the path from an IPFS URI. Path = IPFS hash & following path.
def none_coalesce_handle(tokens): """Process the None-coalescing operator.""" if len(tokens) == 1: return tokens[0] elif tokens[0].isalnum(): return "({b} if {a} is None else {a})".format( a=tokens[0], b=none_coalesce_handle(tokens[1:]), ) else: re...
Process the None-coalescing operator.
async def disconnect(self): """Shut down the watcher task and close websockets. """ if self._connection: log.debug('Closing model connection') await self._connection.close() self._connection = None
Shut down the watcher task and close websockets.
def _get_cpu_cores_per_run0(coreLimit, num_of_threads, allCpus, cores_of_package, siblings_of_core): """This method does the actual work of _get_cpu_cores_per_run without reading the machine architecture from the file system in order to be testable. For description, c.f. above. Note that this method mig...
This method does the actual work of _get_cpu_cores_per_run without reading the machine architecture from the file system in order to be testable. For description, c.f. above. Note that this method might change the input parameters! Do not call it directly, call getCpuCoresPerRun()! @param allCpus: t...
def get_version(mod, default="0.0.0"): """ :param module|str mod: Module, or module name to find version for (pass either calling module, or its .__name__) :param str default: Value to return if version determination fails :return str: Determined version """ name = mod if hasattr(mod, "__nam...
:param module|str mod: Module, or module name to find version for (pass either calling module, or its .__name__) :param str default: Value to return if version determination fails :return str: Determined version
def delete_object(self, bucket, obj, version_id): """Delete an existing object. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :param version_id: The version ID. :returns: A ...
Delete an existing object. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :param version_id: The version ID. :returns: A Flask response.
def find_features(feats, sequ, annotated, start_pos, cutoff): """ find_features - Finds the reference sequence features in the alignments and records the positions :param feats: Dictonary of sequence features :type feats: ``dict`` :param sequ: The sequence alignment for the input sequence :typ...
find_features - Finds the reference sequence features in the alignments and records the positions :param feats: Dictonary of sequence features :type feats: ``dict`` :param sequ: The sequence alignment for the input sequence :type sequ: ``List`` :param annotated: dictonary of the annotated features...
def dirty(field,ttl=None): "decorator to cache the result of a function until a field changes" if ttl is not None: raise NotImplementedError('pg.dirty ttl feature') def decorator(f): @functools.wraps(f) def wrapper(self,*args,**kwargs): # warning: not reentrant d=self.dirty_cache[field]...
decorator to cache the result of a function until a field changes
def make_figure_uhs(extractors, what): """ $ oq plot 'uhs?kind=mean&site_id=0' """ import matplotlib.pyplot as plt fig = plt.figure() got = {} # (calc_id, kind) -> curves for i, ex in enumerate(extractors): uhs = ex.get(what) for kind in uhs.kind: got[ex.calc_id,...
$ oq plot 'uhs?kind=mean&site_id=0'
def from_vrep(config, vrep_host='127.0.0.1', vrep_port=19997, scene=None, tracked_objects=[], tracked_collisions=[], id=None, shared_vrep_io=None): """ Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) ...
Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) :type config: str or dict :param str vrep_host: host of the V-REP server :param int vrep_port: port of the V-REP server :param str scene: path to the V-REP scene to load...
def setup_logger(logger, logfile): # noqa # type: (logger, str) -> None """Set up logger""" global _REGISTERED_LOGGER_HANDLERS logger.setLevel(logging.DEBUG) if is_none_or_empty(logfile): handler = logging.StreamHandler() else: handler = logging.FileHandler(logfile, encoding='ut...
Set up logger
def list_file_jobs(cls, offset=None, limit=None, api=None): """Query ( List ) async jobs :param offset: Pagination offset :param limit: Pagination limit :param api: Api instance :return: Collection object """ api = api or cls._API return super(AsyncJob, cl...
Query ( List ) async jobs :param offset: Pagination offset :param limit: Pagination limit :param api: Api instance :return: Collection object
def download(self, itemID, savePath): """ downloads an item to local disk Inputs: itemID - unique id of item to download savePath - folder to save the file in """ if os.path.isdir(savePath) == False: os.makedirs(savePath) url = self._url...
downloads an item to local disk Inputs: itemID - unique id of item to download savePath - folder to save the file in
def make_callback_children(self, name, *args, **kwdargs): """Invoke callbacks on all objects (i.e. layers) from the top to the bottom, returning when the first one returns True. If none returns True, then make the callback on our 'native' layer. """ if hasattr(self, 'objects'): ...
Invoke callbacks on all objects (i.e. layers) from the top to the bottom, returning when the first one returns True. If none returns True, then make the callback on our 'native' layer.
def vdm_b(vdm, lat): """ Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitude of site in degrees Returns ...
Converts a virtual dipole moment (VDM) or a virtual axial dipole moment (VADM; input in units of Am^2) to a local magnetic field value (output in units of tesla) Parameters ---------- vdm : V(A)DM in units of Am^2 lat: latitude of site in degrees Returns ------- B: local magnetic f...
def load(self, providers, symbols, start, end, logger, backend, **kwargs): '''Load symbols data. :keyword providers: Dictionary of registered data providers. :keyword symbols: list of symbols to load. :keyword start: start date. :keyword end: end date. :keyword lo...
Load symbols data. :keyword providers: Dictionary of registered data providers. :keyword symbols: list of symbols to load. :keyword start: start date. :keyword end: end date. :keyword logger: instance of :class:`logging.Logger` or ``None``. :keyword backend: :clas...
def trnIndextoCoord(self, i): """ Map 1D cell index to a 2D coordinate :param i: integer 1D cell index :return: (x, y), a 2D coordinate """ x = i % self.trnWidth y = i / self.trnWidth return x, y
Map 1D cell index to a 2D coordinate :param i: integer 1D cell index :return: (x, y), a 2D coordinate
def calculate_authentication_data(self, key): ''' Calculate the authentication data based on the current key-id and the given key. ''' # This one is easy if self.key_id == KEY_ID_NONE: return '' # Determine the digestmod and how long the authenticatio...
Calculate the authentication data based on the current key-id and the given key.
def ordered_covering(routing_table, target_length, aliases=dict(), no_raise=False): """Reduce the size of a routing table by merging together entries where possible. .. warning:: The input routing table *must* also include entries which could be removed and replaced by...
Reduce the size of a routing table by merging together entries where possible. .. warning:: The input routing table *must* also include entries which could be removed and replaced by default routing. .. warning:: It is assumed that the input routing table is not in any particular...