text
stringlengths
18
773k
async def _raise_for_status(response): """Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. This fu...
async def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): """Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code...
async def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) ...
def get_numeric_value(string_value): """ parses string_value and returns only number-like part """ num_chars = ['.', '+', '-'] number = '' for c in string_value: if c.isdigit() or c in num_chars: number += c return number
def main(**kwargs): """Entry point to run databench.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s {}'.format(DATABENCH_VERSION)) parser.add_argument('--log', dest='loglevel', default="INFO", ...
def run(analysis, path=None, name=None, info=None, **kwargs): """Run a single analysis. :param Analysis analysis: Analysis class to run. :param str path: Path of analysis. Can be `__file__`. :param str name: Name of the analysis. :param dict info: Optional entries are ``version``, ``title``, ...
def _stringify_predicate_value(value): """Convert Python objects to Space-Track compatible strings - Booleans (``True`` -> ``'true'``) - Sequences (``[25544, 34602]`` -> ``'25544,34602'``) - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``) - ``None`` -> ``'null-val'`` """ if isi...
def args_repr(*args, **kwargs): """ Returns human-readable string representation of both positional and keyword arguments passed to the function. This function uses the built-in :func:`repr()` function to convert individual arguments to string. >>> args_repr("a", (1, 2), some_keyword = list("a...
def obj_repr(obj, *args, **kwargs): """ Returns human-readable string representation of an object given that it has been created by calling constructor with the specified positional and keyword arguments. This is a convenience function to help implement custom `__repr__()` methods. For example:...
def decode_filter(text, encoding='utf-8'): """ decode a binary object to str and filter out non-printable characters Parameters ---------- text: bytes the binary object to be decoded encoding: str the encoding to be used Returns ------- str the decoded a...
def dictmerge(x, y): """ merge two dictionaries """ z = x.copy() z.update(y) return z
def dissolve(inlist): """ list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve([[1, 2], [3, 4]]) [1, 2, 3, 4] ...
def finder(target, matchlist, foldermode=0, regex=False, recursive=True): """ function for finding files/folders in folders and their subdirectories Parameters ---------- target: str or list of str a directory, zip- or tar-archive or a list of them to be searched matchlist: list ...
def multicore(function, cores, multiargs, **singleargs): """ wrapper for multicore process execution Parameters ---------- function individual function to be applied to each process item cores: int the number of subprocesses started/CPUs used; this value is reduced in ca...
def parse_literal(x): """ return the smallest possible data type for a string or list of strings Parameters ---------- x: str or list a string to be parsed Returns ------- int, float or str the parsing result Examples -------- >>> isinstance(parse_liter...
def rescale(inlist, newrange=(0, 1)): """ rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) """ OldMax = max(inlist) OldMin = min(inlist) if OldMin == OldMax: raise RuntimeError('list contains of only one unique value') O...
def run(cmd, outdir=None, logfile=None, inlist=None, void=True, errorpass=False, env=None): """ | wrapper for subprocess execution including logfile writing and command prompt piping | this is a convenience wrapper around the :mod:`subprocess` module and calls its class :class:`~subprocess.Popen` inte...
def urlQueryParser(url, querydict): """ parse a url query """ address_parse = urlparse(url) return urlunparse(address_parse._replace(query=urlencode(querydict)))
def push(self, x): """ append items to the stack; input can be a single value or a list """ if isinstance(x, list): for item in x: self.stack.append(item) else: self.stack.append(x)
def pop(self): """ return the last stack element and delete it from the list """ if not self.empty(): val = self.stack[-1] del self.stack[-1] return val
def axes(self, offset = False): """returns measured value in miligauss""" reg, self._scale = self.SCALES[self._gauss] x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA) if x == -4096: x = OVERFLOW y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA) ...
def _ToString(x): """The default default formatter!.""" # Some cross-language values for primitives. This is tested in # jsontemplate_test.py. if x is None: return 'null' if isinstance(x, six.string_types): return x return pprint.pformat(x)
def _Pairs(data): """dictionary -> list of pairs""" keys = sorted(data) return [{'@key': k, '@value': data[k]} for k in keys]
def _Pluralize(value, unused_context, args): """Formatter to pluralize words.""" if len(args) == 0: s, p = '', 's' elif len(args) == 1: s, p = '', args[0] elif len(args) == 2: s, p = args else: # Should have been checked at compile time raise AssertionErr...
def _StrftimeGm(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns GM time. """ time_tuple = time.gmtime(value) return _StrftimeHelper(args, time_tuple)
def _StrftimeLocal(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns local time. """ time_tuple = time.localtime(value) return _StrftimeHelper(args, time_tuple)
def _TemplateExists(unused_value, context, args): """Returns whether the given name is in the current Template's template group.""" try: name = args[0] except IndexError: raise EvaluationError('The "template" predicate requires an argument.') return context.HasTemplate(name)
def SplitMeta(meta): """Split and validate metacharacters. Example: '{}' -> ('{', '}') This is public so the syntax highlighter and other tools can use it. """ n = len(meta) if n % 2 == 1: raise ConfigurationError( '%r has an odd number of metacharacters' % meta) return meta[...
def MakeTokenRegex(meta_left, meta_right): """Return a (compiled) regular expression for tokenization. Args: meta_left, meta_right: e.g. '{' and '}' - The regular expressions are memoized. - This function is public so the syntax highlighter can use it. """ key = meta_left, meta_right if key no...
def _MatchDirective(token): """Helper function for matching certain directives.""" # Tokens below must start with '.' if token.startswith('.'): token = token[1:] else: return None, None if token == 'end': return END_TOKEN, None if token == 'alternates with': ...
def _Tokenize(template_str, meta_left, meta_right, whitespace): """Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string).""" trimlen = len(meta_left) token_re = MakeTokenRegex(meta_left, meta_right) do_strip = (whitespace == 'strip-line') # Do this outside loop do_strip_part = False ...
def _CompileTemplate( template_str, builder, meta='{}', format_char='|', default_formatter='str', whitespace='smart'): """Compile the template string, calling methods on the 'program builder'. Args: template_str: The template string. It should not have any compilation options in the ...
def FromString(s, **kwargs): """Like FromFile, but takes a string.""" f = StringIO.StringIO(s) return FromFile(f, **kwargs)
def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None, _constructor=None): """Parse a template from a file, using a simple file format. This is useful when you want to include template options in a data file, rather than in the source code. The format is similar to HTTP...
def _MakeGroupFromRootSection(root_section, undefined_str): """Construct a dictinary { template name -> Template() instance } Args: root_section: _Section instance -- root of the original parse tree """ group = {} for statement in root_section.Statements(): if isinstance(statement, six.stri...
def JoinTokens(tokens): """Join tokens (which may be a mix of unicode and str values). See notes on unicode at the top. This function allows mixing encoded utf-8 byte string tokens with unicode tokens. (Python's default encoding is ASCII, and we don't want to change that.) We also want to support pure b...
def _DoRepeatedSection(args, context, callback, trace): """{.repeated section foo}""" block = args items = context.PushSection(block.section_name, block.pre_formatters) if items: if not isinstance(items, list): raise EvaluationError('Expected a list; got %s' % type(items)) ...
def _DoSection(args, context, callback, trace): """{.section foo}""" block = args # If a section present and "true", push the dictionary onto the stack as the # new context, and show it if context.PushSection(block.section_name, block.pre_formatters): _Execute(block.Statements(), context, ca...
def _DoPredicates(args, context, callback, trace): """{.predicate?} Here we execute the first clause that evaluates to true, and then stop. """ block = args value = context.Lookup('@') for (predicate, args, func_type), statements in block.clauses: if func_type == ENHANCED_FUNC: ...
def _DoSubstitute(args, context, callback, trace): """Variable substitution, i.e. {foo} We also implement template formatters here, i.e. {foo|template bar} as well as {.template FOO} for templates that operate on the root of the data dict rather than a subtree. """ name, formatters = args if ...
def _Execute(statements, context, callback, trace): """Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion. """ # Every time we call _Execute, incre...
def expand(template_str, dictionary, **kwargs): """Free function to expands a template string with a data dictionary. This is useful for cases where you don't care about saving the result of compilation (similar to re.match('.*', s) vs DOT_STAR.match(s)) """ t = Template(template_str, **kwargs) retur...
def _FlattenToCallback(tokens, callback): """Takes a nested list structure and flattens it. ['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); """ for t in tokens: if isinstance(t, six.string_types): callback(t) else: _FlattenToCallback(t, callback)
def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'): """OBSOLETE old API.""" try: body_data = data[body_subtree] except KeyError: raise EvaluationError('Data dictionary has no subtree %r' % body_subtree) tokens_body = [] template.execute(body_data, tok...
def expand_with_style(template, style, data, body_subtree='body'): """Expand a data dictionary with a template AND a style. DEPRECATED -- Remove this entire function in favor of expand(d, style=style) A style is a Template instance that factors out the common strings in several "body" templates. Args: ...
def LookupWithType(self, user_str): """ Returns: ref: Either a template instance (itself) or _TemplateRef """ prefix = 'template ' ref = None # fail the lookup by default if user_str.startswith(prefix): name = user_str[len(prefix):] if name == 'SELF...
def _GetFormatter(self, format_str): """ The user's formatters are consulted first, then the default formatters. """ formatter, args, func_type = self.formatters.LookupWithType(format_str) if formatter: return formatter, args, func_type else: raise BadForm...
def _GetPredicate(self, pred_str, test_attr=False): """ The user's predicates are consulted first, then the default predicates. """ predicate, args, func_type = self.predicates.LookupWithType(pred_str) if predicate: pred = predicate, args, func_type else: ...
def NewSection(self, token_type, section_name, pre_formatters): """For sections or repeated sections.""" pre_formatters = [self._GetFormatter(f) for f in pre_formatters] # TODO: Consider getting rid of this dispatching, and turn _Do* into methods if token_type == REPEATED_SECTIO...
def NewOrClause(self, pred_str): """ {.or ...} Can appear inside predicate blocks or section blocks, with slightly different meaning. """ if pred_str: pred = self._GetPredicate(pred_str, test_attr=False) else: pred = None self.current_section.NewOrClau...
def NewPredicateSection(self, pred_str, test_attr=False): """For chains of predicate clauses.""" pred = self._GetPredicate(pred_str, test_attr=test_attr) block = _PredicateSection() block.NewOrClause(pred) self._NewSection(_DoPredicates, block)
def PushSection(self, name, pre_formatters): """Given a section name, push it on the top of the stack. Returns: The new section, or None if there is no such section. """ if name == '@': value = self.stack[-1].context else: value = self.stack[-1].context.get...
def Next(self): """Advance to the next item in a repeated section. Raises: StopIteration if there are no more elements """ stacktop = self.stack[-1] # Now we're iterating -- push a new mutable object onto the stack if stacktop.index == -1: stacktop = _...
def _LookUpStack(self, name): """Look up the stack for the given name.""" i = len(self.stack) - 1 while 1: frame = self.stack[i] if name == '@index': if frame.index != -1: # -1 is undefined return frame.index # @index is 1-based ...
def Lookup(self, name): """Get the value associated with a name in the current context. The current context could be an dictionary in a list, or a dictionary outside a list. Args: name: name to lookup, e.g. 'foo' or 'foo.bar.baz' Returns: The value, or self.undefined_str Rais...
def execute(self, data_dict, callback, group=None, trace=None): """Low level method to expand the template piece by piece. Args: data_dict: The JSON data dictionary. callback: A callback which should be called with each expanded token. group: Dictionary of name -> Template instance (for s...
def expand(self, *args, **kwargs): """Expands the template with the given data dictionary, returning a string. This is a small wrapper around execute(), and is the most convenient interface. Args: data_dict: The JSON data dictionary. Like the builtin dict() constructor, it can tak...
def tokenstream(self, data_dict): """Yields a list of tokens resulting from expansion. This may be useful for WSGI apps. NOTE: In the current implementation, the entire expanded template must be stored memory. NOTE: This is a generator, but JavaScript doesn't have generators. """ toke...
def align_unwrapped(sino): """Align an unwrapped phase array to zero-phase All operations are performed in-place. """ samples = [] if len(sino.shape) == 2: # 2D # take 1D samples at beginning and end of array samples.append(sino[:, 0]) samples.append(sino[:, 1]) ...
def divmod_neg(a, b): """Return divmod with closest result to zero""" q, r = divmod(a, b) # make sure r is close to zero sr = np.sign(r) if np.abs(r) > b/2: q += sr r -= b * sr return q, r
def sinogram_as_radon(uSin, align=True): r"""Compute the phase from a complex wave field sinogram This step is essential when using the ray approximation before computation of the refractive index with the inverse Radon transform. Parameters ---------- uSin: 2d or 3d complex ndarray ...
def sinogram_as_rytov(uSin, u0=1, align=True): r"""Convert the complex wave field sinogram to the Rytov phase This method applies the Rytov approximation to the recorded complex wave sinogram. To achieve this, the following filter is applied: .. math:: u_\mathrm{B}(\mathbf{r}) = u_\mathrm{...
def json_encoder_default(obj): """Handle more data types than the default JSON encoder. Specifically, it treats a `set` and a `numpy.array` like a `list`. Example usage: ``json.dumps(obj, default=json_encoder_default)`` """ if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'): ...
def fig_to_src(figure, image_format='png', dpi=80): """Convert a matplotlib figure to an inline HTML image. :param matplotlib.figure.Figure figure: Figure to display. :param str image_format: png (default) or svg :param int dpi: dots-per-inch for raster graphics. :rtype: str """ if image_fo...
def Reset(self): ' Reset Axis and set default parameters for H-bridge ' spi.SPI_write(self.CS, [0xC0, 0x60]) # reset # spi.SPI_write(self.CS, [0x14, 0x14]) # Stall Treshold setup # spi.SPI_write(self.CS, [0xFF, 0xFF]) # spi.SPI_write(self.CS, [0x13, 0x13]) # Over Cu...
def MaxSpeed(self, speed): ' Setup of maximum speed ' spi.SPI_write(self.CS, [0x07, 0x07]) # Max Speed setup spi.SPI_write(self.CS, [0x00, 0x00]) spi.SPI_write(self.CS, [speed, speed])
def ReleaseSW(self): ' Go away from Limit Switch ' while self.ReadStatusBit(2) == 1: # is Limit Switch ON ? spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW while self.IsBusy(): pass self.MoveWait(10)
def Move(self, units): ' Move some distance units from current position ' steps = units * self.SPU # translate units to steps if steps > 0: # look for direction spi.SPI_write(self.CS, [0x40 | (~self.Dir & 1), 0x40 | (~self.Dir & 1)]) ...
def bbox(coordinates, crs, outname=None, format='ESRI Shapefile', overwrite=True): """ create a bounding box vector object or shapefile from coordinates and coordinate reference system. The CRS can be in either WKT, EPSG or PROJ4 format Parameters ---------- coordinates: dict a dict...
def dissolve(infile, outfile, field, layername=None): """ dissolve the polygons of a vector file by an attribute field Parameters ---------- infile: str the input vector file outfile: str the output shapefile field: str the field name to merge the polygons by laye...
def feature2vector(feature, ref, layername=None): """ create a Vector object from ogr features Parameters ---------- feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature` a single feature or a list of features ref: Vector a reference Vector object to retrieve...
def intersect(obj1, obj2): """ intersect two Vector objects Parameters ---------- obj1: Vector the first vector object; this object is reprojected to the CRS of obj2 if necessary obj2: Vector the second vector object Returns ------- Vector the intersect of o...
def addfeature(self, geometry, fields=None): """ add a feature to the vector object from a geometry Parameters ---------- geometry: :osgeo:class:`ogr.Geometry` the geometry to add as a feature fields: dict or None the field names and value...
def addfield(self, name, type, width=10): """ add a field to the vector layer Parameters ---------- name: str the field name type: int the OGR Field Type (OFT), e.g. ogr.OFTString. See `Module ogr <https://gdal.org/python/osgeo.ogr-mod...
def addlayer(self, name, srs, geomType): """ add a layer to the vector layer Parameters ---------- name: str the layer name srs: int, str or :osgeo:class:`osr.SpatialReference` the spatial reference system. See :func:`spatialist.auxil.crsConvert` ...
def addvector(self, vec): """ add a vector object to the layer of the current Vector object Parameters ---------- vec: Vector the vector object to add merge: bool merge overlapping polygons? Returns ------- """ ve...
def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True): """ create a bounding box from the extent of the Vector object Parameters ---------- outname: str or None the name of the vector file to be written; if None, a Vector object is returned fo...
def convert2wkt(self, set3D=True): """ export the geometry of each feature as a wkt string Parameters ---------- set3D: bool keep the third (height) dimension? Returns ------- """ features = self.getfeatures() for feature in ...
def getFeatureByAttribute(self, fieldname, attribute): """ get features by field attribute Parameters ---------- fieldname: str the name of the queried field attribute: int or str the field value of interest Returns ------- ...
def getFeatureByIndex(self, index): """ get features by numerical (positional) index Parameters ---------- index: int the queried index Returns ------- :osgeo:class:`ogr.Feature` the requested feature """ feature =...
def init_layer(self): """ initialize a layer object Returns ------- """ self.layer = self.vector.GetLayer() self.__features = [None] * self.nfeatures
def load(self): """ load all feature into memory Returns ------- """ self.layer.ResetReading() for i in range(self.nfeatures): if self.__features[i] is None: self.__features[i] = self.layer[i]
def reproject(self, projection): """ in-memory reprojection Parameters ---------- projection: int, str or :osgeo:class:`osr.SpatialReference` the target CRS. See :func:`spatialist.auxil.crsConvert`. Returns ------- """ srs_out = crsC...
def setCRS(self, crs): """ directly reset the spatial reference system of the vector object. This is not going to reproject the Vector object, see :meth:`reproject` instead. Parameters ---------- crs: int, str or :osgeo:class:`osr.SpatialReference` the input ...
def write(self, outfile, format='ESRI Shapefile', overwrite=True): """ write the Vector object to a file Parameters ---------- outfile: the name of the file to write format: str the output file format overwrite: bool overwrite ...
def write_byte_data(self, address, register, value): """ SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr...
def write_word_data(self, address, register, value): """ SMBus Write Word: i2c_smbus_write_word_data() ============================================== This is the opposite of the Read Word operation. 16 bits of data is written to a device, to the designated register that is ...
def write_block_data(self, address, register, value): """ SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified ...
def block_process_call(self, address, register, value): """ SMBus Block Write - Block Read Process Call =========================================== SMBus Block Write - Block Read Process Call was introduced in Revision 2.0 of the specification. This command selects a de...
def write_i2c_block_data(self, address, register, value): """ I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Write: i2c_smbus_write_i2c_block_data() ==================================================...
def read_i2c_block_data(self, address, register, length): """ I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Read: i2c_smbus_read_i2c_block_data() ================================================ ...
def _init_zmq(self, port_publish, port_subscribe): """Initialize zmq messaging. Listen on sub_port. This port might at some point receive the message to start publishing on a certain port, but until then, no publishing. """ log.debug('kernel {} publishing on port {}' ...
def run_process(self, analysis, action_name, message='__nomessagetoken__'): """Executes an process in the analysis with the given message. It also handles the start and stop signals in case an process_id is given. This method is similar to the method in databench.Analysis. """ ...
def event_loop(self): """Event loop.""" try: zmq.eventloop.ioloop.IOLoop.current().start() except KeyboardInterrupt: zmq.eventloop.ioloop.IOLoop.current().stop()
def emit(self, signal, message, analysis_id): """Emit signal to main. Args: signal: Name of the signal to be emitted. message: Message to be sent. analysis_id: Identifies the instance of this analysis. """ log.debug('kernel {} zmq send ({}): {}' ...
def set_ports(self, port0 = 0x00, port1 = 0x00): 'Writes specified value to the pins defined as output by config_ports() method. Writing to input pins has no effect.' self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0) self.bus.write_byte_data(self.address, self.OUTPUT_PORT1, port1)...
def get_ports(self): 'Reads logical values at pins.' return (self.bus.read_byte_data(self.address, self.STATUS_PORT0), self.bus.read_byte_data(self.address, self.STATUS_PORT1));
def get_config(self): 'Reads logical values at pins.' return (self.bus.read_byte_data(self.address, self.CONTROL_PORT0), self.bus.read_byte_data(self.address, self.CONTROL_PORT1));
def set_pullups(self, port0 = 0x00, port1 = 0x00): 'Sets INPUT (1) or OUTPUT (0) direction on pins. Inversion setting is applicable for input pins 1-inverted 0-noninverted input polarity.' self.bus.write_byte_data(self.address, self.PULLUP_PORT0, port0) self.bus.write_byte_data(self.address, se...
def set_ports(self, port0 = 0x00, port1 = 0x00): 'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.' self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1) retu...