code stringlengths 1 18.2k |
|---|
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 forms.ValidationError( _(u'This email is already subscribed')) return self.cleaned_data['email'] |
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') |
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 |
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'] if not getattr(self, '_list_id', None): self._list_id = self.api.lists.create( label=self.list_label, name=s... |
def getargspec(obj): """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 ... |
4-tuple argnames = [] varargname, kwargname = None, None defaults = [] for name, param in inspect.signature(obj): if param.kind == inspect.Parameter.VAR_POSITIONAL: varargname = name elif param.kind == inspect.Parameter.VAR_KEYWORD: kwargname = name else: argnames.append(name) if param.default is not inspect.Parameter.... |
def read_tags(filename): """Reads values of "magic tags" defined in the given Python file. :param filename: Python filename to read the tags from :return: Dictionary of tags """ with open(filename) as f: ast_tree = ast.parse(f.read(), filename) res = {} for node in ast.walk(ast_tree): if type(node) is not ast.Assign: c... |
= target.id[2:-2] res[name] = ast.literal_eval(node.value) return res |
def normalize_unicode(text): """ Normalize any unicode characters to ascii equivalent https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize """ if isinstance(text, six.text_type): return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf8') else: return text |
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ 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. """ if ngrams is None: ngrams = 1 text = re.sub(re.compile('\'s'),... |
i in range(len(tokens)): tokens[i] = tokens[i].strip(punctuation) if len(tokens[i]) < min_length or tokens[i] in stopwords: break if ignore_numeric and isnumeric(tokens[i]): break else: yield tuple(tokens) |
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 [] subprocess.check_call([cmake_exe] + wopts + [str(SRCDIR)], cwd=BIN... |
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.ninja').is_file(): subprocess.check_call([meson_exe, str(SRCDIR)], cwd=BIN... |
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: if self._freeze: return else: self._terms[term] = collections.Counter() if document not in self._terms[term]: sel... |
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 IndexError(TERM_DOES_NOT_EXIST) return sum(self._terms[term].values()) |
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) if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) result = self._terms[term].get(document, 0)... |
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 len(self._terms[term]) |
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 IndexError(DOCUMENT_DOES_NOT_EXIST) |
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_DOES_NOT_EXIST) else: return self._terms[term] |
def get_tfidf(self, term, document, normalized=False): """ 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. """ tf = self.get_term_frequency(term, document) # Speeds up performance by a... |
= 1 + self.get_document_frequency(term) n = 2 + len(self._documents) if normalized: tf /= self.get_document_length(document) return tf * math.log10(n / df) else: return 0.0 |
def generate_document_vector(self, doc, mode='tfidf'): """ 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 parameter... |
required using the `np.asarray` method Available built-in modes: * tfidf: Term Frequency Inverse Document Frequency * ntfidf: Normalized Term Frequency Inverse Document Frequency * tf: Term Frequency * ntf: Normalized Term Frequency """ if mode == 'tfidf': selected_function = HashedIndex.get_tfidf elif mode == 'ntfidf'... |
hasattr(mode, '__call__'): selected_function = mode else: raise ValueError('Unexpected mode: %s', mode) result = [] for term in self._terms: result.append(selected_function(self, term, doc)) return result |
def generate_feature_matrix(self, mode='tfidf'): """ 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 ... |
the matrix is equal to m x n where m is the number of documents and n is the number of terms. The list-of-lists format returned by this function can be very easily converted to a numpy matrix if required using the `np.as_matrix` method. """ result = [] for doc in self._documents: result.append(self.generate_document_ve... |
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 = list(filter(lambda x: x.__class__ == klass, lst)) if filtered: return filtered[0] return None |
def find_classes_in_list(klasses, lst): """ 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...... |
def _build_parmlist(self, parameters): """ Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API. """ args = [] for key, value in parameters.items(): if not value is None: # We always use the explicit-length keyname format, to reduce the chance # of requests failin... |
except NameError: classinfo = str if isinstance(value, classinfo): key = '%s[%d]' % (key.upper(), len(value.encode('utf-8'))) else: key = '%s[%d]' % (key.upper(), len(str(value))) args.append('%s=%s' % (key, value)) args.sort() parmlist = '&'.join(args) return parmlist |
def _parse_parmlist(self, parmlist): """ 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 parameter has an exp... |
the value of A is "B&B") A[1]=B&C[3]=D=7 (Here, the value of C is "D=7") """ parmlist = "&" + parmlist name_re = re.compile(r'\&([A-Z0-9_]+)(\[\d+\])?=') results = {} offset = 0 match = name_re.search(parmlist, offset) while match: name, len_suffix = match.groups() offset = match.end() if len_suffix: val_len = int(len_... |
parmlist val_len = len(parmlist) - match.end() value = parmlist[match.end() : match.end() + val_len] results[name.lower()] = value match = name_re.search(parmlist, offset) return results |
def request(self, url): """ 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 """ self.logger.debug('url:\n' + url) try: response = urlopen(url) return json.loads(response.read().decode('... |
def query(self, address, acceptlanguage=None, limit=20, countrycodes=None): """ 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: ... |
None :param countrycodes: restrict the search to countries given by their ISO 3166-1alpha2 codes (cf. https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ) :type countrycodes: str iterable :returns: a list of search results (each a dict) :rtype: list or None """ url = self.url + '&q=' + quote_plus(address) if acceptlangua... |
self.request(url) |
def query(self, lat=None, lon=None, osm_id=None, osm_type=None, acceptlanguage='', zoom=18): """ 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 ... |
osm_type :type osm_type: str :param acceptlanguage: rfc2616 language code :type acceptlanguage: str or None :param zoom: zoom factor between from 0 to 18 :type zoom: int or None or a key in :data:`zoom_aliases` :param countrycodes: restrict the search to countries given by their ISO 3166-1alpha2 codes (cf. https://en.w... |
or None :raise: NominatimException if invalid zoom value """ url = self.url if osm_id is not None and osm_type not in ('N', 'W', 'R'): raise NominatimException('invalid osm_type') if osm_id is not None and osm_type is not None: url += '&osm_id=' + osm_id + '&osm_type=' + osm_type elif lat is not None and lon is not Non... |
str(lon) else: return None if acceptlanguage: url += '&accept-language=' + acceptlanguage if zoom in zoom_aliases: zoom = zoom_aliases[zoom] if not isinstance(zoom, int) or zoom < 0 or zoom > 18: raise NominatimException('zoom must effectively be betwen 0 and 18') url +='&zoom=' + str(zoom) return self.request(url) |
def from_model(cls, model_name, **kwargs): """ 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 : string Parameters tha... |
float) Horizontal grid resolution (lon, lat) or (DI, DJ) [degrees] Psurf : float Average surface pressure [hPa] (default: 1013.15) Notes ----- Regridded vertical models may have several valid names (e.g., 'GEOS5_47L' and 'GEOS5_REDUCED' refer to the same model). """ settings = _get_model_info(model_name) model = settin... |
def copy_from_model(cls, model_name, reference, **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_m... |
(see :class:`CTMGrid` parameters). Returns ------- A :class:`CTMGrid` object. """ if isinstance(reference, cls): settings = reference.__dict__.copy() settings.pop('model') else: settings = _get_model_info(reference) settings.pop('model_name') settings.update(kwargs) settings['reference'] = reference return cls(model_na... |
def get_layers(self, Psurf=1013.25, Ptop=0.01, **kwargs): """ 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 ------- dictionary of ver... |
For pure sigma grids, sigma coordinates are given by the esig (edges) and csig (centers). For both pure sigma and hybrid grids, pressures at layers edges L are calculated as follows: .. math:: P_e(L) = A_p(L) + B_p(L) * (P_{surf} - C_p) where :math:`P_{surf}`, :math:`P_{top}` Air pressures at the surface and the top of... |
instance). :math:`A_p(L)`, :math:`Bp(L)` Specified in the grid set-up (`Ap` and `Bp` attributes) for hybrid grids, or respectively equals :math:`P_{top}` and :attr:`esig` attribute for pure sigma grids. :math:`Cp(L)` equals :math:`P_{top}` for pure sigma grids or equals 0 for hybrid grids. Pressures at grid centers are... |
of grid edges and grid centers are given by; .. math:: ETA_{e}(L) = (P_e(L) - P_{top}) / (P_{surf} - P_{top}) .. math:: ETA_{c}(L) = (P_c(L) - P_{top}) / (P_{surf} - P_{top}) Altitude values are fit using a 5th-degree polynomial; see `gridspec.prof_altitude` for more details. """ Psurf = np.asarray(Psurf) output_ndims ... |
or an array" " with <= 2 dimensions (or None)") # Compute all variables: takes not much memory, fast # and better for code reading SIGe = None SIGc = None ETAe = None ETAc = None if self.hybrid: try: Ap = broadcast_1d_array(self.Ap, output_ndims) Bp = broadcast_1d_array(self.Bp, output_ndims) except KeyError: raise Val... |
0. else: try: Bp = SIGe = broadcast_1d_array(self.esig, output_ndims) SIGc = broadcast_1d_array(self.csig, output_ndims) except KeyError: raise ValueError("Impossible to compute vertical levels," " data is missing (esig, csig)") Ap = Cp = Ptop Pe = Ap + Bp * (Psurf - Cp) Pc = 0.5 * (Pe[0:-1] + Pe[1:]) if self.hybrid: E... |
else: SIGe = SIGe * np.ones_like(Psurf) SIGc = SIGc * np.ones_like(Psurf) Ze = prof_altitude(Pe, **kwargs) Zc = prof_altitude(Pc, **kwargs) all_vars = {'eta_edges': ETAe, 'eta_centers': ETAc, 'sigma_edges': SIGe, 'sigma_centers': SIGc, 'pressure_edges': Pe, 'pressure_centers': Pc, 'altitude_edges': Ze, 'altitude_center... |
def get_lonlat(self): """ 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 relative to the other grid cells. cent... |
number of grid cells in each direction Nlon = int(360. / rlon) Nlat = int(180. / rlat) + self.halfpolar # Compute grid cell edges elon = np.arange(Nlon + 1) * rlon - np.array(180.) elon -= rlon / 2. * self.center180 elat = np.arange(Nlat + 1) * rlat - np.array(90.) elat -= rlat / 2. * self.halfpolar elat[0] = -90. elat... |
grid cell centers clon = (elon - (rlon / 2.))[1:] clat = np.arange(Nlat) * rlat - np.array(90.) # Fix grid boundaries if halfpolar if self.halfpolar: clat[0] = (elat[0] + elat[1]) / 2. clat[-1] = -clat[0] else: clat += (elat[1] - elat[0]) / 2. return { "lon_centers": clon, "lat_centers": clat, "lon_edges": elon, "lat_e... |
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!""" return filter(lambda x: os.path.exists(x), [ # user dir os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'), # system wide dir os.path.joi... |
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.replace("License :: OSI Approved :: ", "") return found_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(): data['license'] = SDPX_LICENSES[license] else: data['license'] = "%s (FIXME:No S... |
def wrap_prompts_class(Klass): """ 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. """ try: from prompt_toolkit.token import ZeroWidthEscape except ImportError: return Klass class ITerm2IPythonPrompt(Klass): def in_p... |
def get_all_keys(self, start=None): """ 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. """ s = self.stream if not start: start = HEADER_SIZE + self.block_size * self.root_block s.seek(start) block_type = s.read(2) if... |
in range(num_keys): cur_key = reader.read(self.key_size) # We to a tell/seek here so that the user can read from # the file while this loop is still being run cur_pos = s.tell() yield cur_key s.seek(cur_pos) length = sbon.read_varint(reader) reader.seek(length, 1) elif block_type == INDEX: (_, num_keys, first_child) = ... |
# Read pointer to the child block. next_child = struct.unpack('>i', s.read(4))[0] children.append(next_child) for child_loc in children: for key in self.get_all_keys(HEADER_SIZE + self.block_size * child_loc): yield key elif block_type == FREE: pass else: raise Exception('Unhandled block type: {}'.format(block_type)) |
def _replace_star(fmt, size): """ 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 -----... |
ValueError("More than one `*` in format (%s)." % fmt) if n_stars: i = fmt.find('*') s = struct.calcsize(fmt.replace(fmt[i:i + 2], '')) n = old_div((size - s), struct.calcsize(fmt[i + 1])) fmt = fmt.replace('*', str(n)) return fmt |
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(fmt)) if fix: return struct.unpack(fmt, fix)[0] else: raise EOFError |
def readline(self, fmt=None): """ Return next unformatted "line". If format is given, unpack content, otherwise return byte string. """ prefix_size = self._fix() if fmt is None: content = self.read(prefix_size) else: fmt = self.endian + fmt fmt = _replace_star(fmt, prefix_size) content = struct.unpack(fmt, self.read(pr... |
prefix_size != suffix_size: raise IOError(_FIX_ERROR) return content |
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.tell() prefix = self._fix() self.seek(prefix, 1) # skip content suffix = self._fix() if prefix != suffix: raise IOError(_FIX_ERROR) return position, prefix |
def writeline(self, fmt, *args): """ Write `line` (list of objects) with given `fmt` to file. The `line` will be chained if object is iterable (except for basestrings). """ fmt = self.endian + fmt size = struct.calcsize(fmt) fix = struct.pack(self.endian + 'i', size) line = struct.pack(fmt, *args) self.write(fix) self.... |
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) |
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 = 0 while True: byte = ord(stream.read(1)) if not byte & 0b10000000: return value << 7 | byte value = value << 7 | (byte & 0b01111111) |
def open_bpchdataset(filename, fields=[], categories=[], tracerinfo_file='tracerinfo.dat', diaginfo_file='diaginfo.dat', endian=">", decode_cf=True, memmap=True, dask=True, return_store=False): """ Open a GEOS-Chem BPCH file output as an xarray Dataset. Parameters ---------- filename : string Path to the output file to... |
will look for them in the current directory or fall back on a generic set. fields : list, optional List of a subset of variable names to return. This can substantially improve read performance. Note that the field here is just the tracer name - not the category, e.g. 'O3' instead of 'IJ-AVG-$_O3'. categories : list, op... |
look through. This can substantially improve read performance. endian : {'=', '>', '<'}, optional Endianness of file on disk. By default, "big endian" (">") is assumed. decode_cf : bool Enforce CF conventions for variable names, units, and other metadata default_dtype : numpy.dtype, optional Default datatype for variab... |
be memory-mapped from disk instead of eagerly loaded into memory dask : bool Flag indicating that data reading should be deferred (delayed) to construct a task-graph for later execution return_store : bool Also return the underlying DataStore to the user Returns ------- ds : xarray.Dataset Dataset containing the reques... |
: xarray.AbstractDataStore Underlying DataStore which handles the loading and processing of bpch files on disk """ store = BPCHDataStore( filename, fields=fields, categories=categories, tracerinfo_file=tracerinfo_file, diaginfo_file=diaginfo_file, endian=endian, use_mmap=memmap, dask_delayed=dask ) ds = xr.Dataset.load... |
decode_cf: decoded_vars = OrderedDict() rename_dict = {} for v in ds.variables: cf_name = cf.get_valid_varname(v) rename_dict[v] = cf_name new_var = cf.enforce_cf_variable(ds[v]) decoded_vars[cf_name] = new_var ds = xr.Dataset(decoded_vars, attrs=ds.attrs.copy()) # ds.rename(rename_dict, inplace=True) # TODO: There's a... |
kept track of them as we parsed the data. # ds = xr.decode_cf(ds, decode_times=False) # Set attributes for CF conventions ts = get_timestamp() ds.attrs.update(dict( Conventions='CF1.6', source=filename, tracerinfo=tracerinfo_file, diaginfo=diaginfo_file, filetype=store._bpch.filetype, filetitle=store._bpch.filetitle, h... |
store else: return ds |
def open_mfbpchdataset(paths, concat_dim='time', compat='no_conflicts', preprocess=None, lock=None, **kwargs): """ 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 performa... |
we can figure out what its contents are, since that metadata isn't saved anywhere. So this routine will actually sequentially load Datasets for each bpch file, then concatenate them along the "time" axis. You may wish to simply process each file individually, coerce to NetCDF, and then ingest through xarray as normal. ... |
matter as they will be lexicographically sorted before we read in the data concat_dim : str, default='time' Dimension to concatenate Datasets over. We default to "time" since this is how GEOS-Chem splits output files compat : str (optional) String indicating how to compare variables of the same name for potential confl... |
against each other to ensure common dimensions. - 'equals': all values and dimensions must be the same. - 'identical': all values, dimensions and attributes must be the same. - 'no_conflicts': only values which are not null in both datasets must be equal. The returned dataset then contains the combination of all non-nu... |
Dataset prior to concatenation lock : False, True, or threading.Lock (optional) Passed to :py:func:`dask.array.from_array`. By default, xarray employs a per-variable lock when reading data from NetCDF files, but this model has not yet been extended or implemented for bpch files and so this is not actually used. However... |
to pass to :py:func:`xbpch.open_bpchdataset`. """ from xarray.backends.api import _MultiFileCloser # TODO: Include file locks? # Check for dask dask = kwargs.pop('dask', False) if not dask: raise ValueError("Reading multiple files without dask is not supported") kwargs['dask'] = True # Add th if isinstance(paths, bases... |
in paths] bpch_objs = [ds._file_obj for ds in datasets] if preprocess is not None: datasets = [preprocess(ds) for ds in datasets] # Concatenate over time combined = xr.auto_combine(datasets, compat=compat, concat_dim=concat_dim) combined._file_obj = _MultiFileCloser(bpch_objs) combined.attrs = datasets[0].attrs ts = ge... |
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( orm, entry, 'excerpt', 'multilingual_news_excerpt', 'excerpt') self.migrate_placehol... |
def image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None): """ 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 p... |
an appropriate dimension. preserve_aspect_ratio sets whether the aspect ratio of the image is preserved. The default (None) is True unless both width and height are set. See https://www.iterm2.com/documentation-images.html """ if preserve_aspect_ratio is None: if width != 'auto' and height != 'auto': preserve_aspect_ra... |
'height': height, 'preserve_aspect_ratio': int(preserve_aspect_ratio), } # IMAGE_CODE is a string because bytes doesn't support formatting return IMAGE_CODE.format(**data).encode('ascii') |
def display_image_bytes(b, filename=None, inline=1, width='auto', height='auto', preserve_aspect_ratio=None): """ 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%: ... |
preserve_aspect_ratio sets whether the aspect ratio of the image is preserved. The default (None) is True unless both width and height are set. See https://www.iterm2.com/documentation-images.html """ sys.stdout.buffer.write(image_bytes(b, filename=filename, inline=inline, width=width, height=height, preserve_aspect_ra... |
def display_image_file(fn, width='auto', height='auto', preserve_aspect_ratio=None): """ 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 w... |
preserved. The default (None) is True unless both width and height are set. See https://www.iterm2.com/documentation-images.html """ with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f: sys.stdout.buffer.write(image_bytes(f.read(), filename=fn, width=width, height=height, preserve_aspect_ratio=preserve_aspec... |
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 empty lines if line and not line.isspace(): requirements.add(re.sub(r'\s+', '', line)) ... |
def get_holidays(self, division=None, year=None): """ 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 """ if division: holi... |
in six.iteritems(self.data)) ) holidays = filter(lambda holiday: holiday['date'] in dates_in_common, holidays) if year: holidays = filter(lambda holiday: holiday['date'].year == year, holidays) return list(holidays) |
def get_next_holiday(self, division=None, date=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 """ date = date or datetime.date.today() for holiday in self.get_holidays(divisi... |
def is_holiday(self, date, division=None): """ 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 """ return date in (holiday['date'] for holiday in self.get_holidays(division=division)) |
def get_next_work_day(self, division=None, date=None): """ 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 """ da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.