INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Plot a nuclear chart with ( N Z ) as axis and the values of the Table as a color scale
def chart_plot(self, ax=None, cmap='RdBu', xlabel='N', ylabel='Z', grid_on=True, colorbar=True): """Plot a nuclear chart with (N,Z) as axis and the values of the Table as a color scale Parameters ---------- ax: optional matplotlib axes defaults to ...
Use as a decorator for operations on the database to ensure connection setup and teardown. Can only be used on methods on objects with a self. session attribute.
def _uses_db(func, self, *args, **kwargs): """ Use as a decorator for operations on the database, to ensure connection setup and teardown. Can only be used on methods on objects with a `self.session` attribute. """ if not self.session: _logger.debug('Creating new db session') self._init_...
Computes the key from the salt and the master password.
def derive_key(self, master_password): """ Computes the key from the salt and the master password. """ encoder = encoding.Encoder(self.charset) bytes = ('%s:%s' % (master_password, self.name)).encode('utf8') start_time = time.clock() # we fix the scrypt parameters in case the d...
Initialize a database.
def bootstrap(self, path_or_uri): """ Initialize a database. :param database_path: The absolute path to the database to initialize. """ _logger.debug("Bootstrapping new database: %s", path_or_uri) self.database_uri = _urify_db(path_or_uri) db = sa.create_engine(self.data...
Search the database for the given query. Will find partial matches.
def search(self, query): """ Search the database for the given query. Will find partial matches. """ results = self.session.query(Domain).filter(Domain.name.ilike('%%%s%%' % query)).all() return results
Get the: class: Domain <pwm. Domain > object from a name.
def get_domain(self, domain_name): """ Get the :class:`Domain <pwm.Domain>` object from a name. :param domain_name: The domain name to fetch the object for. :returns: The :class:`Domain <pwm.core.Domain>` class with this domain_name if found, else None. """ protocol ...
Modify an existing domain.
def modify_domain(self, domain_name, new_salt=False, username=None): """ Modify an existing domain. :param domain_name: The name of the domain to modify. :param new_salt: Whether to generate a new salt for the domain. :param username: If given, change domain username to this value. ...
Create a new domain entry in the database.
def create_domain(self, domain_name, username=None, alphabet=Domain.DEFAULT_ALPHABET, length=Domain.DEFAULT_KEY_LENGTH): """ Create a new domain entry in the database. :param username: The username to associate with this domain. :param alphabet: A character set restriction to impose...
Yields tile ( x y z ) tuples for a bounding box and zoom levels.
def from_bbox(bbox, zlevs): """Yields tile (x, y, z) tuples for a bounding box and zoom levels. Arguments: bbox - bounding box as a 4-length sequence zlevs - sequence of tile zoom levels """ env = Envelope(bbox) for z in zlevs: corners = [to_tile(*coord + (z,)) for coord in (env.ul,...
Returns a tuple of ( longitude latitude ) from a map tile xyz coordinate.
def to_lonlat(xtile, ytile, zoom): """Returns a tuple of (longitude, latitude) from a map tile xyz coordinate. See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2 Arguments: xtile - x tile location as int or float ytile - y tile location as int or float zo...
Returns a tuple of ( xtile ytile ) from a ( longitude latitude ) coordinate.
def to_tile(lon, lat, zoom): """Returns a tuple of (xtile, ytile) from a (longitude, latitude) coordinate. See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames Arguments: lon - longitude as int or float lat - latitude as int or float zoom - zoom level as int or float """ lat_rad...
Extract messages from Handlebars templates.
def extract_hbs(fileobj, keywords, comment_tags, options): """Extract messages from Handlebars templates. It returns an iterator yielding tuples in the following form ``(lineno, funcname, message, comments)``. TODO: Things to improve: --- Return comments """ server = get_pipeserver() ...
Returns a GDAL virtual filesystem prefixed path.
def vsiprefix(path): """Returns a GDAL virtual filesystem prefixed path. Arguments: path -- file path as str """ vpath = path.lower() scheme = VSI_SCHEMES.get(urlparse(vpath).scheme, '') for ext in VSI_TYPES: if ext in vpath: filesys = VSI_TYPES[ext] break ...
Returns the EPSG ID as int if it exists.
def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return
Main entry point for the CLI.
def main(): """ Main entry point for the CLI. """ args = get_args() ret_code = args.target(args) _logger.debug('Exiting with code %d', ret_code) sys.exit(ret_code)
Initialize loggers.
def _init_logging(verbose=False): """ Initialize loggers. """ config = { 'version': 1, 'formatters': { 'console': { 'format': '* %(message)s', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', ...
Update the content of a single file.
def update_file(url, filename): """Update the content of a single file.""" resp = urlopen(url) if resp.code != 200: raise Exception('GET {} failed.'.format(url)) with open(_get_package_path(filename), 'w') as fp: for l in resp: if not l.startswith(b'#'): fp.wr...
Returns a dictionary of enabled GDAL Driver metadata keyed by the ShortName attribute.
def available_drivers(): """Returns a dictionary of enabled GDAL Driver metadata keyed by the 'ShortName' attribute. """ drivers = {} for i in range(gdal.GetDriverCount()): d = gdal.GetDriver(i) drivers[d.ShortName] = d.GetMetadata() return drivers
Returns the gdal. Driver for a path or None based on the file extension.
def driver_for_path(path, drivers=None): """Returns the gdal.Driver for a path or None based on the file extension. Arguments: path -- file path as str with a GDAL supported file extension """ ext = (os.path.splitext(path)[1][1:] or path).lower() drivers = drivers or ImageDriver.registry if ext...
Converts an OGR polygon to a 2D NumPy array.
def geom_to_array(geom, size, affine): """Converts an OGR polygon to a 2D NumPy array. Arguments: geom -- OGR Geometry size -- array size in pixels as a tuple of (width, height) affine -- AffineTransform """ driver = ImageDriver('MEM') rast = driver.raster(driver.ShortName, size) ra...
Returns a Raster from layer features.
def rasterize(layer, rast): """Returns a Raster from layer features. Arguments: layer -- Layer to rasterize rast -- Raster with target affine, size, and sref """ driver = ImageDriver('MEM') r2 = driver.raster(driver.ShortName, rast.size) r2.affine = rast.affine sref = rast.sref ...
Returns a Raster instance.
def open(path, mode=gdalconst.GA_ReadOnly): """Returns a Raster instance. Arguments: path -- local or remote path as str or file-like object Keyword args: mode -- gdal constant representing access mode """ path = getattr(path, 'name', path) try: return Raster(vsiprefix(path), mo...
Returns an in - memory raster initialized from a pixel buffer.
def frombytes(data, size, bandtype=gdal.GDT_Byte): """Returns an in-memory raster initialized from a pixel buffer. Arguments: data -- byte buffer of raw pixel data size -- two or three-tuple of (xsize, ysize, bandcount) bandtype -- band data type """ r = ImageDriver('MEM').raster('', size, ...
Convert image pixel/ line coordinates to georeferenced x/ y return a generator of two - tuples.
def project(self, coords): """Convert image pixel/line coordinates to georeferenced x/y, return a generator of two-tuples. Arguments: coords -- input coordinates as iterable containing two-tuples/lists such as ((0, 0), (10, 10)) """ geotransform = self.tuple ...
Transform from projection coordinates ( Xp Yp ) space to pixel/ line ( P L ) raster space based on the provided geotransformation.
def transform(self, coords): """Transform from projection coordinates (Xp,Yp) space to pixel/line (P,L) raster space, based on the provided geotransformation. Arguments: coords -- input coordinates as iterable containing two-tuples/lists such as ((-120, 38), (-121, 39)) ...
Returns a copied Raster instance.
def copy(self, source, dest): """Returns a copied Raster instance. Arguments: source -- the source Raster instance or filepath as str dest -- destination filepath as str """ if not self.copyable: raise IOError('Driver does not support raster copying') ...
Calls Driver. Create () with optionally provided creation options as dict or falls back to driver specific defaults.
def Create(self, *args, **kwargs): """Calls Driver.Create() with optionally provided creation options as dict, or falls back to driver specific defaults. """ if not self.writable: raise IOError('Driver does not support raster creation') options = kwargs.pop('options',...
Returns a dict of driver specific raster creation options.
def options(self): """Returns a dict of driver specific raster creation options. See GDAL format docs at http://www.gdal.org/formats_list.html """ if self._options is None: try: elem = ET.fromstring( self.info.get('DMD_CREATIONOPTIONLIST',...
Returns a new Raster instance.
def raster(self, path, size, bandtype=gdal.GDT_Byte): """Returns a new Raster instance. gdal.Driver.Create() does not support all formats. Arguments: path -- file object or path as str size -- two or three-tuple of (xsize, ysize, bandcount) bandtype -- GDAL pixel data t...
Sets the affine transformation.
def SetGeoTransform(self, affine): """Sets the affine transformation. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: affine -- AffineTransform or six-tuple of geotransformation values """ if isinstance(affine, collections.Sequence): ...
Returns an NDArray optionally subset by spatial envelope.
def array(self, envelope=()): """Returns an NDArray, optionally subset by spatial envelope. Keyword args: envelope -- coordinate extent tuple or Envelope """ args = () if envelope: args = self.get_offset(envelope) return self.ds.ReadAsArray(*args)
Returns the minimum bounding rectangle as a tuple of min X min Y max X max Y.
def envelope(self): """Returns the minimum bounding rectangle as a tuple of min X, min Y, max X, max Y. """ if self._envelope is None: origin = self.affine.origin ur_x = origin[0] + self.ds.RasterXSize * self.affine.scale[0] ll_y = origin[1] + self.ds....
Returns a 4 - tuple pixel window ( x_offset y_offset x_size y_size ).
def get_offset(self, envelope): """Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size). Arguments: envelope -- coordinate extent tuple or Envelope """ if isinstance(envelope, collections.Sequence): envelope = Envelope(envelope) if not (self.en...
Returns the underlying ImageDriver instance.
def driver(self): """Returns the underlying ImageDriver instance.""" if self._driver is None: self._driver = ImageDriver(self.ds.GetDriver()) return self._driver
Derive new Raster instances.
def new(self, size=(), affine=None): """Derive new Raster instances. Keyword args: size -- tuple of image size (width, height) affine -- AffineTransform or six-tuple of geotransformation values """ size = size or self.size + (len(self),) band = self.ds.GetRasterB...
Returns a MaskedArray using nodata values.
def masked_array(self, geometry=None): """Returns a MaskedArray using nodata values. Keyword args: geometry -- any geometry, envelope, or coordinate extent tuple """ if geometry is None: return self._masked_array() geom = transform(geometry, self.sref) ...
Returns read only property for band nodata value assuming single band rasters for now.
def nodata(self): """Returns read only property for band nodata value, assuming single band rasters for now. """ if self._nodata is None: self._nodata = self[0].GetNoDataValue() return self._nodata
Returns raster data bytes for partial or full extent.
def ReadRaster(self, *args, **kwargs): """Returns raster data bytes for partial or full extent. Overrides gdal.Dataset.ReadRaster() with the full raster size by default. """ args = args or (0, 0, self.ds.RasterXSize, self.ds.RasterYSize) return self.ds.ReadRaster(*args, ...
Returns a new instance resampled to provided size.
def resample(self, size, interpolation=gdalconst.GRA_NearestNeighbour): """Returns a new instance resampled to provided size. Arguments: size -- tuple of x,y image dimensions """ # Find the scaling factor for pixel size. factors = (size[0] / float(self.RasterXSize), ...
Save this instance to the path and format provided.
def save(self, to, driver=None): """Save this instance to the path and format provided. Arguments: to -- output path as str, file, or MemFileIO instance Keyword args: driver -- GDAL driver name as string or ImageDriver """ path = getattr(to, 'name', to) i...
Sets the spatial reference.
def SetProjection(self, sref): """Sets the spatial reference. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: sref -- SpatialReference or any format supported by the constructor """ if not hasattr(sref, 'ExportToWkt'): sref = ...
Returns a tuple of row column ( band count if multidimensional ).
def shape(self): """Returns a tuple of row, column, (band count if multidimensional).""" shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount) return shp[:2] if shp[2] <= 1 else shp
Returns a new reprojected instance.
def warp(self, to_sref, dest=None, interpolation=gdalconst.GRA_NearestNeighbour): """Returns a new reprojected instance. Arguments: to_sref -- spatial reference as a proj4 or wkt string, or a SpatialReference Keyword args: dest -- filepath as str interpolation --...
computes the ideal conversion ratio for the given alphabet. A ratio is considered ideal when the number of bits in one output encoding chunk that don t add up to one input encoding chunk is minimal.
def calc_chunklen(alph_len): ''' computes the ideal conversion ratio for the given alphabet. A ratio is considered ideal when the number of bits in one output encoding chunk that don't add up to one input encoding chunk is minimal. ''' binlen, enclen = min([ (i, i*8 / m...
retrieves a named charset or treats the input as a custom alphabet and use that
def lookup_alphabet(charset): ''' retrieves a named charset or treats the input as a custom alphabet and use that ''' if charset in PRESETS: return PRESETS[charset] if len(charset) < 16: _logger.warning('very small alphabet in use, possibly a failed lookup?') return charset
gets a chunk from the input data converts it to a number and encodes that number
def _encode_chunk(self, data, index): ''' gets a chunk from the input data, converts it to a number and encodes that number ''' chunk = self._get_chunk(data, index) return self._encode_long(self._chunk_to_long(chunk))
encodes an integer of 8 * self. chunklen [ 0 ] bits using the specified alphabet
def _encode_long(self, val): ''' encodes an integer of 8*self.chunklen[0] bits using the specified alphabet ''' return ''.join([ self.alphabet[(val//len(self.alphabet)**i) % len(self.alphabet)] for i in reversed(range(self.chunklen[1])) ...
parses a chunk of bytes to integer using big - endian representation
def _chunk_to_long(self, chunk): ''' parses a chunk of bytes to integer using big-endian representation ''' return sum([ 256**(self.chunklen[0]-1-i) * ord_byte(chunk[i]) for i in range(self.chunklen[0]) ])
partition the data into chunks and retrieve the chunk at the given index
def _get_chunk(self, data, index): ''' partition the data into chunks and retrieve the chunk at the given index ''' return data[index*self.chunklen[0]:(index+1)*self.chunklen[0]]
Cache result of function call.
def memoize(func): """Cache result of function call.""" cache = {} @wraps(func) def inner(filename): if filename not in cache: cache[filename] = func(filename) return cache[filename] return inner
Get a list of patterns from a file and make a regular expression.
def _regexp(filename): """Get a list of patterns from a file and make a regular expression.""" lines = _get_resource_content(filename).decode('utf-8').splitlines() return re.compile('|'.join(lines))
Dates can be defined in many ways but zipline use aware datetime objects only. Plus the software work with utc timezone so we convert it.
def normalize_date_format(date): ''' Dates can be defined in many ways, but zipline use aware datetime objects only. Plus, the software work with utc timezone so we convert it. ''' if isinstance(date, int): # This is probably epoch time date = time.strftime('%Y-%m-%d %H:%M:%S', ...
Get timezone as set by the system
def _detect_timezone(): ''' Get timezone as set by the system ''' default_timezone = 'America/New_York' locale_code = locale.getdefaultlocale() return default_timezone if not locale_code[0] else \ str(pytz.country_timezones[locale_code[0][-2:]][0])
>>> # Harmonize api endpoints >>> # __version__ should be like major. minor. fix >>> from my_app import __version__ >>> api_url ( __version__/ some/ endpoint )/ v0/ some/ endpoint
def api_url(full_version, resource): ''' >>> # Harmonize api endpoints >>> # __version__ should be like major.minor.fix >>> from my_app import __version__ >>> api_url(__version__, '/some/endpoint') /v0/some/endpoint ''' return '/v{}/{}'.format(dna.utils.Version(full_version).major, resou...
>>> # Wrap api endpoints with more details >>> api_doc (/ resource secure = True key = value ) GET/ resource?secure = true&key = value
def api_doc(full_version, resource, method='GET', **kwargs): ''' >>> # Wrap api endpoints with more details >>> api_doc('/resource', secure=True, key='value') GET /resource?secure=true&key=value ''' doc = '{} {}'.format(method, api_url(full_version, resource)) params = '&'.join(['{}={}'.form...
Returns the model properties as a dict
def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to...
Catch exceptions with a prompt for post - mortem analyzis
def activate_pdb_hook(): ''' Catch exceptions with a prompt for post-mortem analyzis''' def debug_exception(type_exception, value, tb): import pdb pdb.post_mortem(tb) import sys sys.excepthook = debug_exception
Clearer data printing
def emphasis(obj, align=True): ''' Clearer data printing ''' if isinstance(obj, dict): if align: pretty_msg = os.linesep.join( ["%25s: %s" % (k, obj[k]) for k in sorted(obj.keys())]) else: pretty_msg = json.dumps(obj, indent=4, sort_keys=True) else: ...
Use this function to list all coins with their data which are available on cryptocoincharts. Usage: http:// api. cryptocoincharts. info/ listCoins
def listcoins(self): ''' Use this function to list all coins with their data which are available on cryptocoincharts. Usage: http://api.cryptocoincharts.info/listCoins ''' url = self.API_PATH + 'listCoins' json_data = json.loads(self._getdata(url)) ...
Use this function to query price and volume data for ONE trading pair. A list with all coin currencies can be found by using the listcoins method. A example pair: currency1_currency2 = doge_btc Usage: http:// api. cryptocoincharts. info/ tradingPair/ [ currency1_currency2 ]
def tradingpair(self, pair): ''' Use this function to query price and volume data for ONE trading pair. A list with all coin currencies can be found by using the listcoins method. A example pair: currency1_currency2 = "doge_btc" Usage: http://api.cryptocoincharts.info/tradingPai...
Use this function to query price and volume data for MANY trading pairs. Usage: http:// api. cryptocoincharts. info/ tradingPairs/ [ currency1_currency2 currency2_currency3... ] A example pair: currency1_currency2 = doge_btc currency2_currency3 = btc_eur http:// api. cryptocoincharts. info/ tradingPairs/ doge_btc btc_e...
def tradingpairs(self, pairs): ''' Use this function to query price and volume data for MANY trading pairs. Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...] A example pair: currency1_currency2 = "doge_btc" ...
Wrapper method
def _getdata(self, url, data = ""): ''' Wrapper method ''' request = Request(url) if data != "": request = Request(url, urlencode(data)) try: response = urlopen(request) except HTTPError as e: print('The Se...
Connects to the remote master and continuously receives calls executes them then returns a response until interrupted.
async def handle_jobs(job_handler, host, port, *, loop): """ Connects to the remote master and continuously receives calls, executes them, then returns a response until interrupted. """ try: try: reader, writer = await asyncio.open_connection(host, port, loop=loop) exce...
Starts an asyncio event loop to connect to the master and run jobs.
def worker_main(job_handler, host, port): """ Starts an asyncio event loop to connect to the master and run jobs. """ loop = asyncio.new_event_loop() asyncio.set_event_loop(None) loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop)) loop.close()
Runs a pool of workers which connect to a remote HighFive master and begin executing calls.
def run_worker_pool(job_handler, host="localhost", port=48484, *, max_workers=None): """ Runs a pool of workers which connect to a remote HighFive master and begin executing calls. """ if max_workers is None: max_workers = multiprocessing.cpu_count() processes = [...
Sets the classification of this CompanyDetailCompany. Classification of Company
def classification(self, classification): """ Sets the classification of this CompanyDetailCompany. Classification of Company :param classification: The classification of this CompanyDetailCompany. :type: str """ allowed_values = ["Public Limited Indian Non-Gover...
Add message to queue and start processing the queue.
def _send_message(self, msg): """Add message to queue and start processing the queue.""" LWLink.the_queue.put_nowait(msg) if LWLink.thread is None or not LWLink.thread.isAlive(): LWLink.thread = Thread(target=self._send_queue) LWLink.thread.start()
Create the message to turn light on.
def turn_on_light(self, device_id, name): """Create the message to turn light on.""" msg = "!%sFdP32|Turn On|%s" % (device_id, name) self._send_message(msg)
Create the message to turn switch on.
def turn_on_switch(self, device_id, name): """Create the message to turn switch on.""" msg = "!%sF1|Turn On|%s" % (device_id, name) self._send_message(msg)
Scale brightness from 0.. 255 to 1.. 32.
def turn_on_with_brightness(self, device_id, name, brightness): """Scale brightness from 0..255 to 1..32.""" brightness_value = round((brightness * 31) / 255) + 1 # F1 = Light on and F0 = light off. FdP[0..32] is brightness. 32 is # full. We want that when turning the light on. m...
Create the message to turn light or switch off.
def turn_off(self, device_id, name): """Create the message to turn light or switch off.""" msg = "!%sF0|Turn Off|%s" % (device_id, name) self._send_message(msg)
If the queue is not empty process the queue.
def _send_queue(self): """If the queue is not empty, process the queue.""" while not LWLink.the_queue.empty(): self._send_reliable_message(LWLink.the_queue.get_nowait())
Send msg to LightwaveRF hub.
def _send_reliable_message(self, msg): """Send msg to LightwaveRF hub.""" result = False max_retries = 15 trans_id = next(LWLink.transaction_id) msg = "%d,%s" % (trans_id, msg) try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \ as...
Generates a wrapped adapter for the given object
def create_adapter(cmph, ffi, obj): """ Generates a wrapped adapter for the given object Parameters ---------- obj : list, buffer, array, or file Raises ------ ValueError If presented with an object that cannot be adapted Returns ------- CMPH capable adapter """ ...
Sets the nature of this YearlyFinancials. Nature of the balancesheet
def nature(self, nature): """ Sets the nature of this YearlyFinancials. Nature of the balancesheet :param nature: The nature of this YearlyFinancials. :type: str """ allowed_values = ["STANDALONE"] if nature not in allowed_values: raise ValueE...
Figure out a reasonable default with. Use os. environ [ COLUMNS ] if possible and failing that use 80.
def computed_displaywidth(): '''Figure out a reasonable default with. Use os.environ['COLUMNS'] if possible, and failing that use 80. ''' try: width = int(os.environ['COLUMNS']) except (KeyError, ValueError): width = get_terminal_size().columns return width or 80
Return a list of strings as a compact set of columns arranged horizontally or vertically.
def columnize(array, displaywidth=80, colsep = ' ', arrange_vertical=True, ljust=True, lineprefix='', opts={}): """Return a list of strings as a compact set of columns arranged horizontally or vertically. For example, for a line width of 4 characters (arranged vertically): ...
Generates a new Minimal Perfect Hash ( MPH )
def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1, chd_load_factor=None, fch_bits_per_key=None, num_graph_vertices=None, brz_memory_size=8, brz_temp_dir=None, brz_max_keys_per_bucket=128, bdz_precomputed_rank=7, chd_avg_ke...
Load a Minimal Perfect Hash ( MPH ) Given an input stream this will load a minimal perfect hash
def load_hash(existing_mph): """ Load a Minimal Perfect Hash (MPH) Given an input stream, this will load a minimal perfect hash Parameters ---------- existing_mph : file_like, string An input stream that is file like, and able to load a preexisting MPH, or the filename represent...
Persist the Minimal Perfect Hash ( MPH ) to a stream
def save(self, output): """ Persist the Minimal Perfect Hash (MPH) to a stream Parameters ---------- output : file_like The stream to use to persist the MPH Raises ------ IOError If there is an issue accessing or manipulating the ...
Generate hash code for a key from the Minimal Perfect Hash ( MPH )
def lookup(self, key): """ Generate hash code for a key from the Minimal Perfect Hash (MPH) Parameters ---------- Key : object The item to generate a key for, this works best for keys that are strings, or can be transformed fairly directly into bytes ...
Update values of configuration section with dict.
def update_(self, sct_dict, conf_arg=True): """Update values of configuration section with dict. Args: sct_dict (dict): dict indexed with option names. Undefined options are discarded. conf_arg (bool): if True, only options that can be set in a config ...
Restore default values of options in this section.
def reset_(self): """Restore default values of options in this section.""" for opt, meta in self.defaults_(): self[opt] = meta.default
Use a dictionary to create a: class: ConfigurationManager.
def from_dict_(cls, conf_dict): """Use a dictionary to create a :class:`ConfigurationManager`. Args: conf_dict (dict of dict of :class:`ConfOpt`): the first level of keys should be the section names. The second level should be the option names. The values are...
Set the list of config files.
def set_config_files_(self, *config_files): """Set the list of config files. Args: config_files (pathlike): path of config files, given in the order of reading. """ self._config_files = tuple(pathlib.Path(path) for path in config_files)
Iterator over sections option names and option values.
def opt_vals_(self): """Iterator over sections, option names, and option values. This iterator is also implemented at the section level. The two loops produce the same output:: for sct, opt, val in conf.opt_vals_(): print(sct, opt, val) for sct in conf....
Iterator over sections option names and option metadata.
def defaults_(self): """Iterator over sections, option names, and option metadata. This iterator is also implemented at the section level. The two loops produce the same output:: for sct, opt, meta in conf.defaults_(): print(sct, opt, meta.default) for ...
Create config file.
def create_config_(self, index=0, update=False): """Create config file. Create config file in :attr:`config_files_[index]`. Parameters: index(int): index of config file. update (bool): if set to True and :attr:`config_files_` already exists, its content ...
Update values of configuration options with dict.
def update_(self, conf_dict, conf_arg=True): """Update values of configuration options with dict. Args: conf_dict (dict): dict of dict indexed with section and option names. conf_arg (bool): if True, only options that can be set in a config file a...
Read a config file and set config values accordingly.
def read_config_(self, cfile): """Read a config file and set config values accordingly. Returns: dict: content of config file. """ if not cfile.exists(): return {} try: conf_dict = toml.load(str(cfile)) except toml.TomlDecodeError: ...
Read config files and set config values accordingly.
def read_configs_(self): """Read config files and set config values accordingly. Returns: (dict, list, list): respectively content of files, list of missing/empty files and list of files for which a parsing error arised. """ if not self.config_files_:...
For the given module file ( usually found by:
def _lookup_version(module_file): """ For the given module file (usually found by: from package import __file__ as module_file in the caller, return the location of the current RELEASE-VERSION file and the file itself. """ version_dir = path.abspath(path.dirname(module_file)) v...
List of cli strings for a given option.
def _names(section, option): """List of cli strings for a given option.""" meta = section.def_[option] action = meta.cmd_kwargs.get('action') if action is internal.Switch: names = ['-{}'.format(option), '+{}'.format(option)] if meta.shortname is not None: names.append('-{}'.f...
List of config sections used by a command.
def sections_list(self, cmd=None): """List of config sections used by a command. Args: cmd (str): command name, set to ``None`` or ``''`` for the bare command. Returns: list of str: list of configuration sections used by that command. """ ...
Scan options related to one command and enrich _opt_cmds.
def _cmd_opts_solver(self, cmd_name): """Scan options related to one command and enrich _opt_cmds.""" sections = self.sections_list(cmd_name) cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare for sct in reversed(sections): for opt, opt_meta in self._conf[sct...
Add options to a parser.
def _add_options_to_parser(self, opts_dict, parser): """Add options to a parser.""" store_bool = ('store_true', 'store_false') for opt, sct in opts_dict.items(): meta = self._conf[sct].def_[opt] kwargs = copy.deepcopy(meta.cmd_kwargs) action = kwargs.get('acti...
Build command line argument parser.
def _build_parser(self): """Build command line argument parser. Returns: :class:`argparse.ArgumentParser`: the command line argument parser. You probably won't need to use it directly. To parse command line arguments and update the :class:`ConfigurationManager` insta...
Parse arguments and update options accordingly.
def parse_args(self, arglist=None): """Parse arguments and update options accordingly. Args: arglist (list of str): list of arguments to parse. If set to None, ``sys.argv[1:]`` is used. Returns: :class:`Namespace`: the argument namespace returned by the ...
Write zsh _arguments compdef for a given command.
def _zsh_comp_command(self, zcf, cmd, grouping, add_help=True): """Write zsh _arguments compdef for a given command. Args: zcf (file): zsh compdef file. cmd (str): command name, set to None or '' for bare command. grouping (bool): group options (zsh>=5.4). ...
Write zsh compdef script.
def zsh_complete(self, path, cmd, *cmds, sourceable=False): """Write zsh compdef script. Args: path (path-like): desired path of the compdef script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. ...