text
stringlengths
81
112k
This is a decorator that creates an async with statement around a function, and makes sure that a _session argument is always passed. Only usable on async functions of course. The _session argument is (supposed to be) an aiohttp.ClientSession instance in all functions that this decorator has been used o...
Adds the ratelimit and request timeout parameters to a function. def _add_request_parameters(func): """Adds the ratelimit and request timeout parameters to a function.""" # The function the decorator returns async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout...
Returns the stats for the profiles on the specified regions and platform. The format for regions without a matching user, the format is the same as get_profile. The stats are returned in a dictionary with a similar format to what https://github.com/SunDwarf/OWAPI/blob/master/api.md#get-apiv3ubattletagstats spec...
Does a request to some endpoint. This is also where ratelimit logic is handled. async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None, handle_ratelimit=None, max_tries=None, request_timeout=None): """Does a request to som...
Uses aiohttp to make a get request asynchronously. Will raise asyncio.TimeoutError if the request could not be completed within _async_timeout_seconds (default 5) seconds. async def _async_get(self, session: aiohttp.ClientSession, *args, _async_timeout_seconds: int = 5, **kwa...
Check if argument is a method. Optionally, we can also check if minimum or maximum arities (number of accepted arguments) match given minimum and/or maximum. def is_method(arg, min_arity=None, max_arity=None): """Check if argument is a method. Optionally, we can also check if minimum or maximum ariti...
Check if the argument is a readable file-like object. def _is_readable(self, obj): """Check if the argument is a readable file-like object.""" try: read = getattr(obj, 'read') except AttributeError: return False else: return is_method(read, max_arity=...
Check if the argument is a writable file-like object. def _is_writable(self, obj): """Check if the argument is a writable file-like object.""" try: write = getattr(obj, 'write') except AttributeError: return False else: return is_method(write, min_ari...
loops the rungtd1d function below. Figure it's easier to troubleshoot in Python than Fortran. def run(time: datetime, altkm: float, glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *, f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset: """ loops the rungtd...
loop over location and time time: datetime or numpy.datetime64 or list of datetime or np.ndarray of datetime glat: float or 2-D np.ndarray glon: float or 2-D np.ndarray altkm: float or list or 1-D np.ndarray def loopalt_gtd(time: datetime, glat: Union[float, np.ndarray], glon: Union[fl...
This is the "atomic" function looped by other functions def rungtd1d(time: datetime, altkm: np.ndarray, glat: float, glon: float, *, f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset: """ This is the "atomic" function looped by other functions ...
Validate the predicate description. def _validate_desc(self, desc): """Validate the predicate description.""" if desc is None: return desc if not isinstance(desc, STRING_TYPES): raise TypeError( "predicate description for Matching must be a string, " ...
Return the placeholder part of matcher's ``__repr__``. def _get_placeholder_repr(self): """Return the placeholder part of matcher's ``__repr__``.""" placeholder = '...' if self.TRANSFORM is not None: placeholder = '%s(%s)' % (self.TRANSFORM.__name__, placeholder) return plac...
Ensure the matcher class definition is acceptable. :raise RuntimeError: If there is a problem def _validate_class_definition(meta, classname, bases, dict_): """Ensure the matcher class definition is acceptable. :raise RuntimeError: If there is a problem """ # let the BaseMatcher...
Checks whether given class name and dictionary define the :class:`BaseMatcher`. def _is_base_matcher_class_definition(meta, classname, dict_): """Checks whether given class name and dictionary define the :class:`BaseMatcher`. """ if classname != 'BaseMatcher': return...
Return names of magic methods defined by a class. :return: Iterable of magic methods, each w/o the ``__`` prefix/suffix def _list_magic_methods(meta, class_): """Return names of magic methods defined by a class. :return: Iterable of magic methods, each w/o the ``__`` prefix/suffix """ ...
if (!(this instanceof SemVer)) return new SemVer(version, loose); def semver(version, loose): if isinstance(version, SemVer): if version.loose == loose: return version else: version = version.version elif not isinstance(version, str): # xxx: raise Invalid...
Handler for the event emitted when autodoc processes a docstring. See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring. The TL;DR is that we can modify ``lines`` in-place to influence the output. def autodoc_process_docstring(app, what, name, obj, options, lines): """Handler for the ...
Raise ValidationError if the contact exists. def clean_email(self): """ Raise ValidationError if the contact exists. """ contacts = self.api.lists.contacts(id=self.list_id)['result'] for contact in contacts: if contact['email'] == self.cleaned_data['email']: raise f...
Create a contact with using the email on the list. def add_contact(self): """ Create a contact with using the email on the list. """ self.api.lists.addcontact( contact=self.cleaned_data['email'], id=self.list_id, method='POST')
Get or create an Api() instance using django settings. def api(self): """ Get or create an Api() instance using django settings. """ api = getattr(self, '_api', None) if api is None: self._api = mailjet.Api() return self._api
Get or create the list id. def list_id(self): """ Get or create the list id. """ list_id = getattr(self, '_list_id', None) if list_id is None: for l in self.api.lists.all()['lists']: if l['name'] == self.list_name: self._list_id = l['id'] ...
Portable version of inspect.getargspec(). Necessary because the original is no longer available starting from Python 3.6. :return: 4-tuple of (argnames, varargname, kwargname, defaults) Note that distinction between positional-or-keyword and keyword-only parameters will be lost, as the original g...
Reads values of "magic tags" defined in the given Python file. :param filename: Python filename to read the tags from :return: Dictionary of tags def read_tags(filename): """Reads values of "magic tags" defined in the given Python file. :param filename: Python filename to read the tags from :retu...
Normalize any unicode characters to ascii equivalent https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize def normalize_unicode(text): """ Normalize any unicode characters to ascii equivalent https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize """ if isi...
Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ Parses the given text and yields tokens which rep...
attempt to build using CMake >= 3 def cmake_setup(): """ attempt to build using CMake >= 3 """ cmake_exe = shutil.which('cmake') if not cmake_exe: raise FileNotFoundError('CMake not available') wopts = ['-G', 'MinGW Makefiles', '-DCMAKE_SH="CMAKE_SH-NOTFOUND'] if os.name == 'nt' else [...
attempt to build with Meson + Ninja def meson_setup(): """ attempt to build with Meson + Ninja """ meson_exe = shutil.which('meson') ninja_exe = shutil.which('ninja') if not meson_exe or not ninja_exe: raise FileNotFoundError('Meson or Ninja not available') if not (BINDIR / 'build...
Adds an occurrence of the term in the specified document. def add_term_occurrence(self, term, document): """ Adds an occurrence of the term in the specified document. """ if document not in self._documents: self._documents[document] = 0 if term not in self._terms: ...
Gets the frequency of the specified term in the entire corpus added to the HashedIndex. def get_total_term_frequency(self, term): """ Gets the frequency of the specified term in the entire corpus added to the HashedIndex. """ if term not in self._terms: raise...
Returns the frequency of the term specified in the document. def get_term_frequency(self, term, document, normalized=False): """ Returns the frequency of the term specified in the document. """ if document not in self._documents: raise IndexError(DOCUMENT_DOES_NOT_EXIST) ...
Returns the number of documents the specified term appears in. def get_document_frequency(self, term): """ Returns the number of documents the specified term appears in. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return le...
Returns the number of terms found within the specified document. def get_document_length(self, document): """ Returns the number of terms found within the specified document. """ if document in self._documents: return self._documents[document] else: raise...
Returns all documents related to the specified term in the form of a Counter object. def get_documents(self, term): """ Returns all documents related to the specified term in the form of a Counter object. """ if term not in self._terms: raise IndexError(TERM_...
Returns the Term-Frequency Inverse-Document-Frequency value for the given term in the specified document. If normalized is True, term frequency will be divided by the document length. def get_tfidf(self, term, document, normalized=False): """ Returns the Term-Frequency Inverse-Document-...
Returns a representation of the specified document as a feature vector weighted according the mode specified (by default tf-dif). A custom weighting function can also be passed which receives the hashedindex instance, the selected term and document as parameters. The result will be ret...
Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inverted Index using the tf-idf weighting by default. The term counts in each document can alternatively be used by specifying scheme='count'. A custom weighting function can also be...
Returns the first occurrence of an instance of type `klass` in the given list, or None if no such instance is present. def find_class_in_list(klass, lst): """ Returns the first occurrence of an instance of type `klass` in the given list, or None if no such instance is present. """ filtered = ...
Returns a tuple containing an entry corresponding to each of the requested class types, where the entry is either the first object instance of that type or None of no such instances are available. Example Usage: find_classes_in_list( [Address, Response], [<classes.Response....
Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API. def _build_parmlist(self, parameters): """ Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API. """ ...
Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters (=, &) may appear inside parameter values, provided the pa...
Send a http request to the given *url*, try to decode the reply assuming it's JSON in UTF-8, and return the result :returns: Decoded result, or None in case of an error :rtype: mixed def request(self, url): """ Send a http request to the given *url*, try to decode the r...
Issue a geocoding query for *address* to the Nominatim instance and return the decoded results :param address: a query string with an address or presumed parts of an address :type address: str or (if python2) unicode :param acceptlanguage: rfc2616 language code ...
Issue a reverse geocoding query for a place given by *lat* and *lon*, or by *osm_id* and *osm_type* to the Nominatim instance and return the decoded results :param lat: the geograpical latitude of the place :param lon: the geograpical longitude of the place :param osm_id: openst...
Define a grid using the specifications of a given model. Parameters ---------- model_name : string Name the model (see :func:`get_supported_models` for available model names). Supports multiple formats (e.g., 'GEOS5', 'GEOS-5' or 'GEOS_5'). **kwargs :...
Set-up a user-defined grid using specifications of a reference grid model. Parameters ---------- model_name : string name of the user-defined grid model. reference : string or :class:`CTMGrid` instance Name of the reference model (see :func:`get_supported...
Compute scalars or coordinates associated to the vertical layers. Parameters ---------- grid_spec : CTMGrid object CTMGrid containing the information necessary to re-construct grid levels for a given model coordinate system. Returns ------- dicti...
Calculate longitude-latitude grid for a specified resolution and configuration / ordering. Parameters ---------- rlon, rlat : float Resolution (in degrees) of longitude and latitude grids. halfpolar : bool (default=True) Polar grid boxes span half of rlat...
existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins! def _get_template_dirs(): """existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!"...
try to get a license from the classifiers def _license_from_classifiers(data): """try to get a license from the classifiers""" classifiers = data.get('classifiers', []) found_license = None for c in classifiers: if c.startswith("License :: OSI Approved :: "): found_license = c.repla...
try to get SDPX license def _normalize_license(data): """try to get SDPX license""" license = data.get('license', None) if not license: # try to get license from classifiers license = _license_from_classifiers(data) if license: if license in SDPX_LICENSES.keys(): dat...
Wrap an IPython's Prompt class This is needed in order for Prompt to inject the correct escape sequences at the right positions for shell integrations. def wrap_prompts_class(Klass): """ Wrap an IPython's Prompt class This is needed in order for Prompt to inject the correct escape sequences a...
A generator which yields a list of all valid keys starting at the given `start` offset. If `start` is `None`, we will start from the root of the tree. def get_all_keys(self, start=None): """ A generator which yields a list of all valid keys starting at the given `start` offset....
Replace the `*` placeholder in a format string (fmt), so that struct.calcsize(fmt) is equal to the given `size` using the format following the placeholder. Raises `ValueError` if number of `*` is larger than 1. If no `*` in `fmt`, returns `fmt` without checking its size! Examples -------- ...
Read pre- or suffix of line at current position with given format `fmt` (default 'i'). def _fix(self, fmt='i'): """ Read pre- or suffix of line at current position with given format `fmt` (default 'i'). """ fmt = self.endian + fmt fix = self.read(struct.calcsize(...
Return next unformatted "line". If format is given, unpack content, otherwise return byte string. def readline(self, fmt=None): """ Return next unformatted "line". If format is given, unpack content, otherwise return byte string. """ prefix_size = self._fix() if...
Skip the next line and returns position and size of line. Raises IOError if pre- and suffix of line do not match. def skipline(self): """ Skip the next line and returns position and size of line. Raises IOError if pre- and suffix of line do not match. """ position = self...
Write `line` (list of objects) with given `fmt` to file. The `line` will be chained if object is iterable (except for basestrings). def writeline(self, fmt, *args): """ Write `line` (list of objects) with given `fmt` to file. The `line` will be chained if object is iterable (exc...
Write `lines` with given `format`. def writelines(self, lines, fmt): """ Write `lines` with given `format`. """ if isinstance(fmt, basestring): fmt = [fmt] * len(lines) for f, line in zip(fmt, lines): self.writeline(f, line, self.endian)
Read while the most significant bit is set, then put the 7 least significant bits of all read bytes together to create a number. def read_varint(stream): """Read while the most significant bit is set, then put the 7 least significant bits of all read bytes together to create a number. """ value = ...
Open a GEOS-Chem BPCH file output as an xarray Dataset. Parameters ---------- filename : string Path to the output file to read in. {tracerinfo,diaginfo}_file : string, optional Path to the metadata "info" .dat files which are used to decipher the metadata corresponding to each ...
Open multiple bpch files as a single dataset. You must have dask installed for this to work, as this greatly simplifies issues relating to multi-file I/O. Also, please note that this is not a very performant routine. I/O is still limited by the fact that we need to manually scan/read through each bpch...
Write your forwards methods here. def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry in orm['multilingual_news.NewsEntry'].objects.all(): self.migrate_placeholder( ...
Return a bytes string that displays image given by bytes b in the terminal If filename=None, the filename defaults to "Unnamed file" width and height are strings, following the format N: N character cells. Npx: N pixels. N%: N percent of the session's width or height. 'auto...
Display the image given by the bytes b in the terminal. If filename=None the filename defaults to "Unnamed file". width and height are strings, following the format N: N character cells. Npx: N pixels. N%: N percent of the session's width or height. 'auto': The image's inhe...
Display an image in the terminal. A newline is not printed. width and height are strings, following the format N: N character cells. Npx: N pixels. N%: N percent of the session's width or height. 'auto': The image's inherent size will be used to determine an appropriate ...
Get requirements from pip requirement files. def get_requirements(*args): """Get requirements from pip requirement files.""" requirements = set() contents = get_contents(*args) for line in contents.splitlines(): # Strip comments. line = re.sub(r'^#.*|\s#.*', '', line) # Ignore e...
Gets a list of all known bank holidays, optionally filtered by division and/or year :param division: see division constants; defaults to common holidays :param year: defaults to all available years :return: list of dicts with titles, dates, etc def get_holidays(self, division=None, year=None): ...
Returns the next known bank holiday :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: dict def get_next_holiday(self, division=None, date=None): """ Returns the next known bank holiday ...
True if the date is a known bank holiday :param date: the date to check :param division: see division constants; defaults to common holidays :return: bool def is_holiday(self, date, division=None): """ True if the date is a known bank holiday :param date: the date to che...
Returns the next work day, skipping weekends and bank holidays :param division: see division constants; defaults to common holidays :param date: search starting from this date; defaults to today :return: datetime.date; NB: get_next_holiday returns a dict def get_next_work_day(self, division=Non...
True if the date is not a weekend or a known bank holiday :param date: the date to check :param division: see division constants; defaults to common holidays :return: bool def is_work_day(self, date, division=None): """ True if the date is not a weekend or a known bank holiday ...
Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data def get_all_regions_with_tiles(self): """ Generator which yields a set of (rx, ry) tuples which describe all regions for which the world has tile data """ for key...
Returns the coordinates of the given entity UUID inside this world, or `None` if the UUID is not found. def get_entity_uuid_coords(self, uuid): """ Returns the coordinates of the given entity UUID inside this world, or `None` if the UUID is not found. """ if uuid in self...
A dict whose keys are the UUIDs (or just IDs, in some cases) of entities, and whose values are the `(rx, ry)` coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world. def _entity_to_region_map(self): """ A dict whose ...
Convert a string into a fuzzy regular expression pattern. :param pattern: The input pattern (a string). :returns: A compiled regular expression object. This function works by adding ``.*`` between each of the characters in the input pattern and compiling the resulting expression into a case insens...
A list of :class:`PasswordEntry` objects that don't match the exclude list. def filtered_entries(self): """A list of :class:`PasswordEntry` objects that don't match the exclude list.""" return [ e for e in self.entries if not any(fnmatch.fnmatch(e.name.lower(), p.lower()) for p in self.excl...
Perform a "fuzzy" search that matches the given characters in the given order. :param filters: The pattern(s) to search for. :returns: The matched password names (a list of strings). def fuzzy_search(self, *filters): """ Perform a "fuzzy" search that matches the given characters in the...
Select a password from the available choices. :param arguments: Refer to :func:`smart_search()`. :returns: The name of a password (a string) or :data:`None` (when no password matched the given `arguments`). def select_entry(self, *arguments): """ Select a password fro...
Perform a simple search for case insensitive substring matches. :param keywords: The string(s) to search for. :returns: The matched password names (a generator of strings). Only passwords whose names matches *all* of the given keywords are returned. def simple_search(self, *keywords)...
Perform a smart search on the given keywords or patterns. :param arguments: The keywords or patterns to search for. :returns: The matched password names (a list of strings). :raises: The following exceptions can be raised: - :exc:`.NoMatchingPasswordError` when no matching pas...
A list of :class:`PasswordEntry` objects. def entries(self): """A list of :class:`PasswordEntry` objects.""" passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name)
An execution context created using :mod:`executor.contexts`. The value of :attr:`context` defaults to a :class:`~executor.contexts.LocalContext` object with the following characteristics: - The working directory of the execution context is set to the value of :attr:`directory...
Normalize the value of :attr:`directory` when it's set. def directory(self, value): """Normalize the value of :attr:`directory` when it's set.""" # Normalize the value of `directory'. set_property(self, "directory", parse_path(value)) # Clear the computed values of `context' and `entrie...
A list of :class:`PasswordEntry` objects. def entries(self): """A list of :class:`PasswordEntry` objects.""" timer = Timer() passwords = [] logger.info("Scanning %s ..", format_path(self.directory)) listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0"...
Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password storage directory doesn't exist. def ensure_directory_exists(self): """ Make sure :attr:`directory` exists. :raises: :exc:`.MissingPasswordStoreError` when the password st...
Format :attr:`text` for viewing on a terminal. :param include_password: :data:`True` to include the password in the formatted text, :data:`False` to exclude the password from the formatted text. :param use_colors: :data:`True` to use ANS...
Read an output's diaginfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- diaginfo_file : str Path to diaginfo.dat Returns ------- DataFrame containing the category information. def get_diaginfo(diaginfo_file): """ Rea...
Read an output's tracerinfo.dat file and parse into a DataFrame for use in selecting and parsing categories. Parameters ---------- tracerinfo_file : str Path to tracerinfo.dat Returns ------- DataFrame containing the tracer information. def get_tracerinfo(tracerinfo_file): """...
Read a chunk of data from a bpch output file. Parameters ---------- filename : str Path to file on disk containing the data file_position : int Position (bytes) where desired data chunk begins shape : tuple of ints Resultant (n-dimensional) shape of requested data; the chun...
Helper function to load the data referenced by this bundle. def _read(self): """ Helper function to load the data referenced by this bundle. """ if self._dask: d = da.from_delayed( delayed(read_from_bpch, )( self.filename, self.file_position, self.shape, ...
Close this bpch file. def close(self): """ Close this bpch file. """ if not self.fp.closed: for v in list(self.var_data): del self.var_data[v] self.fp.close()
Read the main metadata packaged within a bpch file, indicating the output filetype and its title. def _read_metadata(self): """ Read the main metadata packaged within a bpch file, indicating the output filetype and its title. """ filetype = self.fp.readline().strip() f...
Process the header information (data model / grid spec) def _read_header(self): """ Process the header information (data model / grid spec) """ self._header_pos = self.fp.tell() line = self.fp.readline('20sffii') modelname, res0, res1, halfpolar, center180 = line self._attribu...
Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein. def _read_var_data(self): """ Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data cont...
Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid. def broadcast_1d_array(arr, ndim, axis=1): """ Broadcast 1-d array `arr` t...
Return the current timestamp in machine local time. Parameters: ----------- time, date : Boolean Flag to include the time or date components, respectively, in the output. fmt : str, optional If passed, will override the time/date choice and use as the format string passe...
This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer instead of a boolean, and removes ...
Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ if command_status not in range(256): ...
Write your forwards methods here. def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for entry_title in orm.NewsEntryTitle.objects.all(): entry = NewsEntry.objects.get(pk=entry_title.entr...