code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if name is None:
name = 'Time Field'
# Basic field
# This regex allows values from 000000 to 235959
field = pp.Regex('(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]')
# Parse action
field.setParseAction(lambda t: datetime.datetime.strptime(t[0], '%H%M%S')
.ti... | def time(name=None) | Creates the grammar for a Time or Duration (T) field, accepting only
numbers in a certain pattern.
:param name: name for the field
:return: grammar for the date field | 4.504482 | 4.028834 | 1.118061 |
if name is None:
name = 'Lookup Field'
if values is None:
raise ValueError('The values can no be None')
# TODO: This should not be needed, it is just a patch. Fix this.
try:
v = values.asList()
values = v
except AttributeError:
values = values
# On... | def lookup(values, name=None) | Creates the grammar for a Lookup (L) field, accepting only values from a
list.
Like in the Alphanumeric field, the result will be stripped of all heading
and trailing whitespaces.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field | 5.525526 | 5.34498 | 1.033779 |
if name is None:
name = 'Blank Field'
field = pp.Regex('[ ]{' + str(columns) + '}')
field.leaveWhitespace()
field.suppress()
field.setName(name)
return field | def blank(columns=1, name=None) | Creates the grammar for a blank field.
These are for constant empty strings which should be ignored, as they are
used just as fillers.
:param columns: number of columns, which is the required number of
whitespaces
:param name: name for the field
:return: grammar for the blank field | 5.926344 | 6.348005 | 0.933576 |
if attribute in self.filters:
valid_gff_objects = self.fast_attributes[attribute] if not value else\
[i for i in self.fast_attributes[attribute] if i.attributes.get(attribute, False) == value]
if features:
valid_ids = [gff_object.attributes.get(se... | def get_attribute(self, attribute, value=None, features=False) | This returns a list of GFF objects (or GFF Features) with the given attribute and if supplied, those
attributes with the specified value
:param attribute: The 'info' field attribute we are querying
:param value: Optional keyword, only return attributes equal to this value
:param feature... | 1.965012 | 1.916331 | 1.025403 |
d = self.positions.get(seqid,[])
if overlap:
return [gff_object for gff_start, gff_end in d
for gff_object in d[(gff_start, gff_end)]
if not (end <= gff_start or start >= gff_end)]
else:
return [gff_object for gff_start, gf... | def contains(self, seqid, start, end, overlap=True) | This returns a list of GFF objects which cover a specified location.
:param seqid: The landmark identifier (usually a chromosome)
:param start: The 1-based position of the start of the range we are querying
:param end: The 1-based position of the end of the range we are querying
:param ... | 2.454911 | 2.508141 | 0.978777 |
d = self.positions.get(chrom,[])
if overlap:
return [vcf_entry for vcf_start, vcf_end in d
for vcf_entry in d[(vcf_start, vcf_end)]
if not (end < vcf_start or start > vcf_end)]
else:
return [vcf_entry for vcf_start, vcf_end... | def contains(self, chrom, start, end, overlap=True) | This returns a list of VCFEntry objects which cover a specified location.
:param chrom: The landmark identifier (usually a chromosome)
:param start: The 1-based position of the start of the range we are querying
:param end: The 1-based position of the end of the range we are querying
:p... | 2.427695 | 2.558589 | 0.948841 |
chroms = set([i.chrom for i in variants])
for chrom in chroms:
if self.append_chromosome:
chrom = 'chr%s' % chrom
to_delete = [pos for pos in self.positions[chrom] if pos in variants]
for pos in to_delete:
del self.positions[ch... | def remove_variants(self, variants) | Remove a list of variants from the positions we are scanning | 3.04298 | 2.966192 | 1.025888 |
# since the loaderplugin_sourcepath values is the complete
# modpath with the loader plugin, the values must be stripped
# before making use of the filtering helper function for
# grouping the inner mappings
fake_spec = {}
registry = spec.get(CALMJS_LOADERPLUGIN... | def generate_handler_sourcepath(
self, toolchain, spec, loaderplugin_sourcepath) | The default implementation is a recursive lookup method, which
subclasses may make use of.
Subclasses must implement this to return a mapping of modnames
the the absolute path of the desired sourcefiles. Example:
return {
'text': '/tmp/src/example_module/text/index.js',
... | 6.443008 | 6.253746 | 1.030264 |
# TODO calmjs-4.0.0 consider formalizing to the method instead
npm_pkg_name = (
self.node_module_pkg_name
if self.node_module_pkg_name else
self.find_node_module_pkg_name(toolchain, spec)
)
if not npm_pkg_name:
cls = type(self)
... | def generate_handler_sourcepath(
self, toolchain, spec, loaderplugin_sourcepath) | Attempt to locate the plugin source; returns a mapping of
modnames to the absolute path of the located sources. | 4.850111 | 4.799769 | 1.010488 |
pkg_records_entry = self._dist_to_package_module_map(entry_point)
pkg_records_entry.extend(
rec for rec in records if rec not in pkg_records_entry)
# TODO figure out a more efficient way to do this with a bit
# more reuse.
if entry_point.dist is not None:
... | def store_records_for_package(self, entry_point, records) | Given that records are based on the parent, and the same entry
point(s) will reference those same records multiple times, the
actual stored records must be limited. | 3.68698 | 3.647112 | 1.010931 |
config = CWRConfiguration()
field_configs = config.load_field_config('table')
field_configs.update(config.load_field_config('common'))
field_values = CWRTables()
for entry in field_configs.values():
if 'source' in entry:
values_id = entry['source']
entry['value... | def default_file_encoder() | Get default encoder cwr file
:return: | 5.195536 | 5.201881 | 0.99878 |
# Acquires sequence number
sequence = str(tag.sequence_n)
# If the sequence is bigger the max, it is cut
if len(sequence) > self._sequence_l:
sequence = sequence[:self._sequence_l]
# If the sequence is smaller the max, it is padded with zeroes
while... | def encode(self, tag) | Parses a CWR file name from a FileTag object.
The result will be a string following the format CWyynnnnsss_rrr.Vxx,
where the numeric sequence will have the length set on the encoder's
constructor.
:param tag: FileTag to parse
:return: a string file name parsed from the FileTag | 3.826506 | 3.700699 | 1.033996 |
data = ''
data += self._record_encode(transmission.header)
for group in transmission.groups:
data += self._record_encode(group.group_header)
for transaction in group.transactions:
for record in transaction:
data += self._record... | def encode(self, transmission) | Encodes the data, creating a CWR structure from an instance from the
domain model.
:param entity: the instance to encode
:return: a cwr string structure created from the received data | 2.637456 | 2.739773 | 0.962655 |
if not self.scans:
for i in self:
yield i
else:
for i in self.scans.values():
yield i
yield None | def getScans(self, modifications=True, fdr=True) | get a random scan | 4.744627 | 4.426815 | 1.071793 |
if self.ra.has_key(title):
self.filename.seek(self.ra[title][0],0)
toRead = self.ra[title][1]-self.ra[title][0]
info = self.filename.read(toRead)
scan = self.parseScan(info)
else:
return None
return scan | def getScan(self, title, peptide=None) | allows random lookup | 3.956081 | 3.791581 | 1.043386 |
setupScan = True
foundCharge = False
foundMass = False
foundTitle = False
scanObj = ScanObject()
scanObj.ms_level = 2
for row in scan.split('\n'):
if not row:
continue
entry = row.strip().split('=')
if l... | def parseScan(self, scan) | All input follows the BEGIN IONS row and ends before END IONS | 2.679133 | 2.523345 | 1.061738 |
sql = self.base_sql + " where sh.SpectrumID = %d and p.Sequence = '%s'"%(int(specId),peptide)
self.cur.execute(sql)
i = self.cur.fetchone()
if not i:
return None
scan = self.parseFullScan(i)
scan.spectrumId = specId
return scan | def getScan(self, specId, peptide=None) | get a random scan | 4.242962 | 4.436697 | 0.956333 |
if fdr:
sql = self.base_sql+"WHERE p.ConfidenceLevel >= {} and p.SearchEngineRank <= {} {}".format(self.clvl, self.srank, self.extra)
try:
self.cur.execute(sql)
except sqlite3.OperationalError:
sql = self.base_sql+"WHERE p.ConfidenceLe... | def getScans(self, modifications=False, fdr=True) | get a random scan | 2.871096 | 2.900779 | 0.989767 |
scanObj = PeptideObject()
peptide = str(i[1])
pid=i[2]
scanObj.acc = self.protein_map.get(i[4], i[4])
if pid is None:
return None
if modifications:
sql = 'select aam.ModificationName,pam.Position,aam.DeltaMass from peptidesaminoacidmodific... | def parseFullScan(self, i, modifications=False) | parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml | 3.341064 | 3.310944 | 1.009097 |
if fdr:
sql = "select sp.Spectrum, p.Sequence, p.PeptideID, p.SpectrumID from spectrumheaders sh left join spectra sp on (sp.UniqueSpectrumID=sh.UniqueSpectrumID) left join peptides p on (sh.SpectrumID=p.SpectrumID) WHERE p.ConfidenceLevel >= %d and p.SearchEngineRank <= %d" % (self.clvl, s... | def getScans(self, modifications=True, fdr=True) | get a random scan | 2.284088 | 2.300715 | 0.992773 |
scanObj = PeptideObject()
peptide = str(i[1])
pid=i[2]
if modifications:
sql = 'select aam.ModificationName,pam.Position,aam.DeltaMass from peptidesaminoacidmodifications pam left join aminoacidmodifications aam on (aam.AminoAcidModificationID=pam.AminoAcidModificati... | def parseFullScan(self, i, modifications=True) | parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml | 4.603825 | 4.465827 | 1.030901 |
frags = cls.__module__.split('.')
for name in ('.'.join(frags[:x]) for x in range(len(frags), 0, -1)):
dist = find_pkg_dist(name)
if dist:
return dist | def _cls_lookup_dist(cls) | Attempt to resolve the distribution from the provided class in the
most naive way - this assumes the Python module path to the class
contains the name of the package that provided the module and class. | 4.636308 | 3.67721 | 1.260822 |
try:
d = getcallargs(builder, package_names=[], export_target='some_path')
except TypeError:
return False
return d == {'package_names': [], 'export_target': 'some_path'} | def verify_builder(builder) | To ensure that the provided builder has a signature that is at least
compatible. | 8.855957 | 9.294372 | 0.95283 |
try:
toolchain, spec = builder_result
except Exception:
return None, None
if not isinstance(toolchain, toolchain_cls) or not isinstance(spec, Spec):
return None, None
return toolchain, spec | def extract_builder_result(builder_result, toolchain_cls=Toolchain) | Extract the builder result to produce a ``Toolchain`` and ``Spec``
instance. | 3.544889 | 2.484143 | 1.427007 |
pkgs = []
for cls in getmro(type(toolchain)):
if not issubclass(cls, Toolchain):
continue
dist = _cls_lookup_dist(cls)
value = {
'project_name': dist.project_name,
'version': dist.version,
} if dist else {}
key = '%s:%s' % (cls.__... | def trace_toolchain(toolchain) | Trace the versions of the involved packages for the provided
toolchain instance. | 3.980039 | 3.861979 | 1.03057 |
project_name = self.packages.normalize(package_name)
return self.records.get((project_name, artifact_name)) | def get_artifact_filename(self, package_name, artifact_name) | Similar to pkg_resources.resource_filename, however this works
with the information cached in this registry instance, and
arguments are not quite the same.
Arguments:
package_name
The name of the package to get the artifact from
artifact_name
The exact n... | 9.16114 | 7.4898 | 1.223149 |
paths = self.compat_builders.get(builder_name)
if not paths:
# perhaps warn, but just return
return
resolver = (
# traces dependencies for distribution.
find_packages_requirements_dists
if dependencies else
# just... | def resolve_artifacts_by_builder_compat(
self, package_names, builder_name, dependencies=False) | Yield the list of paths to the artifacts in the order of the
dependency resolution
Arguments:
package_names
The names of the packages to probe the dependency graph, to
be provided as a list of strings.
artifact_name
The exact name of the artifact.
... | 9.530653 | 9.91042 | 0.96168 |
filename = self.metadata.get(package_name)
if not filename or not exists(filename):
return {}
with open(filename, encoding='utf8') as fd:
contents = fd.read()
try:
is_json_compat(contents)
except ValueError:
logger.info("... | def get_artifact_metadata(self, package_name) | Return metadata of the artifacts built through this registry. | 4.040991 | 3.967153 | 1.018612 |
export_target = spec['export_target']
toolchain_bases = trace_toolchain(toolchain)
toolchain_bin_path = spec.get(TOOLCHAIN_BIN_PATH)
toolchain_bin = ([
basename(toolchain_bin_path), # bin_name
get_bin_version_str(toolchain_bin_path), # bin_version
... | def generate_metadata_entry(self, entry_point, toolchain, spec) | After the toolchain and spec have been executed, this may be
called to generate the artifact export entry for persistence
into the metadata file. | 4.567957 | 4.514386 | 1.011867 |
entry_points = self.packages.get(package_name, NotImplemented)
if entry_points is NotImplemented:
logger.debug(
"package '%s' has not declared any entry points for the '%s' "
"registry for artifact construction",
package_name, self.re... | def iter_records_for(self, package_name) | Iterate records for a specific package. | 3.112334 | 3.023772 | 1.029289 |
try:
builder = entry_point.resolve()
except ImportError:
logger.error(
"unable to import the target builder for the entry point "
"'%s' from package '%s' to generate artifact '%s'",
entry_point, entry_point.dist, export_ta... | def generate_builder(self, entry_point, export_target) | Yields exactly one builder if both the provided entry point and
export target satisfies the checks required. | 3.630482 | 3.651331 | 0.99429 |
toolchain(spec)
if not exists(spec['export_target']):
logger.error(
"the entry point '%s' from package '%s' failed to "
"generate an artifact at '%s'",
entry_point, entry_point.dist, spec['export_target']
)
ret... | def execute_builder(self, entry_point, toolchain, spec) | Accepts the arguments provided by the builder and executes them. | 7.069538 | 8.216987 | 0.860357 |
metadata = super(ArtifactRegistry, self).process_package(package_name)
if metadata:
self.update_artifact_metadata(package_name, metadata) | def process_package(self, package_name) | Build artifacts declared for the given package. | 5.287104 | 4.532889 | 1.166387 |
if name is None:
name = 'Alphanumeric Field'
if min_size < 0:
# Can't have negative min
raise BaseException()
if max_size < min_size:
# Max can't be lower than min
raise BaseException()
field = pp.Word(pp.alphanums, min=min_size, max=max_size)
# Parse... | def alphanum_variable(min_size, max_size, name=None) | Creates the grammar for an alphanumeric code where the size ranges between
two values.
:param min_size: minimum size
:param max_size: maximum size
:param name: name for the field
:return: grammar for an alphanumeric field of a variable size | 3.828435 | 3.963716 | 0.96587 |
if columns < 0:
# Can't have negative size
raise BaseException()
field = numeric(columns, name)
# Parse action
field.addParseAction(_to_year)
return field | def year(columns, name=None) | Creates the grammar for a field containing a year.
:param columns: the number of columns for the year
:param name: the name of the field
:return: | 18.243366 | 15.07788 | 1.209942 |
try:
value = json.loads(value)
except ValueError as e:
raise ValueError('JSON decoding error: ' + str(e))
except TypeError:
# Check that the value can be serialized back into json.
try:
json.dumps(value)
except TypeError as e:
raise Value... | def is_json_compat(value) | Check that the value is either a JSON decodable string or a dict
that can be encoded into a JSON.
Raises ValueError when validation fails. | 3.549125 | 3.299346 | 1.075706 |
try:
is_json_compat(value)
except ValueError as e:
raise DistutilsSetupError("%r %s" % (attr, e))
return True | def validate_json_field(dist, attr, value) | Check for json validity. | 6.473738 | 5.874042 | 1.102093 |
# does not work as reliably in Python 2.
if isinstance(value, str):
value = value.split()
value = list(value)
try:
check = (' '.join(value)).split()
if check == value:
return True
except Exception:
pass
raise DistutilsSetupError("%r must be a li... | def validate_line_list(dist, attr, value) | Validate that the value is compatible | 5.528996 | 5.892703 | 0.938279 |
value = getattr(cmd.distribution, argname, None)
if isinstance(value, dict):
value = json.dumps(
value, indent=4, sort_keys=True, separators=(',', ': '))
cmd.write_or_delete_file(argname, filename, value, force=True) | def write_json_file(argname, cmd, basename, filename) | Write JSON captured from the defined argname into the package's
egg-info directory using the specified filename. | 4.123889 | 4.012986 | 1.027636 |
values = getattr(cmd.distribution, argname, None)
if isinstance(values, list):
values = '\n'.join(values)
cmd.write_or_delete_file(argname, filename, values, force=True) | def write_line_list(argname, cmd, basename, filename) | Write out the retrieved value as list of lines. | 5.543773 | 5.061382 | 1.095308 |
working_set = working_set or default_working_set
req = Requirement.parse(pkg_name)
return working_set.find(req) | def find_pkg_dist(pkg_name, working_set=None) | Locate a package's distribution by its name. | 3.297272 | 3.316909 | 0.99408 |
results = []
errors = []
for name in (
package_names.split()
if hasattr(package_names, 'split') else package_names):
try:
Requirement.parse(name)
except ValueError:
errors.append(name)
else:
results.append(name)
... | def convert_package_names(package_names) | Convert package names, which can be a string of a number of package
names or requirements separated by spaces. | 3.237364 | 2.84558 | 1.137682 |
working_set = working_set or default_working_set
requirements = [
r for r in (Requirement.parse(req) for req in pkg_names)
if working_set.find(r)
]
return list(reversed(working_set.resolve(requirements))) | def find_packages_requirements_dists(pkg_names, working_set=None) | Return the entire list of dependency requirements, reversed from the
bottom. | 3.625126 | 3.616657 | 1.002342 |
dists = []
# opting for a naive implementation
targets = set(pkg_names)
for dist in find_packages_requirements_dists(pkg_names, working_set):
if dist.project_name in targets:
continue
dists.append(dist)
return dists | def find_packages_parents_requirements_dists(pkg_names, working_set=None) | Leverages the `find_packages_requirements_dists` but strip out the
distributions that matches pkg_names. | 3.999437 | 3.498188 | 1.143288 |
# use the given package's distribution to acquire the json file.
if not dist.has_metadata(filename):
logger.debug("no '%s' for '%s'", filename, dist)
return
try:
result = dist.get_metadata(filename)
except IOError:
logger.error("I/O error on reading of '%s' for '%s... | def read_dist_egginfo_json(dist, filename=DEFAULT_JSON) | Safely get a json within an egginfo from a distribution. | 3.184834 | 3.079555 | 1.034186 |
working_set = working_set or default_working_set
dist = find_pkg_dist(pkg_name, working_set=working_set)
return read_dist_egginfo_json(dist, filename) | def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None) | Read json from egginfo of a package identified by `pkg_name` that's
already installed within the current Python environment. | 3.005456 | 3.497225 | 0.859383 |
working_set = working_set or default_working_set
obj = {}
# TODO figure out the best way to explicitly report back to caller
# how the keys came to be (from which dist). Perhaps create a
# detailed function based on this, retain this one to return the
# distilled results.
depends = ... | def flatten_dist_egginfo_json(
source_dists, filename=DEFAULT_JSON, dep_keys=DEP_KEYS,
working_set=None) | Flatten a distribution's egginfo json, with the depended keys to be
flattened.
Originally this was done for this:
Resolve a distribution's (dev)dependencies through the working set
and generate a flattened version package.json, returned as a dict,
from the resolved distributions.
Default work... | 7.831075 | 7.772117 | 1.007586 |
working_set = working_set or default_working_set
# Ensure only grabbing packages that exists in working_set
dists = find_packages_requirements_dists(
pkg_names, working_set=working_set)
return flatten_dist_egginfo_json(
dists, filename=filename, dep_keys=dep_keys, working_set=worki... | def flatten_egginfo_json(
pkg_names, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None) | A shorthand calling convention where the package name is supplied
instead of a distribution.
Originally written for this:
Generate a flattened package.json with packages `pkg_names` that are
already installed within the current Python environment (defaults
to the current global working_set which s... | 3.876289 | 4.450199 | 0.871037 |
json_filename = (
json_field + '.json' if json_filename is None else json_filename)
# Default calmjs core implementation specific functions, to be used by
# integrators intended to use this as a distribution.
def get_extras_json(pkg_names, working_set=None):
working_set... | def build_helpers_egginfo_json(
json_field, json_key_registry, json_filename=None) | Return a tuple of functions that will provide the usage of the
JSON egginfo based around the provided field. | 3.113721 | 3.152942 | 0.98756 |
def get_module_registry_dependencies(
pkg_names, registry_name=registry_name, working_set=None):
working_set = working_set or default_working_set
registry = get(registry_name)
if not isinstance(registry, BaseModuleRegistry):
return {}
result = ... | def build_helpers_module_registry_dependencies(registry_name='calmjs.module') | Return a tuple of funtions that will provide the functions that
return the relevant sets of module registry records based on the
dependencies defined for the provided packages. | 2.002249 | 1.954989 | 1.024174 |
return any(get(registry_name).iter_records_for(
cmd.distribution.get_name())) | def has_calmjs_artifact_declarations(cmd, registry_name='calmjs.artifacts') | For a distutils command to verify that the artifact build step is
possible. | 24.940397 | 14.908642 | 1.672882 |
if value is not True:
return
build_cmd = dist.get_command_obj('build')
if not isinstance(build_cmd, cmdclass):
logger.error(
"'build' command in Distribution is not an instance of "
"'%s:%s' (got %r instead)",
cmdclass.__module__, cmdclass.__name__,... | def build_calmjs_artifacts(dist, key, value, cmdclass=BuildCommand) | Trigger the artifact build process through the setuptools. | 4.55165 | 4.803332 | 0.947603 |
if field_id in self._fields:
# Field already exists
field = self._fields[field_id]
else:
# Field does not exist
# It is created
field = self._create_field(field_id)
# Field is saved
self._fields[field_id] = fi... | def get_rule(self, field_id) | Returns the rule for the field identified by the id.
If it is set as not being compulsory, the rule will be adapted to
accept string composed only of white characters.
:param field_id: unique id in the system for the field
:return: the rule of a field | 2.886237 | 3.083715 | 0.935961 |
# Field configuration info
config = self._field_configs[field_id]
adapter = self._adapters[config['type']]
if 'name' in config:
name = config['name']
else:
name = None
if 'size' in config:
columns = config['size']
el... | def _create_field(self, field_id) | Creates the field with the specified parameters.
:param field_id: identifier for the field
:return: the basic rule for the field | 2.731955 | 2.883291 | 0.947513 |
result = []
with open(os.path.join(self.__path(), os.path.basename(file_name)),
'rt') as csvfile:
headers_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for type_row in headers_reader:
for t in type_row:
r... | def read_csv_file(self, file_name) | Parses a CSV file into a list.
:param file_name: name of the CSV file
:return: a list with the file's contents | 3.355783 | 3.48913 | 0.961782 |
with open(os.path.join(self.__path(), os.path.basename(file_name)),
'rt') as yamlfile:
return yaml.load(yamlfile) | 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 | 3.824269 | 4.262453 | 0.897199 |
if file_id not in self._file_values:
file_contents = 'cwr_%s.csv' % file_id
self._file_values[file_id] = self._reader.read_csv_file(
file_contents)
return self._file_values[file_id] | 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 | 4.261314 | 4.506351 | 0.945624 |
field = basic.lookup(values, name='Record Type (one of %s)' % values)
return field.setResultsName('record_type') | 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 this field as optional, it is expected... | 16.785067 | 19.0285 | 0.882101 |
field = record_type(required_type)
field += factory.get_rule('transaction_sequence_n')
field += factory.get_rule('record_sequence_n')
# field.leaveWhitespace()
return field | 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 | 10.543893 | 12.844389 | 0.820895 |
if self.name in entity:
return entity
for key, value in entity.items():
if isinstance(value, dict):
if self.name in value:
return value
raise KeyError("The field %s (%s) not found in %s" % (self.name, self._rule['type'], entity... | def expand_entity(self, entity) | Search and return entity or sub entity that contain value of this field.
:param entity:
:return: entity
:raise KeyError | 3.857455 | 3.57229 | 1.079827 |
entity = self.expand_entity(entity)
value = entity[self.name]
result = self.format(value)
return result | def encode(self, entity) | Encode this
:param entity:
:return: cwr string | 6.22938 | 7.451373 | 0.836004 |
with open(os.path.join(self.__path(), os.path.basename(file_name)),
'rt') as file_config:
return self._parser.parseString(file_config.read()) | 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 | 4.989989 | 5.318896 | 0.938163 |
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file(
self._file_defaults)
return self._cwr_defaults | 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 | 4.174638 | 4.340535 | 0.96178 |
if file_id not in self._field_configs:
self._field_configs[file_id] = self._reader.read_yaml_file(
'field_config_%s.yml' % file_id)
return self._field_configs[file_id] | 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 | 2.599078 | 2.902703 | 0.895399 |
if file_id not in self._group_configs:
self._group_configs[file_id] = self._reader.read_config_file(
'group_config_%s.cml' % file_id)
return self._group_configs[file_id] | 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 | 3.056958 | 3.546076 | 0.862068 |
if file_id not in self._record_configs:
self._record_configs[file_id] = self._reader.read_config_file(
'record_config_%s.cml' % file_id)
return self._record_configs[file_id] | 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 | 3.108367 | 3.594222 | 0.864824 |
if file_id not in self._transaction_configs:
self._transaction_configs[file_id] = self._reader.read_config_file(
'transaction_config_%s.cml' % file_id)
return self._transaction_configs[file_id] | 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 | 3.054524 | 3.520098 | 0.867738 |
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file(
'acknowledge_config_%s.yml' % file_id)
return self._cwr_defaults | def load_acknowledge_config(self, file_id) | Loads the CWR acknowledge config
:return: the values matrix | 5.06921 | 4.529568 | 1.119138 |
self.print_usage(sys.stderr)
args = {'prog': self.prog, 'message': message}
self._print_message(
_('%(prog)s: error: %(message)s\n') % args, sys.stderr) | def soft_error(self, message) | Same as error, without the dying in a fire part. | 4.03499 | 3.817714 | 1.056913 |
factory = default_filename_grammar_factory()
grammar_old = factory.get_rule('filename_old')
grammar_new = factory.get_rule('filename_new')
return FileNameDecoder(grammar_old, grammar_new) | 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 | 5.40159 | 5.021578 | 1.075676 |
file_name = self._filename_decoder.decode(data['filename'])
file_data = data['contents']
i = 0
max_size = len(file_data)
while file_data[i:i + 1] != 'H' and i < max_size:
i += 1
if i > 0:
data['contents'] = file_data[i:]
transmis... | 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 instance | 4.165061 | 3.631141 | 1.147039 |
try:
file_tag = self._filename_decoder_new.decode(file_name)
except:
try:
file_tag = self._filename_decoder_old.decode(file_name)
except:
file_tag = FileTag(0, 0, '', '', '')
return file_tag | 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 FileTag instance | 3.427446 | 2.698671 | 1.27005 |
def cleanup():
logger.removeHandler(handler)
logger.level = old_level
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
old_level = logger.level
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter(
u'%(asc... | def enable_pretty_logging(logger='calmjs', level=logging.DEBUG, stream=None) | Shorthand to enable pretty logging | 2.171571 | 2.170858 | 1.000328 |
keys = _PLATFORM_ENV_KEYS.get(sys.platform, [])
if 'PATH' not in keys:
# this MUST be available due to Node.js (and others really)
# needing something to look for binary locations when it shells
# out to other binaries.
keys.append('PATH')
results = {
key: os.en... | 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. | 8.251382 | 7.473679 | 1.104059 |
as_bytes = isinstance(stdin, bytes)
source = stdin if as_bytes else stdin.encode(locale)
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
stdout, stderr = p.communicate(source)
if as_bytes:
return stdout, stderr
return (stdout.decode(locale), stderr.decode(locale)) | 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. | 2.51019 | 2.423724 | 1.035675 |
msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno)
raise OSError(_errno, msg) | 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. | 4.559443 | 4.710526 | 0.967927 |
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('PATH', defpath)
if not path:
return None
paths = path.split(pathsep)
if sys.platform == 'win32':
# oh boy
if curdi... | 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. | 2.09077 | 2.10992 | 0.990924 |
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):
logger.error(
"registry '%s' for '%s' is reserved for p... | def _init(self) | Turn the records into actual usable keys. | 2.639821 | 2.581736 | 1.022498 |
result = [
(key, base[key], fresh[key])
for key in set(base.keys()) & set(fresh.keys())
if base[key] != fresh[key]
]
base.update(fresh)
return result | 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). | 2.677695 | 2.224461 | 1.20375 |
registry = spec.get(CALMJS_LOADERPLUGIN_REGISTRY)
if isinstance(registry, BaseLoaderPluginRegistry):
logger.debug(
"loaderplugin registry '%s' already assigned to spec",
registry.registry_name)
return registry
elif not registry:
# resolving registry
... | 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. | 3.492367 | 3.155136 | 1.106883 |
default = dict_setget_dict(spec, sourcepath_map_key)
registry = spec_update_loaderplugin_registry(spec)
# it is more loaderplugin_sourcepath_maps
plugins = dict_setget_dict(spec, loaderplugin_sourcepath_map_key)
for modname, sourcepath in sourcepath_map.items():
parts = modname.split... | 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)
and split out the keys that does not contain loaderplugin syntax and
assign it to the spec under sourcepath_key.
For the parts with loader plugin syntax (i.e. modnames (keys)... | 4.634335 | 4.740589 | 0.977586 |
# ensure the registry is applied to the spec
registry = spec_update_loaderplugin_registry(
spec, default=toolchain.loaderplugin_registry)
# this one is named like so for the compile entry method
plugin_sourcepath = dict_setget_dict(
spec, loaderplugin_read_key + '_sourcepath')
... | 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_loaderplugins``) loaderplugin
sourcepath mappings back into one that is usable with the standard
``toolchain_spec_compile_entries`` function.
Arguments:
toolchain
The toolchain
spec
... | 6.405657 | 6.131167 | 1.04477 |
processor = getattr(toolchain, 'compile_%s_entry' % process_name)
modpath_logger = (
partial(overwrite_log, toolchain.modpath_suffix)
if callable(overwrite_log) else None)
targetpath_logger = (
partial(overwrite_log, toolchain.targetpath_suffix)
if callable(overwrite_lo... | 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
flow is to deferr the actual processing to the toolchain method
`compile_{process_name}_entry` for each entry in... | 3.683713 | 2.836891 | 1.298504 |
# Contains a mapping of the module name to the compiled file's
# relative path starting from the base build_dir.
all_modpaths = {}
all_targets = {}
# List of exported module names, should be equal to all keys of
# the compiled and bundled sources.
all_export_module_names = []
def ... | def process_compile_entries(
processor, spec, entries, modpath_logger=None, targetpath_logger=None) | The generalized raw spec entry process invocation loop. | 4.450939 | 4.563176 | 0.975404 |
self.update({k: other[k] for k in selected}) | def update_selected(self, other, selected) | Like update, however a list of selected keys must be provided. | 8.845935 | 4.624315 | 1.912918 |
if frame is None:
logger.debug(
'currentframe() returned None; frame protection disabled')
return
f_back = frame.f_back
while f_back:
if f_back.f_code is self.handle.__code__:
raise RuntimeError(
"... | 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. | 4.168444 | 4.165228 | 1.000772 |
if name is None:
return
advice = (f, a, kw)
debug = self.get(DEBUG)
frame = currentframe()
if frame is None:
logger.debug('currentframe() failed to return frame')
else:
if name in self._called:
self.__advice_... | 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
keyword arguments to f when it's invoked. | 4.592796 | 4.826264 | 0.951626 |
if name in self._called:
logger.warning(
"advice group '%s' has been called for this spec %r",
name, self,
)
# only now ensure checking
self.__advice_stack_frame_protection(currentframe())
else:
self._c... | 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 this system should make it clear that they will... | 5.344102 | 5.071599 | 1.053731 |
if key not in spec:
# do nothing for now
return
if not spec[key]:
logger.warning(
"cannot resolve realpath of '%s' as it is not defined", key)
return
check = realpath(join(spec.get(WORKING_DIR, ''), spec[key]))
i... | def realpath(self, spec, key) | Resolve and update the path key in the spec with its realpath,
based on the working directory. | 4.789712 | 3.930644 | 1.218557 |
self.compile_prefix = 'compile_'
self.sourcepath_suffix = '_sourcepath'
self.modpath_suffix = '_modpaths'
self.targetpath_suffix = '_targetpaths' | 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. | 5.885718 | 2.695255 | 2.183733 |
if not realpath(target).startswith(spec[BUILD_DIR]):
raise ValueError('build_target %s is outside build_dir' % target) | def _validate_build_target(self, spec, target) | Essentially validate that the target is inside the build_dir. | 8.666197 | 5.271211 | 1.644062 |
if not isinstance(self.transpiler, BaseUnparser):
_deprecation_warning(
'transpiler callable assigned to %r must be an instance of '
'calmjs.parse.unparsers.base.BaseUnparser by calmjs-4.0.0; '
'if the original transpile behavior is to be ret... | 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. | 5.402568 | 5.572363 | 0.969529 |
opener = self.opener
bd_target = self._generate_transpile_target(spec, target)
logger.info('Transpiling %s to %s', source, bd_target)
with opener(source, 'r') as reader, opener(bd_target, 'w') as _writer:
writer = SourceWriter(_writer)
self.transpiler(sp... | def simple_transpile_modname_source_target(
self, spec, modname, source, target) | The original simple transpile method called by compile_transpile
on each target. | 3.745764 | 3.794452 | 0.987168 |
modname, source, target, modpath = entry
transpiled_modpath = {modname: modpath}
transpiled_target = {modname: target}
export_module_name = [modname]
self.transpile_modname_source_target(spec, modname, source, target)
return transpiled_modpath, transpiled_target... | 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. | 4.519926 | 4.463543 | 1.012632 |
modname, source, target, modpath = entry
bundled_modpath = {modname: modpath}
bundled_target = {modname: target}
export_module_name = []
if isfile(source):
export_module_name.append(modname)
copy_target = join(spec[BUILD_DIR], target)
... | 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. | 3.300812 | 3.141281 | 1.050785 |
modname, source, target, modpath = entry
handler = spec[CALMJS_LOADERPLUGIN_REGISTRY].get(modname)
if handler:
return handler(self, spec, modname, source, target, modpath)
logger.warning(
"no loaderplugin handler found for plugin entry '%s'", modname)
... | 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 resolution of the
loader plugin handlers must be available in t... | 7.826668 | 5.03257 | 1.555203 |
loaderplugin_registry = spec.get(CALMJS_LOADERPLUGIN_REGISTRY)
if '!' in modname and loaderplugin_registry:
handler = loaderplugin_registry.get(modname)
if handler:
return handler.modname_source_to_target(
self, spec, modname, source)... | 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 separators (i.e. '/' or any other) into
a system or OS specific form (e.g.... | 4.3466 | 3.23916 | 1.341891 |
return self.modname_source_target_to_modpath(
spec, modname, source, target) | 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 written to the output file
for linkage by tools. Some other tools may desire the target to
be returned instead, or const... | 3.012438 | 3.151373 | 0.955913 |
for modname_source in d.items():
try:
modname = self.modname_source_to_modname(spec, *modname_source)
source = self.modname_source_to_source(spec, *modname_source)
target = self.modname_source_to_target(spec, *modname_source)
... | 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
calmjs.toolchain, but in brief:
modname
The Java... | 3.780334 | 3.628501 | 1.041845 |
spec[EXPORT_MODULE_NAMES] = export_module_names = spec.get(
EXPORT_MODULE_NAMES, [])
if not isinstance(export_module_names, list):
raise TypeError(
"spec provided a '%s' but it is not of type list "
"(got %r instead)" % (EXPORT_MODULE_NAM... | 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. | 3.836606 | 3.828797 | 1.00204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.