text
stringlengths
18
773k
def read_yaml_file(self, file_name): """ Parses a YAML file into a matrix. :param file_name: name of the YAML file :return: a matrix with the file's contents """ with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as yamlfile: ...
def get_data(self, file_id): """ Acquires the data from the table identified by the id. The file is read only once, consecutive calls to this method will return the sale collection. :param file_id: identifier for the table :return: all the values from the table ...
def record_type(values): """ Creates a record type field. These serve as the header field on records, identifying them. Usually this field can be only an specific value, but sometimes a small range of codes is allowed. This is specified by the 'values' parameter. While it is possible to set t...
def record_prefix(required_type, factory): """ Creates a record prefix for the specified record type. :param required_type: the type of the record using this prefix :param factory: field factory :return: the record prefix """ field = record_type(required_type) field += factory.get_rule(...
def expand_entity(self, entity): """ Search and return entity or sub entity that contain value of this field. :param entity: :return: entity :raise KeyError """ if self.name in entity: return entity for key, value in entity.items(): ...
def encode(self, entity): """ Encode this :param entity: :return: cwr string """ entity = self.expand_entity(entity) value = entity[self.name] result = self.format(value) return result
def read_config_file(self, file_name): """ Reads a CWR grammar config file. :param file_name: name of the text file :return: the file's contents """ with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as file_config: re...
def _load_cwr_defaults(self): """ Loads the CWR default values file, creating a matrix from it, and then returns this data. The file will only be loaded once. :return: the CWR default values matrix """ if self._cwr_defaults is None: self._cwr_default...
def load_field_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._field_configs: self._field_configs[file_id] = self._reader.read_yaml_f...
def load_group_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._group_configs: self._group_configs[file_id] = self._reader.read_config...
def load_record_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._record_configs: self._record_configs[file_id] = self._reader.read_con...
def load_transaction_config(self, file_id): """ Loads the configuration fields file for the id. :param file_id: the id for the field :return: the fields configuration """ if file_id not in self._transaction_configs: self._transaction_configs[file_id] = self._...
def load_acknowledge_config(self, file_id): """ Loads the CWR acknowledge config :return: the values matrix """ if self._cwr_defaults is None: self._cwr_defaults = self._reader.read_yaml_file( 'acknowledge_config_%s.yml' % file_id) return self...
def soft_error(self, message): """ Same as error, without the dying in a fire part. """ self.print_usage(sys.stderr) args = {'prog': self.prog, 'message': message} self._print_message( _('%(prog)s: error: %(message)s\n') % args, sys.stderr)
def default_filename_decoder(): """ Creates a decoder which parses CWR filenames following the old or the new convention. :return: a CWR filename decoder for the old and the new conventions """ factory = default_filename_grammar_factory() grammar_old = factory.get_rule('filename_old') ...
def decode(self, data): """ Parses the file, creating a CWRFile from it. It requires a dictionary with two values: - filename, containing the filename - contents, containing the file contents :param data: dictionary with the data to parse :return: a CWRFile inst...
def decode(self, file_name): """ Parses the filename, creating a FileTag from it. It will try both the old and the new conventions, if the filename does not conform any of them, then an empty FileTag will be returned. :param file_name: filename to parse :return: a FileT...
def enable_pretty_logging(logger='calmjs', level=logging.DEBUG, stream=None): """ Shorthand to enable pretty logging """ def cleanup(): logger.removeHandler(handler) logger.level = old_level if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) ...
def finalize_env(env): """ Produce a platform specific env for passing into subprocess.Popen family of external process calling methods, and the supplied env will be updated on top of it. Returns a new env. """ keys = _PLATFORM_ENV_KEYS.get(sys.platform, []) if 'PATH' not in keys: ...
def fork_exec(args, stdin='', **kwargs): """ Do a fork-exec through the subprocess.Popen abstraction in a way that takes a stdin and return stdout. """ as_bytes = isinstance(stdin, bytes) source = stdin if as_bytes else stdin.encode(locale) p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PI...
def raise_os_error(_errno, path=None): """ Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2.7. """ msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno) raise OSError(_errno, msg)
def which(cmd, mode=os.F_OK | os.X_OK, path=None): """ Given cmd, check where it is on PATH. Loosely based on the version in python 3.3. """ if os.path.dirname(cmd): if os.path.isfile(cmd) and os.access(cmd, mode): return cmd if path is None: path = os.environ.get(...
def _init(self): """ Turn the records into actual usable keys. """ self._entry_points = {} for entry_point in self.raw_entry_points: if entry_point.dist.project_name != self.reserved.get( entry_point.name, entry_point.dist.project_name): ...
def dict_update_overwrite_check(base, fresh): """ For updating a base dict with a fresh one, returning a list of 3-tuples containing the key, previous value (base[key]) and the fresh value (fresh[key]) for all colliding changes (reassignment of identical values are omitted). """ result = [ ...
def spec_update_loaderplugin_registry(spec, default=None): """ Resolve a BasePluginLoaderRegistry instance from spec, and update spec[CALMJS_LOADERPLUGIN_REGISTRY] with that value before returning it. """ registry = spec.get(CALMJS_LOADERPLUGIN_REGISTRY) if isinstance(registry, BaseLoaderPl...
def spec_update_sourcepath_filter_loaderplugins( spec, sourcepath_map, sourcepath_map_key, loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS): """ Take an existing spec and a sourcepath mapping (that could be produced via calmjs.dist.*_module_registry_dependencies functions) a...
def toolchain_spec_prepare_loaderplugins( toolchain, spec, loaderplugin_read_key, handler_sourcepath_key, loaderplugin_sourcepath_map_key=LOADERPLUGIN_SOURCEPATH_MAPS): """ A standard helper function for combining the filtered (e.g. using ``spec_update_sourcepath_filter_loade...
def toolchain_spec_compile_entries( toolchain, spec, entries, process_name, overwrite_log=None): """ The standardized Toolchain Spec Entries compile function This function accepts a toolchain instance, the spec to be operated with and the entries provided for the process name. The standard ...
def process_compile_entries( processor, spec, entries, modpath_logger=None, targetpath_logger=None): """ The generalized raw spec entry process invocation loop. """ # Contains a mapping of the module name to the compiled file's # relative path starting from the base build_dir. all_modpa...
def update_selected(self, other, selected): """ Like update, however a list of selected keys must be provided. """ self.update({k: other[k] for k in selected})
def __advice_stack_frame_protection(self, frame): """ Overriding of this is only permitted if and only if your name is Megumin and you have a pet/familiar named Chomusuke. """ if frame is None: logger.debug( 'currentframe() returned None; frame protec...
def advise(self, name, f, *a, **kw): """ Add an advice that will be handled later by the handle method. Arguments: name The name of the advice group f A callable method or function. The rest of the arguments will be passed as arguments and ...
def handle(self, name): """ Call all advices at the provided name. This has an analogue in the join point in aspected oriented programming, but the analogy is a weak one as we don't have the proper metaobject protocol to support this. Implementation that make use of thi...
def realpath(self, spec, key): """ Resolve and update the path key in the spec with its realpath, based on the working directory. """ if key not in spec: # do nothing for now return if not spec[key]: logger.warning( "c...
def setup_prefix_suffix(self): """ Set up the compile prefix, sourcepath and the targetpath suffix attributes, which are the prefix to the function name and the suffixes to retrieve the values from for creating the generator function. """ self.compile_prefix = 'c...
def _validate_build_target(self, spec, target): """ Essentially validate that the target is inside the build_dir. """ if not realpath(target).startswith(spec[BUILD_DIR]): raise ValueError('build_target %s is outside build_dir' % target)
def transpile_modname_source_target(self, spec, modname, source, target): """ The function that gets called by compile_transpile_entry for processing the provided JavaScript source file provided by some Python package through the transpiler instance. """ if not isinstanc...
def simple_transpile_modname_source_target( self, spec, modname, source, target): """ The original simple transpile method called by compile_transpile on each target. """ opener = self.opener bd_target = self._generate_transpile_target(spec, target) l...
def compile_transpile_entry(self, spec, entry): """ Handler for each entry for the transpile method of the compile process. This invokes the transpiler that was set up to transpile the input files into the build directory. """ modname, source, target, modpath = entry ...
def compile_bundle_entry(self, spec, entry): """ Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory. """ modname, source, target, modpath = entry bundled_modpath = {modname: modp...
def compile_loaderplugin_entry(self, spec, entry): """ Generic loader plugin entry handler. The default implementation assumes that everything up to the first '!' symbol resolves to some known loader plugin within the registry. The registry instance responsible for the ...
def modname_source_to_target(self, spec, modname, source): """ Create a target file name from the input module name and its source file name. The result should be a path relative to the build_dir, and this is derived directly from the modname with NO implicit convers of path sep...
def modname_source_target_modnamesource_to_modpath( self, spec, modname, source, target, modname_source): """ Typical JavaScript tools will get confused if '.js' is added, so by default the same modname is returned as path rather than the target file for the module path to be...
def _gen_modname_source_target_modpath(self, spec, d): """ Private generator that will consume those above functions. This should NOT be overridden. Produces the following 4-tuple on iteration with the input dict; the definition is written at the module level documention for ...
def compile(self, spec): """ Generic step that compiles from a spec to build the specified things into the build directory `build_dir`, by gathering all the files and feed them through the transpilation process or by simple copying. """ spec[EXPORT_MODULE_NAMES] ...
def _calf(self, spec): """ The main call, assuming the base spec is prepared. Also, no advices will be triggered. """ self.prepare(spec) self.compile(spec) self.assemble(spec) self.link(spec) self.finalize(spec)
def calf(self, spec): """ Typical safe usage is this, which sets everything that could be problematic up. Requires the filename which everything will be produced to. """ if not isinstance(spec, Spec): raise TypeError('spec must be of type Spec') if ...
def transpile_modname_source_target(self, spec, modname, source, target): """ Calls the original version. """ return self.simple_transpile_modname_source_target( spec, modname, source, target)
def get_bin_version_str(bin_path, version_flag='-v', kw={}): """ Get the version string through the binary. """ try: prog = _get_exec_binary(bin_path, kw) version_str = version_expr.search( check_output([prog, version_flag], **kw).decode(locale) ).groups()[0] exc...
def get_bin_version(bin_path, version_flag='-v', kw={}): """ Get the version string through the binary and return a tuple of integers. """ version_str = get_bin_version_str(bin_path, version_flag, kw) if version_str: return tuple(int(i) for i in version_str.split('.'))
def node(self, source, args=(), env={}): """ Calls node with an inline source. Returns decoded output of stdout and stderr; decoding determine by locale. """ return self._exec(self.node_bin, source, args=args, env=env)
def create_for_module_vars(cls, scope_vars): """ This was originally designed to be invoked at the module level for packages that implement specific support, but this can be used to create an instance that has the Node.js backed executable be found via current directory's node_mo...
def pkg_manager_view( self, package_names, stream=None, explicit=False, **kw): """ Returns the manifest JSON for the Python package name. Default npm implementation calls for package.json. If this class is initiated using standard procedures, this will mimic the fun...
def pkg_manager_init( self, package_names, overwrite=False, merge=False, callback=None, **kw): """ Note: default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated...
def pkg_manager_install( self, package_names=None, production=None, development=None, args=(), env={}, **kw): """ This will install all dependencies into the current working directory for the specific Python package from the selected JavaScript package...
def run(self, args=(), env={}): """ Calls the package manager with the arguments. Returns decoded output of stdout and stderr; decoding determine by locale. """ # the following will call self._get_exec_binary return self._exec(self.binary, args=args, env=env)
def _get_exec_binary(binary, kw): """ On win32, the subprocess module can only reliably resolve the target binary if it's actually a binary; as for a Node.js script it seems to only work iff shell=True was specified, presenting a security risk. Resolve the target manually through which will acc...
def _init_entry_points(self, entry_points): """ Default initialization loop. """ logger.debug( "registering %d entry points for registry '%s'", len(entry_points), self.registry_name, ) for entry_point in entry_points: try: ...
def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records already exist in the module mapping list, # it likely means that a package declared multiple keys for the # same package name...
def register_entry_point(self, entry_point): """ Register a lone entry_point Will raise ImportError if the entry_point leads to an invalid import. """ module = _import_module(entry_point.module_name) self._register_entry_point_module(entry_point, module)
def _register_entry_point_module(self, entry_point, module): """ Private method that registers an entry_point with a provided module. """ records_map = self._map_entry_point_module(entry_point, module) self.store_records_for_package(entry_point, list(records_map.keys()))...
def get_record(self, name): """ Get a record by name """ result = {} result.update(self.records.get(name, {})) return result
def get_records_for_package(self, package_name): """ Get all records identified by package. """ names = self.package_module_map.get(package_name, []) result = {} for name in names: result.update(self.get_record(name)) return result
def resolve_parent_registry_name(self, registry_name, suffix): """ Subclasses should override to specify the default suffix, as the invocation is done without a suffix. """ if not registry_name.endswith(suffix): raise ValueError( "child module registr...
def get_record(self, name): """ Get a record for the registered name, which will be a set of matching desired "module names" for the given path. """ return set().union(self.records.get(name, set()))
def get_records_for_package(self, package_name): """ Get all records identified by package. """ result = [] result.extend(self.package_module_map.get(package_name)) return result
def which(self): """ Figure out which binary this will execute. Returns None if the binary is not found. """ if self.binary is None: return None return which(self.binary, path=self.env_path)
def find_node_modules_basedir(self): """ Find all node_modules directories configured to be accessible through this driver instance. This is typically used for adding the direct instance, and does not traverse the parent directories like what Node.js does. Returns a lis...
def which_with_node_modules(self): """ Which with node_path and node_modules """ if self.binary is None: return None # first, log down the pedantic things... if isdir(self.join_cwd(NODE_MODULES)): logger.debug( "'%s' instance will...
def _set_env_path_with_node_modules(self): """ Attempt to locate and set the paths to the binary with the working directory defined for this instance. """ modcls_name = ':'.join(( self.__class__.__module__, self.__class__.__name__)) if self.binary is None: ...
def _exec(self, binary, stdin='', args=(), env={}): """ Executes the binary using stdin and args with environment variables. Returns a tuple of stdout, stderr. Format determined by the input text (either str or bytes), and the encoding of str will be determined by the l...
def dump(self, blob, stream): """ Call json.dump with the attributes of this instance as arguments. """ json.dump( blob, stream, indent=self.indent, sort_keys=True, separators=self.separators, )
def dumps(self, blob): """ Call json.dumps with the attributes of this instance as arguments. """ return json.dumps( blob, indent=self.indent, sort_keys=True, separators=self.separators, )
def join_cwd(self, path=None): """ Join the path with the current working directory. If it is specified for this instance of the object it will be used, otherwise rely on the global value. """ if self.working_dir: logger.debug( "'%s' instance...
def modname_source_to_target( self, toolchain, spec, modname, source): """ This is called by the Toolchain for modnames that contain a '!' as that signifies a loaderplugin syntax. This will be used by the toolchain (which will also be supplied as the first argument) ...
def unwrap(self, value): """ A helper method for unwrapping the loaderplugin fragment out of the provided value (typically a modname) and return it. Note that the filter chaining is very implementation specific to each and every loader plugin and their specific toolchain, so ...
def _unicode_handler(obj): """ Transforms an unicode string into a UTF-8 equivalent. :param obj: object to transform into it's UTF-8 equivalent :return: the UTF-8 equivalent of the string """ try: result = obj.isoformat() except AttributeError: raise TypeError("Unserializabl...
def encode(self, entity): """ Encodes the data, creating a JSON structure from an instance from the domain model. :param entity: the instance to encode :return: a JSON structure created from the received data """ encoded = self._dict_encoder.encode(entity) ...
def ipi_base_number(name=None): """ IPI Base Number field. An IPI Base Number code written on a field follows the Pattern C-NNNNNNNNN-M. This being: - C: header, a character. - N: numeric value. - M: control digit. So, for example, an IPI Base Number code field can contain I-000000229-...
def ipi_name_number(name=None): """ IPI Name Number field. An IPI Name Number is composed of eleven digits. So, for example, an IPI Name Number code field can contain 00014107338. :param name: name for the field :return: a parser for the IPI Name Number field """ if name is None: ...
def iswc(name=None): """ ISWC field. A ISWC code written on a field follows the Pattern TNNNNNNNNNC. This being: - T: header, it is always T. - N: numeric value. - C: control digit. So, for example, an ISWC code field can contain T0345246801. :param name: name for the field :r...
def percentage(columns, maximum=100, name=None): """ Creates the grammar for a Numeric (N) field storing a percentage and accepting only the specified number of characters. It is possible to set the maximum allowed value. By default this is 100 (for 100%), and if modified it is expected to be reduc...
def _assert_is_percentage(value, maximum=100): """ Makes sure the received value is a percentage. Otherwise an exception is thrown. :param value: the value to check """ if value < 0 or value > maximum: message = 'The value on a percentage field should be between 0 and %s' \ ...
def ean_13(name=None): """ Creates the grammar for an EAN 13 code. These are the codes on thirteen digits barcodes. :param name: name for the field :return: grammar for an EAN 13 field """ if name is None: name = 'EAN 13 Field' field = basic.numeric(13) field = field.set...
def isrc(name=None): """ Creates the grammar for an ISRC code. ISRC stands for International Standard Recording Code, which is the standard ISO 3901. This stores information identifying a particular recording. :param name: name for the field :return: grammar for an ISRC field """ ...
def _isrc_long(name=None): """ Creates the grammar for a short ISRC code. ISRC stands for International Standard Recording Code, which is the standard ISO 3901. This stores information identifying a particular recording. This variant contain no separator for the parts, and follows the pattern:...
def visan(name=None): """ Creates the grammar for a V-ISAN code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'V-ISAN Field' field = pp.Regex('[0-9]{2...
def audio_visual_key(name=None): """ Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'AVI Field' societ...
def date_time(name=None): """ Creates the grammar for a date and time field, which is a combination of the Date (D) and Time or Duration field (T). This field requires first a Date, and then a Time, without any space in between. :param name: name for the field :return: grammar for a Date a...
def lookup_int(values, name=None): """ Lookup field which transforms the result into an integer. :param values: values allowed :param name: name for the field :return: grammar for the lookup field """ field = basic.lookup(values, name) field.addParseAction(lambda l: int(l[0])) ret...
def extract_function_argument(text, f_name, f_argn, f_argt=asttypes.String): """ Extract a specific argument from a specific function name. Arguments: text The source text. f_name The name of the function f_argn The argument position f_argt The argument type...
def yield_amd_require_string_arguments( node, pos, reserved_module=reserved_module, wrapped=define_wrapped): """ This yields only strings within the lists provided in the argument list at the specified position from a function call. Originally, this was implemented for yield a list of m...
def yield_string_argument(node, pos): """ Yield just a string argument from position of the function call. """ if not isinstance(node.args.items[pos], asttypes.String): return yield to_str(node.args.items[pos])
def yield_module_imports(root, checks=string_imports()): """ Gather all require and define calls from unbundled JavaScript source files and yield all module names. The imports can either be of the CommonJS or AMD syntax. """ if not isinstance(root, asttypes.Node): raise TypeError('prov...
def yield_module_imports_nodes(root, checks=import_nodes()): """ Yield all nodes that provide an import """ if not isinstance(root, asttypes.Node): raise TypeError('provided root must be a node') for child in yield_function(root, deep_filter): for f, condition in checks: ...
def open_fasta_index(self): """ custom type for file made w/ buildFastaIndex, fai for ones made with samtools """ index = self.fasta_index try: handle = open(index, 'rb') except (IOError, TypeError): sys.stderr.write('index not found, creating it\n...
def get_sequence(self, chrom, start, end, strand='+', indexing=(-1, 0)): """ chromosome is entered relative to the file it was built with, so it can be 'chr11' or '11', start/end are coordinates, which default to python style [0,1) internally. So positions should be entered with (1,1) in...
def resolve_child_module_registries_lineage(registry): """ For a given child module registry, attempt to resolve the lineage. Return an iterator, yielding from parent down to the input registry, inclusive of the input registry. """ children = [registry] while isinstance(registry, BaseChild...
def addModification(self, aa,position, modMass, modType): """ !!!!MODIFICATION POSITION IS 0 BASED!!!!!! Modifications are stored internally as a tuple with this format: (amino acid modified, index in peptide of amino acid, modification type, modification mass) ie (M, 7, Oxidatio...
def resource_filename_mod_dist(module_name, dist): """ Given a module name and a distribution, attempt to resolve the actual path to the module. """ try: return pkg_resources.resource_filename( dist.as_requirement(), join(*module_name.split('.'))) except pkg_resources.Distri...