Search is not available for this dataset
text
stringlengths
75
104k
def to_json_str(self): """Convert data to json string representation. Returns: json representation as string. """ adict = dict(vars(self), sort_keys=True) adict['type'] = self.__class__.__name__ return json.dumps(adict)
def find_file_match(folder_path, regex=''): """ Returns absolute paths of files that match the regex within folder_path and all its children folders. Note: The regex matching is done using the match function of the re module. Parameters ---------- folder_path: string regex: string...
def qquery(xml_thing, xpath_thing, vars=None, funcs=None): ''' Quick query. Convenience for using the MicroXPath engine. Give it some XML and an expression and it will yield the results. No fuss. xml_thing - bytes or string, or amara3.xml.tree node xpath_thing - string or parsed XPath expressio...
def p_function_call(p): """ FunctionCall : NAME FormalArguments """ #Hacking around the ambiguity between node type test & function call if p[1] in ('node', 'text'): p[0] = ast.NodeType(p[1]) else: p[0] = ast.FunctionCall(p[1], p[2])
def boolean_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_boolean(obj)
def number_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_number(obj)
def string_arg(ctx, obj): ''' Handles LiteralObjects as well as computable arguments ''' if hasattr(obj, 'compute'): obj = next(obj.compute(ctx), False) return to_string(obj)
def name(ctx, obj=None): ''' Yields one string a node name or the empty string, operating on the first item in the provided obj, or the current item if obj is omitted If this item is a node, yield its node name (generic identifier), otherwise yield '' If obj is provided, but empty, yield '' ''' ...
def string_(ctx, seq=None): ''' Yields one string, derived from the argument literal (or the first item in the argument sequence, unless empty in which case yield '') as follows: * If a node, yield its string-value * If NaN, yield 'NaN' * If +0 or -0, yield '0' * If positive infinity, yield 'In...
def concat(ctx, *strings): ''' Yields one string, concatenation of argument strings ''' strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ]) strings = (next(string_arg(ctx, s), '') for s in strings) #assert(all(map(lambda x: isinstance(x, str), strings))) #FIXME: Ch...
def starts_with(ctx, full, part): ''' Yields one boolean, whether the first string starts with the second ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.startswith(part)
def contains(ctx, full, part): ''' Yields one boolean, whether the first string contains the second ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield part in full
def substring_before(ctx, full, part): ''' Yields one string ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.partition(part)[0]
def substring_after(ctx, full, part): ''' Yields one string ''' full = next(string_arg(ctx, full), '') part = next(string_arg(ctx, part), '') yield full.partition(part)[-1]
def substring(ctx, full, start, length): ''' Yields one string ''' full = next(string_arg(ctx, full), '') start = int(next(to_number(start))) length = int(next(to_number(length))) yield full[start-1:start-1+length]
def string_length(ctx, s=None): ''' Yields one number ''' if s is None: s = ctx.node elif callable(s): s = next(s.compute(ctx), '') yield len(s)
def boolean(ctx, obj): ''' Yields one boolean, false if the argument sequence is empty, otherwise * false if the first item is a boolean and false * false if the first item is a number and positive or negative zero or NaN * false if the first item is a string and '' * true in all other cases ...
def number(ctx, seq=None): ''' Yields one float, derived from the first item in the argument sequence (unless empty in which case yield NaN) as follows: * If string with optional whitespace followed by an optional minus sign followed by a Number followed by whitespace, converte to the IEEE 754 number that ...
def foreach_(ctx, seq, expr): ''' Yields the result of applying an expression to each item in the input sequence. * seq: input sequence * expr: expression to be converted to string, then dynamically evaluated for each item on the sequence to produce the result ''' from . import context, parse a...
def lookup_(ctx, tableid, key): ''' Yields a sequence of a single value, the result of looking up a value from the tables provided in the context, or an empty sequence if lookup is unsuccessful * tableid: id of the lookup table to use * expr: expression to be converted to string, then dynamically evalu...
def replace_chars_for_svg_code(svg_content): """ Replace known special characters to SVG code. Parameters ---------- svg_content: str Returns ------- corrected_svg: str Corrected SVG content """ result = svg_content svg_char = [ ('&', '&'), ('>', '&g...
def _check_svg_file(svg_file): """ Try to read a SVG file if `svg_file` is a string. Raise an exception in case of error or return the svg object. If `svg_file` is a svgutils svg object, will just return it. Parameters ---------- svg_file: str or svgutils.transform.SVGFigure object If ...
def merge_svg_files(svg_file1, svg_file2, x_coord, y_coord, scale=1): """ Merge `svg_file2` in `svg_file1` in the given positions `x_coord`, `y_coord` and `scale`. Parameters ---------- svg_file1: str or svgutils svg document object Path to a '.svg' file. svg_file2: str or svgutils svg doc...
def rsvg_export(input_file, output_file, dpi=90, rsvg_binpath=None): """ Calls the `rsvg-convert` command, to convert a svg to a PDF (with unicode). Parameters ---------- rsvg_binpath: str Path to `rsvg-convert` command input_file: str Path to the input file output_file: str ...
def merge_pdfs(pdf_filepaths, out_filepath): """ Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`. Parameters ---------- pdf_filepaths: list of str Paths to PDF files. out_filepath: str Path to the result PDF file. Returns ------- path: str ...
def _embed_font_to_svg(filepath, font_files): """ Return the ElementTree of the SVG content in `filepath` with the font content embedded. """ with open(filepath, 'r') as svgf: tree = etree.parse(svgf) if not font_files: return tree fontfaces = FontFaceGroup() for font_file ...
def embed_font_to_svg(filepath, outfile, font_files): """ Write ttf and otf font content from `font_files` in the svg file in `filepath` and write the result in `outfile`. Parameters ---------- filepath: str The SVG file whose content must be modified. outfile: str The file...
def _check_inputs(self): ''' make some basic checks on the inputs to make sure they are valid''' try: _ = self._inputs[0] except TypeError: raise RuntimeError( "inputs should be iterable but found type='{0}', value=" "'{1}'".format(type(sel...
def _check_function(self): ''' make some basic checks on the function to make sure it is valid''' # note, callable is valid for Python 2 and Python 3.2 onwards but # not inbetween if not callable(self._function): raise RuntimeError( "provided function '{0}' is...
def _recurse(self, inputs, output): '''internal recursion routine called by the run method that generates all input combinations''' if inputs: my_input = inputs[0] name = my_input.name if my_input.state: my_options = my_input.options(self.state...
def create_input(option, template_name, template_location="template"): '''create an input file using jinja2 by filling a template with the values from the option variable passed in.''' # restructure option list into jinja2 input format jinja2_input = {} for item in option: try: ...
def _recurse(self, inputs, output, depth, max_depth): '''We work out all combinations using this internal recursion method''' if depth < max_depth: for index, option in enumerate(inputs): my_output = list(output) my_output.append(option) self._...
def to_string(obj): ''' Cast an arbitrary object or sequence to a string type ''' if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, Iterable) and not isinstance(obj, str): val = next(obj, None) else: val = obj if val is None: yield '' ...
def to_number(obj): ''' Cast an arbitrary object or sequence to a number type ''' if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, Iterable) and not isinstance(obj, str): val = next(obj, None) else: val = obj if val is None: #FIXME: Shoul...
def to_boolean(obj): ''' Cast an arbitrary sequence to a boolean type ''' #if hasattr(obj, '__iter__'): if isinstance(obj, LiteralWrapper): val = obj.obj elif isinstance(obj, Iterable) and not isinstance(obj, str): val = next(obj, None) else: val = obj if val is N...
def _serialize(xp_ast): '''Generate token strings which, when joined together, form a valid XPath serialization of the AST.''' if hasattr(xp_ast, '_serialize'): for tok in xp_ast._serialize(): yield(tok) elif isinstance(xp_ast, str): yield(repr(xp_ast))
def change_xml_encoding(filepath, src_enc, dst_enc='utf-8'): """ Modify the encoding entry in the XML file. Parameters ---------- filepath: str Path to the file to be modified. src_enc: str Encoding that is written in the file dst_enc: str Encoding to be set in the fil...
def save_into_qrcode(text, out_filepath, color='', box_size=10, pixel_size=1850): """ Save `text` in a qrcode svg image file. Parameters ---------- text: str The string to be codified in the QR image. out_filepath: str Path to the output file color: str A RGB color exp...
def _qrcode_to_file(qrcode, out_filepath): """ Save a `qrcode` object into `out_filepath`. Parameters ---------- qrcode: qrcode object out_filepath: str Path to the output file. """ try: qrcode.save(out_filepath) except Exception as exc: raise IOError('Error tryi...
def handle_cdata(pos, window, charpat, stopchars): ''' Return (result, new_position) tuple. Result is cdata string if possible and None if more input is needed Or of course bad syntax can raise a RuntimeError ''' cdata = '' cursor = start = pos try: while True: while...
def launch(option): '''Set the gromacs input data using the supplied input options, run gromacs and extract and return the required outputs.''' from melody.inputs import create_input _ = create_input(option, template_name="input.mdp") # save the input file in the appropriate place and launch groma...
def call_command(cmd_name, args_strings): """Call CLI command with arguments and returns its return value. Parameters ---------- cmd_name: str Command name or full path to the binary file. arg_strings: str Argument strings list. Returns ------- return_value Com...
def getCSV(self): """ Returns ------- filename: str """ import getpass import gspread user = raw_input("Insert Google username:") password = getpass.getpass(prompt="Insert password:") name = raw_input("SpreadSheet filename on Drive:") ...
def write(elem, a_writer): ''' Write a MicroXML element node (yes, even one representign a whole document) elem - Amara MicroXML element node to be written out writer - instance of amara3.uxml.writer to implement the writing process ''' a_writer.start_element(elem.xml_name, attribs=elem.xml_attr...
def tex2pdf(tex_file, output_file=None, output_format='pdf'): """ Call PDFLatex to convert TeX files to PDF. Parameters ---------- tex_file: str Path to the input LateX file. output_file: str Path to the output PDF file. If None, will use the same output directory as the te...
def options(self, my_psy): '''Returns all potential loop fusion options for the psy object provided''' # compute options dynamically here as they may depend on previous # changes to the psy tree my_options = [] invokes = my_psy.invokes.invoke_list #print "there ar...
def transform(geom, to_sref): """Returns a transformed Geometry. Arguments: geom -- any coercible Geometry value or Envelope to_sref -- SpatialReference or EPSG ID as int """ # If we have an envelope, assume it's in the target sref. try: geom = getattr(geom, 'polygon', Envelope(geom...
def Geometry(*args, **kwargs): """Returns an ogr.Geometry instance optionally created from a geojson str or dict. The spatial reference may also be provided. """ # Look for geojson as a positional or keyword arg. arg = kwargs.pop('geojson', None) or len(args) and args[0] try: srs = kwarg...
def centroid(self): """Returns the envelope centroid as a (x, y) tuple.""" return self.min_x + self.width * 0.5, self.min_y + self.height * 0.5
def expand(self, other): """Expands this envelope by the given Envelope or tuple. Arguments: other -- Envelope, two-tuple, or four-tuple """ if len(other) == 2: other += other mid = len(other) // 2 self.ll = map(min, self.ll, other[:mid]) self...
def intersect(self, other): """Returns the intersection of this and another Envelope.""" inter = Envelope(tuple(self)) if inter.intersects(other): mid = len(other) // 2 inter.ll = map(max, inter.ll, other[:mid]) inter.ur = map(min, inter.ur, other[mid:]) ...
def intersects(self, other): """Returns true if this envelope intersects another. Arguments: other -- Envelope or tuple of (minX, minY, maxX, maxY) """ try: return (self.min_x <= other.max_x and self.max_x >= other.min_x and se...
def scale(self, xfactor, yfactor=None): """Returns a new envelope rescaled from center by the given factor(s). Arguments: xfactor -- int or float X scaling factor yfactor -- int or float Y scaling factor """ yfactor = xfactor if yfactor is None else yfactor x, y ...
def polygon(self): """Returns an OGR Geometry for this envelope.""" ring = ogr.Geometry(ogr.wkbLinearRing) for coord in self.ll, self.lr, self.ur, self.ul, self.ll: ring.AddPoint_2D(*coord) polyg = ogr.Geometry(ogr.wkbPolygon) polyg.AddGeometryDirectly(ring) r...
def from_name(cls, name): "Imports a mass table from a file" filename = os.path.join(package_dir, 'data', name + '.txt') return cls.from_file(filename, name)
def from_file(cls, filename, name=''): "Imports a mass table from a file" df = pd.read_csv(filename, header=0, delim_whitespace=True, index_col=[0, 1])['M'] df.name = name return cls(df=df, name=name)
def from_ZNM(cls, Z, N, M, name=''): """ Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 ...
def to_file(self, path): """Export the contents to a file as comma separated values. Parameters ---------- path : string File path where the data should be saved to Example ------- Export the last ten elements of AME2012 to a new file: >>> T...
def select(self, condition, name=''): """ Selects nuclei according to a condition on Z,N or M Parameters ---------- condition : function, Can have one of the signatures f(M), f(Z,N) or f(Z, N, M) must return a boolean value name: string, optional ...
def at(self, nuclei): """Return a selection of the Table at positions given by ``nuclei`` Parameters ---------- nuclei: list of tuples A list where each element is tuple of the form (Z,N) Example ------- Return binding energies at magic nuclei: ...
def intersection(self, table): """ Select nuclei which also belong to ``table`` Parameters ---------- table: Table, Table object Example: ---------- Table('AME2003').intersection(Table('AME1995')) """ idx = self.df.index & table.df.index ...
def not_in(self, table): """ Select nuclei not in table Parameters ---------- table: Table, Table object from where nuclei should be removed Example: ---------- Find the new nuclei in AME2003 with Z,N >= 8: >>> Table('AME2003').not_in(Table('AME...
def odd_odd(self): """Selects odd-odd nuclei from the table: >>> Table('FRDM95').odd_odd Out[13]: Z N 9 9 1.21 11 0.10 13 3.08 15 9.32 ... """ return self.select(lambda Z, N: (Z % 2) and (N % 2)...
def odd_even(self): """ Selects odd-even nuclei from the table """ return self.select(lambda Z, N: (Z % 2) and not(N % 2), name=self.name)
def even_odd(self): """ Selects even-odd nuclei from the table """ return self.select(lambda Z, N: not(Z % 2) and (N % 2), name=self.name)
def even_even(self): """ Selects even-even nuclei from the table """ return self.select(lambda Z, N: not(Z % 2) and not(N % 2), name=self.name)
def error(self, relative_to='AME2003'): """ Calculate error difference Parameters ---------- relative_to : string, a valid mass table name. Example: ---------- >>> Table('DUZU').error(relative_to='AME2003') """ df = self.df - ...
def rmse(self, relative_to='AME2003'): """Calculate root mean squared error Parameters ---------- relative_to : string, a valid mass table name. Example: ---------- >>> template = '{0:10}|{1:^6.2f}|{2:^6.2f}|{3:^6.2f}' >>> print 'Model '...
def binding_energy(self): """ Return binding energies instead of mass excesses """ M_P = 938.2723 # MeV M_E = 0.5110 # MeV M_N = 939.5656 # MeV AMU = 931.494028 # MeV df = self.Z * (M_P + M_E) + (self.A - self.Z) * M_N - (se...
def q_alpha(self): """Return Q_alpha""" M_ALPHA = 2.4249156 # He4 mass excess in MeV f = lambda parent, daugther: parent - daugther - M_ALPHA return self.derived('Q_alpha', (-2, -2), f)
def q_beta(self): """Return Q_beta""" f = lambda parent, daugther: parent - daugther return self.derived('Q_beta', (1, -1), f)
def s2n(self): """Return 2 neutron separation energy""" M_N = 8.0713171 # neutron mass excess in MeV f = lambda parent, daugther: -parent + daugther + 2 * M_N return self.derived('s2n', (0, -2), f)
def s1n(self): """Return 1 neutron separation energy""" M_N = 8.0713171 # neutron mass excess in MeV f = lambda parent, daugther: -parent + daugther + M_N return self.derived('s1n', (0, -1), f)
def s2p(self): """Return 2 proton separation energy""" M_P = 7.28897050 # proton mass excess in MeV f = lambda parent, daugther: -parent + daugther + 2 * M_P return self.derived('s2p', (-2, 0), f)
def s1p(self): """Return 1 proton separation energy""" M_P = 7.28897050 # proton mass excess in MeV f = lambda parent, daugther: -parent + daugther + M_P return self.derived('s1p', (-1, 0), f)
def derived(self, name, relative_coords, formula): """Helper function for derived quantities""" relZ, relN = relative_coords daughter_idx = [(x[0] + relZ, x[1] + relN) for x in self.df.index] values = formula(self.df.values, self.df.loc[daughter_idx].values) return Table(df=pd.Se...
def ds2n(self): """Calculates the derivative of the neutron separation energies: ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2) """ idx = [(x[0] + 0, x[1] + 2) for x in self.df.index] values = self.s2n.values - self.s2n.loc[idx].values return Table(df=pd.Series(values, index=self.df....
def ds2p(self): """Calculates the derivative of the neutron separation energies: ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2) """ idx = [(x[0] + 2, x[1]) for x in self.df.index] values = self.s2p.values - self.s2p.loc[idx].values return Table(df=pd.Series(values, index=self.df.inde...
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 ...
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_...
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...
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...
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
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 ...
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. ...
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...
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,...
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...
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...
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() ...
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 ...
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
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)
def _init_logging(verbose=False): """ Initialize loggers. """ config = { 'version': 1, 'formatters': { 'console': { 'format': '* %(message)s', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', ...
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...
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
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...
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...
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 ...
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...