code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.prepare(spec)
self.compile(spec)
self.assemble(spec)
self.link(spec)
self.finalize(spec) | def _calf(self, spec) | The main call, assuming the base spec is prepared.
Also, no advices will be triggered. | 4.488615 | 3.234146 | 1.387883 |
if not isinstance(spec, Spec):
raise TypeError('spec must be of type Spec')
if not spec.get(BUILD_DIR):
tempdir = realpath(mkdtemp())
spec.advise(CLEANUP, shutil.rmtree, tempdir)
build_dir = join(tempdir, 'build')
mkdir(build_dir)
... | 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. | 6.03037 | 5.922144 | 1.018275 |
return self.simple_transpile_modname_source_target(
spec, modname, source, target) | def transpile_modname_source_target(self, spec, modname, source, target) | Calls the original version. | 4.750946 | 4.227119 | 1.12392 |
try:
prog = _get_exec_binary(bin_path, kw)
version_str = version_expr.search(
check_output([prog, version_flag], **kw).decode(locale)
).groups()[0]
except OSError:
logger.warning("failed to execute '%s'", bin_path)
return None
except Exception:
... | def get_bin_version_str(bin_path, version_flag='-v', kw={}) | Get the version string through the binary. | 3.427352 | 3.444596 | 0.994994 |
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 get_bin_version(bin_path, version_flag='-v', kw={}) | Get the version string through the binary and return a tuple of
integers. | 2.488191 | 2.404088 | 1.034983 |
return self._exec(self.node_bin, source, args=args, env=env) | def node(self, source, args=(), env={}) | Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale. | 6.719752 | 6.634012 | 1.012924 |
inst = cls()
if not inst._set_env_path_with_node_modules():
import warnings
msg = (
"Unable to locate the '%(binary)s' binary or runtime; default "
"module level functions will not work. Please either provide "
"%(PATH)s a... | 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_modules or
NODE_PATH. | 7.677851 | 6.954913 | 1.103946 |
# For looking up the pkg_name to dist converter for explicit
to_dists = {
False: find_packages_requirements_dists,
True: pkg_names_to_dists,
}
# assuming string, and assume whitespaces are invalid.
pkg_names, malformed = convert_package_names(pa... | 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 functionality of ``npm view`` but mostly for showing
the dependencies. This is done as a default action.
... | 4.567309 | 4.667236 | 0.97859 |
# this will be modified in place
original_json = {}
pkgdef_json = self.pkg_manager_view(package_names, **kw)
# Now we figure out the actual file we want to work with.
pkgdef_path = self.join_cwd(self.pkgdef_filename)
existed = exists(pkgdef_path)
if e... | 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 using standard procedures, this will
emulate the functionality of ``npm init`` for the generation of
a working ``package.j... | 4.541525 | 4.031897 | 1.126399 |
if not package_names:
logger.warning(
"no package name supplied, not continuing with '%s %s'",
self.pkg_manager_bin, self.install_cmd,
)
return
result = self.pkg_manager_init(package_names, **kw)
if result is False:
... | 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 manager; this requires that this package
manager's package definition file to be properly generated
first, otherwise the process will be aborted.
... | 3.859605 | 3.699064 | 1.0434 |
# the following will call self._get_exec_binary
return self._exec(self.binary, args=args, env=env) | def run(self, args=(), env={}) | Calls the package manager with the arguments.
Returns decoded output of stdout and stderr; decoding determine
by locale. | 11.458147 | 12.28519 | 0.93268 |
binary = which(binary, path=kw.get('env', {}).get('PATH'))
if binary is None:
raise_os_error(errno.ENOENT)
return binary | 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
account for that.
The kw argument is the key... | 5.773137 | 5.699479 | 1.012924 |
logger.debug(
"registering %d entry points for registry '%s'",
len(entry_points), self.registry_name,
)
for entry_point in entry_points:
try:
logger.debug(
"registering entry point '%s' from '%s'",
... | def _init_entry_points(self, entry_points) | Default initialization loop. | 2.526323 | 2.454972 | 1.029064 |
# If provided records already exist in the module mapping list,
# it likely means that a package declared multiple keys for the
# same package namespace; while normally this does not happen,
# this default implementation make no assumptions as to whether
# or not this i... | def store_records_for_package(self, entry_point, records) | Store the records in a way that permit lookup by package | 12.518811 | 12.616469 | 0.992259 |
module = _import_module(entry_point.module_name)
self._register_entry_point_module(entry_point, module) | def register_entry_point(self, entry_point) | Register a lone entry_point
Will raise ImportError if the entry_point leads to an invalid
import. | 3.945808 | 3.747684 | 1.052866 |
records_map = self._map_entry_point_module(entry_point, module)
self.store_records_for_package(entry_point, list(records_map.keys()))
for module_name, records in records_map.items():
if module_name in self.records:
logger.info(
"module '... | def _register_entry_point_module(self, entry_point, module) | Private method that registers an entry_point with a provided
module. | 2.849238 | 3.024334 | 0.942104 |
result = {}
result.update(self.records.get(name, {}))
return result | def get_record(self, name) | Get a record by name | 6.533729 | 6.184942 | 1.056393 |
names = self.package_module_map.get(package_name, [])
result = {}
for name in names:
result.update(self.get_record(name))
return result | def get_records_for_package(self, package_name) | Get all records identified by package. | 3.850909 | 3.65419 | 1.053834 |
if not registry_name.endswith(suffix):
raise ValueError(
"child module registry name defined with invalid suffix "
"('%s' does not end with '%s')" % (registry_name, suffix))
return registry_name[:-len(suffix)] | 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. | 4.506307 | 3.940649 | 1.143544 |
return set().union(self.records.get(name, set())) | 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. | 12.742042 | 9.828283 | 1.296467 |
result = []
result.extend(self.package_module_map.get(package_name))
return result | def get_records_for_package(self, package_name) | Get all records identified by package. | 6.498025 | 6.014381 | 1.080415 |
if self.binary is None:
return None
return which(self.binary, path=self.env_path) | def which(self) | Figure out which binary this will execute.
Returns None if the binary is not found. | 8.726478 | 5.455514 | 1.59957 |
paths = []
# First do the working dir.
local_node_path = self.join_cwd(NODE_MODULES)
if isdir(local_node_path):
paths.append(local_node_path)
# do the NODE_PATH environment variable last, as Node.js seem to
# have these resolving just before the gl... | 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 list of directories that contain a 'node_modules'
di... | 6.929668 | 6.938538 | 0.998722 |
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 attempt to locate '%s' binary from "
"%s%s%s%s%s, located through the working d... | def which_with_node_modules(self) | Which with node_path and node_modules | 4.321901 | 4.196555 | 1.029869 |
modcls_name = ':'.join((
self.__class__.__module__, self.__class__.__name__))
if self.binary is None:
raise ValueError(
"binary undefined for '%s' instance" % modcls_name)
logger.debug(
"locating '%s' node binary for %s instance..."... | 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. | 5.330082 | 4.991405 | 1.067852 |
call_kw = self._gen_call_kws(**env)
call_args = [self._get_exec_binary(call_kw)]
call_args.extend(args)
return fork_exec(call_args, stdin, **call_kw) | 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 locale this module was imported in. | 5.856956 | 6.391219 | 0.916407 |
json.dump(
blob, stream, indent=self.indent, sort_keys=True,
separators=self.separators,
) | def dump(self, blob, stream) | Call json.dump with the attributes of this instance as
arguments. | 4.463464 | 3.784487 | 1.17941 |
return json.dumps(
blob, indent=self.indent, sort_keys=True,
separators=self.separators,
) | def dumps(self, blob) | Call json.dumps with the attributes of this instance as
arguments. | 4.831289 | 3.871692 | 1.24785 |
if self.working_dir:
logger.debug(
"'%s' instance 'working_dir' set to '%s' for join_cwd",
type(self).__name__, self.working_dir,
)
cwd = self.working_dir
else:
cwd = getcwd()
logger.debug(
... | 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. | 3.007966 | 2.897343 | 1.038181 |
stripped_modname = self.unwrap(modname)
chained = (
self.registry.get_record(stripped_modname)
if '!' in stripped_modname else None)
if chained:
# ensure the stripped_modname is provided as by default the
# handler will only deal with its... | 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)
to resolve the copy target, which must be a path relative to the
spec[WORKING_DIR].
If... | 6.990499 | 5.832646 | 1.198513 |
globs = value.split('!', 1)
if globs[0].split('?', 1)[0] == self.name:
return globs[-1]
else:
return value | 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
this default implementation is not going... | 5.886749 | 4.868196 | 1.209226 |
try:
result = obj.isoformat()
except AttributeError:
raise TypeError("Unserializable object {} of type {}".format(obj,
type(obj)))
return result | 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 | 4.247205 | 5.603791 | 0.757916 |
encoded = self._dict_encoder.encode(entity)
if sys.version_info[0] == 2:
result = json.dumps(encoded, ensure_ascii=False,
default=_iso_handler, encoding='latin1')
else:
# For Python 3
result = json.dumps(encoded, ensur... | 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 | 3.222776 | 3.594394 | 0.896612 |
if name is None:
name = 'IPI Base Number Field'
field = pp.Regex('I-[0-9]{9}-[0-9]')
# Name
field.setName(name)
field_num = basic.numeric(13)
field_num.setName(name)
field = field | field_num
# White spaces are not removed
field.leaveWhitespace()
return field.... | 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-7.
:param name: name for the field
... | 7.739111 | 6.20624 | 1.246989 |
if name is None:
name = 'IPI Name Number Field'
field = basic.numeric(11)
field.setName(name)
return field.setResultsName('ipi_name_n') | 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 | 9.966264 | 7.505728 | 1.327821 |
if name is None:
name = 'ISWC Field'
# T followed by 10 numbers
field = pp.Regex('T[0-9]{10}')
# Name
field.setName(name)
# White spaces are not removed
field.leaveWhitespace()
return field.setResultsName('iswc') | 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
:return: a parser for the ISWC fiel... | 8.485464 | 6.258084 | 1.35592 |
if name is None:
name = 'Percentage Field'
if columns < 3:
message = 'The values can not be lower than 3'
raise pp.ParseException(message)
field = basic.numeric_float(columns, 3)
field.addParseAction(lambda v: _assert_is_percentage(v[0], maximum))
field.setName(name... | 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 reduced, not increased.
The three first digits will be for th... | 7.226136 | 4.910419 | 1.471592 |
if value < 0 or value > maximum:
message = 'The value on a percentage field should be between 0 and %s' \
% maximum
raise pp.ParseException(message) | 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 | 6.959542 | 7.801686 | 0.892056 |
if name is None:
name = 'EAN 13 Field'
field = basic.numeric(13)
field = field.setName(name)
return field.setResultsName('ean_13') | 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 | 6.843865 | 4.870747 | 1.405096 |
if name is None:
name = 'ISRC Field'
field = _isrc_short(name) | _isrc_long(name)
field.setName(name)
return field.setResultsName('isrc') | 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 | 6.758729 | 5.254559 | 1.28626 |
config = CWRTables()
if name is None:
name = 'ISRC Field'
country = config.get_data('isrc_country_code')
# registrant = basic.alphanum(3)
# year = pp.Regex('[0-9]{2}')
# work_id = pp.Regex('[0-9]{5}')
country_regex = ''
for c in country:
if len(country_regex) > 0... | 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:
CCXXXYYNNNNN
Where each code ... | 4.360657 | 3.425716 | 1.272918 |
if name is None:
name = 'V-ISAN Field'
field = pp.Regex('[0-9]{25}')
field.setName(name)
return field.setResultsName('visan') | 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 | 10.782907 | 6.332548 | 1.702775 |
if name is None:
name = 'AVI Field'
society_code = basic.numeric(3)
society_code = society_code.setName('Society Code') \
.setResultsName('society_code')
av_number = basic.alphanum(15, extended=True, isLast=True)
field_empty = pp.Regex('[ ]{15}')
field_empty.setParseActio... | 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 | 4.953825 | 4.296097 | 1.153099 |
if name is None:
name = 'Date and Time Field'
date = basic.date('Date')
time = basic.time('Time')
date = date.setResultsName('date')
time = time.setResultsName('time')
field = pp.Group(date + time)
field.setParseAction(lambda d: _combine_date_time(d[0]))
field.setName(n... | 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 and Time field | 4.059057 | 3.85237 | 1.053652 |
field = basic.lookup(values, name)
field.addParseAction(lambda l: int(l[0]))
return field | 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 | 9.854637 | 10.573716 | 0.931994 |
tree = parse(text)
return list(filter_function_argument(tree, f_name, f_argn, f_argt)) | 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 from calmjs.parse.asttypes;
default: calmjs.parse.asttypes.String | 3.866002 | 4.675828 | 0.826806 |
for i, child in enumerate(node.args.items[pos]):
if isinstance(child, asttypes.String):
result = to_str(child)
if ((result not in reserved_module) and (
result != define_wrapped.get(i))):
yield result | 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 module names to
be imported as represented by this given node, which must be of the
FunctionCall type. | 6.195512 | 6.905079 | 0.89724 |
if not isinstance(node.args.items[pos], asttypes.String):
return
yield to_str(node.args.items[pos]) | def yield_string_argument(node, pos) | Yield just a string argument from position of the function call. | 8.409985 | 7.77913 | 1.081096 |
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:
if condition(child):
for name in f(child):
yield name
continu... | 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. | 8.11335 | 8.600464 | 0.943362 |
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:
if condition(child):
for name in f(child):
yield name
continu... | def yield_module_imports_nodes(root, checks=import_nodes()) | Yield all nodes that provide an import | 7.954808 | 8.151124 | 0.975915 |
index = self.fasta_index
try:
handle = open(index, 'rb')
except (IOError, TypeError):
sys.stderr.write('index not found, creating it\n')
try:
self.build_fasta_index()
return
except IOError:
r... | def open_fasta_index(self) | custom type for file made w/ buildFastaIndex, fai for ones made with samtools | 5.212411 | 5.139635 | 1.01416 |
try:
divisor = int(self.sequence_index[chrom][2])
except KeyError:
self.open_fasta_index()
try:
divisor = int(self.sequence_index[chrom][2])
except KeyError:
sys.stderr.write("%s cannot be found within the fasta ind... | 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) indexing. This can be changed with the indexing keyword.
The default is for everything ... | 3.881777 | 3.902444 | 0.994704 |
children = [registry]
while isinstance(registry, BaseChildModuleRegistry):
if registry.parent in children:
# this should never normally occur under normal usage where
# classes have been properly subclassed with methods defined
# to specificiation and with stand... | 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. | 5.669732 | 5.509806 | 1.029026 |
#clean up xtandem
if not modType:
#try to figure out what it is
tmass = abs(modMass)
smass = str(tmass)
prec = len(str(tmass-int(tmass)))-2
precFormat = '%'+'0.%df'%prec
# modType = ""
# masses = config.MODIFICA... | 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, Oxidation, 15.9...)
such as: M35(o) for an oxidized methionine at residue 35 | 5.241614 | 5.347793 | 0.980145 |
try:
return pkg_resources.resource_filename(
dist.as_requirement(), join(*module_name.split('.')))
except pkg_resources.DistributionNotFound:
logger.warning(
"distribution '%s' not found, falling back to resolution using "
"module_name '%s'", dist, modul... | def resource_filename_mod_dist(module_name, dist) | Given a module name and a distribution, attempt to resolve the
actual path to the module. | 3.396733 | 3.327325 | 1.02086 |
if entry_point.dist is None:
# distribution missing is typically caused by mocked entry
# points from tests; silently falling back to basic lookup
result = pkg_resources.resource_filename(module_name, '')
else:
result = resource_filename_mod_dist(module_name, entry_point.di... | def resource_filename_mod_entry_point(module_name, entry_point) | If a given package declares a namespace and also provide submodules
nested at that namespace level, and for whatever reason that module
is needed, Python's import mechanism will not have a path associated
with that module. However, if given an entry_point, this path can
be resolved through its distribu... | 3.517431 | 3.383699 | 1.039522 |
globber_f = globber if callable(globber) else registry['globber'][globber]
modpath_f = modpath if callable(modpath) else registry['modpath'][modpath]
logger.debug(
'modgen generating file listing for module %s',
module.__name__,
)
module_frags = module.__name__.split('.')
... | def modgen(
module, entry_point,
modpath='pkg_resources', globber='root', fext=JS_EXT,
registry=_utils) | JavaScript styled module location listing generator.
Arguments:
module
The Python module to start fetching from.
entry_point
This is the original entry point that has a distribution
reference such that the resource_filename API call may be used
to locate the actual resourc... | 2.95434 | 2.757571 | 1.071356 |
def marker(f):
mark = util_type + '_'
if not f.__name__.startswith(mark):
raise TypeError(
'not registering %s to %s' % (f.__name__, util_type))
registry[util_type][f.__name__[len(mark):]] = f
return f
return marker | def register(util_type, registry=_utils) | Crude, local registration decorator for a crude local registry of
all utilities local to this module. | 3.625148 | 3.693125 | 0.981594 |
module_paths = getattr(module, '__path__', [])
if not module_paths:
logger.warning(
"module '%s' does not appear to be a namespace module or does not "
"export available paths onto the filesystem; JavaScript source "
"files cannot be extracted from this module."... | def modpath_all(module, entry_point) | Provides the raw __path__. Incompatible with PEP 302-based import
hooks and incompatible with zip_safe packages.
Deprecated. Will be removed by calmjs-4.0. | 7.506256 | 7.618684 | 0.985243 |
module_paths = modpath_all(module, entry_point)
if len(module_paths) > 1:
logger.info(
"module '%s' has multiple paths, default selecting '%s' as base.",
module.__name__, module_paths[-1],
)
return module_paths[-1:] | def modpath_last(module, entry_point) | Provides the raw __path__. Incompatible with PEP 302-based import
hooks and incompatible with zip_safe packages.
Deprecated. Will be removed by calmjs-4.0. | 4.251374 | 4.343277 | 0.97884 |
result = []
try:
path = resource_filename_mod_entry_point(module.__name__, entry_point)
except ImportError:
logger.warning("module '%s' could not be imported", module.__name__)
except Exception:
logger.warning("%r does not appear to be a valid module", module)
else:
... | def modpath_pkg_resources(module, entry_point) | Goes through pkg_resources for compliance with various PEPs.
This one accepts a module as argument. | 3.62671 | 3.600577 | 1.007258 |
modname_f = modname if callable(modname) else _utils['modname'][modname]
return {
modname_f(modname_fragments): join(base, subpath)
for modname_fragments, base, subpath in modgen(
module, entry_point=entry_point,
modpath=modpath, globber=globber,
fext=f... | def mapper(module, entry_point,
modpath='pkg_resources', globber='root', modname='es6',
fext=JS_EXT, registry=_utils) | General mapper
Loads components from the micro registry. | 4.415238 | 4.91106 | 0.89904 |
return mapper(
module, entry_point=entry_point, modpath='pkg_resources',
globber=globber, modname='python', fext=fext) | def mapper_python(module, entry_point, globber='root', fext=JS_EXT) | Default mapper using python style globber
Finds the latest path declared for the module at hand and extract
a list of importable JS modules using the es6 module import format. | 5.403334 | 7.209339 | 0.749491 |
code = str(self.id_code)
while len(code) < self._code_size:
code = '0' + code
return code | def _printable_id_code(self) | Returns the code in a printable form, filling with zeros if needed.
:return: the ID code in a printable form | 4.057272 | 3.846475 | 1.054803 |
code = super(ISWCCode, self)._printable_id_code()
code1 = code[:3]
code2 = code[3:6]
code3 = code[-3:]
return '%s.%s.%s' % (code1, code2, code3) | def _printable_id_code(self) | Returns the code in a printable form, separating it into groups of
three characters using a point between them.
:return: the ID code in a printable form | 3.563555 | 3.511239 | 1.0149 |
lines = s.splitlines(True)
for line in lines:
self.current_mapping.append(
(self.generated_col, self.index, self.row, self.col_last))
self.stream.write(line)
if line[-1] in '\r\n':
# start again.
self._newline(... | def write(self, s) | Standard write, for standard sources part of the original file. | 4.735377 | 4.526773 | 1.046082 |
lines = s.splitlines(True)
for line in lines:
if line[-1] not in '\r\n':
if not self.warn:
logger.warning(
'partial line discard UNSUPPORTED; source map '
'generated will not match at the column lev... | def discard(self, s) | Discard from original file. | 9.235704 | 8.520658 | 1.083919 |
lines = s.splitlines(True)
for line in lines:
self.stream.write(line)
if line[-1] in '\r\n':
self._newline()
else:
# this is the last line
self.generated_col += len(line) | def write_padding(self, s) | Write string that are not part of the original file. | 5.009914 | 4.790385 | 1.045827 |
locale = babel.core.Locale.parse(locale)
if format:
pattern = babel.numbers.parse_pattern(format)
else:
try:
pattern = locale.currency_formats[format_type]
except KeyError:
raise babel.numbers.UnknownCurrencyFormatError(
"%r is not a known... | def format_currency(number, currency, format, locale=babel.numbers.LC_NUMERIC,
force_frac=None, format_type='standard') | Same as ``babel.numbers.format_currency``, but has ``force_frac``
argument instead of ``currency_digits``.
If the ``force_frac`` argument is given, the argument is passed down to
``pattern.apply``. | 2.75893 | 2.771579 | 0.995436 |
print("This example prints variant character data.")
c = Cihai()
if not c.unihan.is_bootstrapped: # download and install Unihan to db
c.unihan.bootstrap(unihan_options)
c.unihan.add_plugin(
'cihai.data.unihan.dataset.UnihanVariants', namespace='variants'
)
print("## ZVar... | def run(unihan_options={}) | Wrapped so we can test in tests/test_examples.py | 7.415078 | 7.037513 | 1.05365 |
self.metadata.reflect(views=True, extend_existing=True)
self.base = automap_base(metadata=self.metadata)
self.base.prepare() | def reflect_db(self) | No-op to reflect db info.
This is available as a method so the database can be reflected
outside initialization (such bootstrapping unihan during CLI usage). | 4.451588 | 4.251655 | 1.047025 |
global Element_, AtomicString_
Element_ = element
AtomicString_ = atomicstring
s, nodes = parse_exprs(s)
remove_invisible(nodes)
nodes = map(remove_private, nodes)
return El('math', El('mstyle', *nodes)) | def parse(s, element=Element, atomicstring=lambda s: s) | Translates from ASCIIMathML (an easy to type and highly readable way to
represent math formulas) into MathML (a w3c standard directly displayable by
some web browsers).
The function `parse()` generates a tree of elements:
>>> import asciimathml
>>> asciimathml.parse('sqrt 2')
<Element math at b76fb28c>
T... | 10.181524 | 14.812449 | 0.687363 |
def nodes_to_string(n):
if isinstance(n, list):
result = '[ '
for m in map(nodes_to_string, n):
result += m
result += ' '
result += ']'
return result
else:
try:
return tostring(remove_p... | def trace_parser(p) | Decorator for tracing the parser.
Use it to decorate functions with signature:
string -> (string, nodes)
and a trace of the progress made by the parser will be printed to stderr.
Currently parse_exprs(), parse_expr() and parse_m() have the right signature. | 3.073141 | 2.903442 | 1.058447 |
'''
prob is a ndarray representing a probability distribution.
index is a number between 0 and and the number of symbols ( len(prob)-1 )
return the probability distribution if the element at 'index' was no longer available
'''
if type(dist) is not Distribution:
raise TypeError("remove_sy... | def remove_symbol_from_dist(dist, index) | prob is a ndarray representing a probability distribution.
index is a number between 0 and and the number of symbols ( len(prob)-1 )
return the probability distribution if the element at 'index' was no longer available | 6.347323 | 2.486911 | 2.552292 |
'''
change every response in x that matches 'index' by randomly sampling from prob
'''
#pdb.set_trace()
N = (x==index).sum()
#x[x==index]=9
x[x==index] = dist.sample(N) | def change_response(x, prob, index) | change every response in x that matches 'index' by randomly sampling from prob | 9.449602 | 5.332674 | 1.772019 |
#pdb.set_trace()
N=4
m = 100
x = np.zeros(m*(2**N))
y = np.zeros(m*(2**N))
for i in range(1, 2**N):
x[i*m:(i+1)*m] = i
y[i*m:(i+1)*m] = i + np.random.randint(0, 2*i, m)
diff = differentiate_mi(x,y)
return x, y, diff | def toy_example() | Make a toy example where x is uniformly distributed with N bits and y
follows x but with symbol dependent noise.
x=0 -> y=0
x=1 -> y=1 + e
x=2 -> y=2 + 2*e
...
x=n -> y=n + n*e
where by n*e I am saying that the noise grows | 3.345296 | 3.334421 | 1.003261 |
'''
for each symbol in x, change x such that there are no more of such symbols
(replacing by a random distribution with the same proba of all other symbols)
and compute mi(new_x, y)
'''
#pdb.set_trace()
dist = Distribution(discrete.symbols_to_prob(x))
diff = np.zeros(len(dist.prob))
... | def differentiate_mi(x, y) | for each symbol in x, change x such that there are no more of such symbols
(replacing by a random distribution with the same proba of all other symbols)
and compute mi(new_x, y) | 7.870546 | 3.599949 | 2.186294 |
'''
generate a random number in [0,1) and return the index into self.prob
such that self.prob[index] <= random_number but self.prob[index+1] > random_number
implementation note: the problem is identical to finding the index into self.cumsum
where the random number should be inse... | def sample(self, *args) | generate a random number in [0,1) and return the index into self.prob
such that self.prob[index] <= random_number but self.prob[index+1] > random_number
implementation note: the problem is identical to finding the index into self.cumsum
where the random number should be inserted to keep the arr... | 5.990335 | 1.300387 | 4.606578 |
reset = Style.RESET_ALL
levelname = [
LEVEL_COLORS.get(record.levelname),
Style.BRIGHT,
'(%(levelname)s)',
Style.RESET_ALL,
' ',
]
asctime = [
'[',
Fore.BLACK,
Style.DIM,
Style.BRIGHT,
'%(asctime)s',
Fore.RESET... | def default_log_template(self, record) | Return the prefix for the log message. Template for Formatter.
:param: record: :py:class:`logging.LogRecord` object. this is passed in
from inside the :py:meth:`logging.Formatter.format` record. | 2.855745 | 2.847292 | 1.002969 |
if base is None:
return additional
if additional is None:
return base
if not (
isinstance(base, collections.Mapping)
and isinstance(additional, collections.Mapping)
):
return additional
merged = base
for key, value in additional.items():
if... | def merge_dict(base, additional) | Combine two dictionary-like objects.
Notes
-----
Code from https://github.com/pypa/warehouse
Copyright 2013 Donald Stufft
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at... | 1.868028 | 1.940835 | 0.962487 |
context = {
'user_cache_dir': dirs.user_cache_dir,
'user_config_dir': dirs.user_config_dir,
'user_data_dir': dirs.user_data_dir,
'user_log_dir': dirs.user_log_dir,
'site_config_dir': dirs.site_config_dir,
'site_data_dir': dirs.site_data_dir,
}
for k, v i... | def expand_config(d, dirs) | Expand configuration XDG variables, environmental variables, and tildes.
Parameters
----------
d : dict
config information
dirs : appdirs.AppDirs
XDG application mapping
Notes
-----
*Environmentable variables* are expanded via :py:func:`os.path.expandvars`.
So ``${PWD}`... | 1.791067 | 1.685865 | 1.062402 |
options = merge_dict(UNIHAN_ETL_DEFAULT_OPTIONS.copy(), options)
p = unihan.Packager(options)
p.download()
data = p.export()
table = create_unihan_table(UNIHAN_FIELDS, metadata)
metadata.create_all()
metadata.bind.execute(table.insert(), data) | def bootstrap_unihan(metadata, options={}) | Download, extract and import unihan to database. | 6.099801 | 5.120863 | 1.191166 |
fields = UNIHAN_FIELDS + DEFAULT_COLUMNS
if TABLE_NAME in metadata.tables.keys():
table = metadata.tables[TABLE_NAME]
if set(fields) == set(c.name for c in table.columns):
return True
else:
return False
else:
return False | def is_bootstrapped(metadata) | Return True if cihai is correctly bootstrapped. | 4.446161 | 4.365118 | 1.018566 |
if TABLE_NAME not in metadata.tables:
table = Table(TABLE_NAME, metadata)
table.append_column(Column('char', String(12), primary_key=True))
table.append_column(Column('ucn', String(12), primary_key=True))
for column_name in columns:
col = Column(column_name, Strin... | def create_unihan_table(columns, metadata) | Create table and return :class:`sqlalchemy.Table`.
Parameters
----------
columns : list
columns for table, e.g. ``['kDefinition', 'kCantonese']``
metadata : :class:`sqlalchemy.schema.MetaData`
Instance of sqlalchemy metadata
Returns
-------
:class:`sqlalchemy.schema.Table`... | 2.443287 | 2.686723 | 0.909393 |
if isinstance(pk, str):
pk = unhexlify(pk.encode())
assert len(pk) == 32, 'PK is 32bytes {}'.format(len(pk))
k = keccak_256(pk).digest()
ripe = RIPEMD160.new(k).digest()
if prefix is None:
body = (b"\x68" if main_net else b"\x98") + ripe
else:
assert isinstance(prefi... | def get_address(pk, main_net=True, prefix=None) | compute the nem-py address from the public one | 3.088729 | 3.015156 | 1.024401 |
Unihan = self.sql.base.classes.Unihan
return self.sql.session.query(Unihan).filter_by(char=char) | def lookup_char(self, char) | Return character information from datasets.
Parameters
----------
char : str
character / string to lookup
Returns
-------
:class:`sqlalchemy.orm.query.Query` :
list of matches | 8.275445 | 10.209825 | 0.810537 |
if isinstance(hints, string_types):
hints = [hints]
Unihan = self.sql.base.classes.Unihan
columns = Unihan.__table__.columns
return self.sql.session.query(Unihan).filter(
or_(*[column.contains(hint) for column in columns for hint in hints])
) | def reverse_char(self, hints) | Return QuerySet of objects from SQLAlchemy of results.
Parameters
----------
hints: list of str
strings to lookup
Returns
-------
:class:`sqlalchemy.orm.query.Query` :
reverse matches | 5.82436 | 5.352511 | 1.088155 |
Unihan = self.sql.base.classes.Unihan
query = self.sql.session.query(Unihan)
for field in fields:
query = query.filter(Column(field).isnot(None))
return query | def with_fields(self, *fields) | Returns list of characters with information for certain fields.
Parameters
----------
*fields : list of str
fields for which information should be available
Returns
-------
:class:`sqlalchemy.orm.query.Query` :
list of matches | 5.244137 | 5.888269 | 0.890608 |
'''
compute and return the mutual information between x and y
inputs:
-------
x, y: numpy arrays of shape samples x dimension
method: 'nearest-neighbors', 'gaussian', or 'bin'
units: 'bits' or 'nats'
output:
-------
mi: float
Notes:
-... | def mi(x, y, bins_x=None, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits') | compute and return the mutual information between x and y
inputs:
-------
x, y: numpy arrays of shape samples x dimension
method: 'nearest-neighbors', 'gaussian', or 'bin'
units: 'bits' or 'nats'
output:
-------
mi: float
Notes:
------
... | 3.938447 | 2.240978 | 1.757468 |
'''
compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats'
'''
HXY = entropy(data=np.concatenate([x, y], axis=1), bins=bins_xy, method=method, units=units)
HY = ... | def cond_entropy(x, y, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits') | compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats' | 3.663458 | 1.969022 | 1.860547 |
'''
given a probability distribution (prob) or an interable of symbols (data) compute and
return its entropy
inputs:
------
data: iterable of symbols
prob: iterable with probabilities
tol: if prob is given, 'entropy' checks that the sum is about 1.
... | def entropy(data=None, prob=None, tol=1e-5) | given a probability distribution (prob) or an interable of symbols (data) compute and
return its entropy
inputs:
------
data: iterable of symbols
prob: iterable with probabilities
tol: if prob is given, 'entropy' checks that the sum is about 1.
... | 4.115068 | 2.521936 | 1.63171 |
'''
Return a dict mapping symbols to probability.
input:
-----
symbols: iterable of hashable items
works well if symbols is a zip of iterables
'''
myCounter = Counter(symbols)
N = float(len(list(symbols))) # symbols might be a zip object in python 3
... | def symbols_to_prob(symbols) | Return a dict mapping symbols to probability.
input:
-----
symbols: iterable of hashable items
works well if symbols is a zip of iterables | 12.323312 | 3.920492 | 3.143307 |
'''
Combine different symbols into a 'super'-symbol
args can be an iterable of iterables that support hashing
see example for 2D ndarray input
usage:
1) combine two symbols, each a number into just one symbol
x = numpy.random.randint(0,4,1000)
y = numpy.random.randint(0,2,... | def combine_symbols(*args) | Combine different symbols into a 'super'-symbol
args can be an iterable of iterables that support hashing
see example for 2D ndarray input
usage:
1) combine two symbols, each a number into just one symbol
x = numpy.random.randint(0,4,1000)
y = numpy.random.randint(0,2,1000)
... | 6.57888 | 1.301277 | 5.055711 |
'''
compute and return the mutual information between x and y
inputs:
-------
x, y: iterables of hashable items
output:
-------
mi: float
Notes:
------
if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try
info[p] = _inf... | def mi(x, y) | compute and return the mutual information between x and y
inputs:
-------
x, y: iterables of hashable items
output:
-------
mi: float
Notes:
------
if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try
info[p] = _info.mi(x, info... | 5.143528 | 2.604683 | 1.974723 |
'''
compute and return the mutual information between x and y given z, I(x, y | z)
inputs:
-------
x, y, z: iterables with discrete symbols
output:
-------
mi: float
implementation notes:
---------------------
I(x, y | z) = H(x | z) - H(x | y, z)
... | def cond_mi(x, y, z) | compute and return the mutual information between x and y given z, I(x, y | z)
inputs:
-------
x, y, z: iterables with discrete symbols
output:
-------
mi: float
implementation notes:
---------------------
I(x, y | z) = H(x | z) - H(x | y, z)
... | 3.506709 | 2.028249 | 1.728934 |
'''
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
output:
-------
... | def mi_chain_rule(X, y) | Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
output:
-------
ndarray:... | 5.441117 | 1.881401 | 2.892056 |
'''
Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same.
'''
assert(P.keys()==Q.keys())
distance = 0
for k in P.keys():
distance += P[k] * log(P[k]/Q[k])
ret... | def KL_divergence(P,Q) | Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same. | 4.322388 | 2.207257 | 1.958262 |
'''
bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full
range of the signal. If they are not None, everything above maxX gets assigned to
binsN-1 and everything below minX gets assigned to 0, this is effectively the same
as clipping x before passing it to 'bin'
inpu... | def bin(x, bins, maxX=None, minX=None) | bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full
range of the signal. If they are not None, everything above maxX gets assigned to
binsN-1 and everything below minX gets assigned to 0, this is effectively the same
as clipping x before passing it to 'bin'
input:
-----... | 5.2641 | 1.558848 | 3.376916 |
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except Exception:
return None
... | def linkcode_resolve(domain, info): # NOQA: C901
if domain != 'py' | Determine the URL corresponding to Python object
Notes
-----
From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa
on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt | 2.273668 | 2.255746 | 1.007945 |
# Adapted from curve25519_athlon.c in djb's Curve25519.
z = qdiv(z)
z2 = z * z % PRIME # 2
z9 = pow2(z2, 2) * z % PRIME # 9
z11 = z9 * z2 % PRIME # 11
z2_5_0 = (z11*z11) % PRIME * z9 % PRIME # 31 == 2^5 - 2^0
z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % PRIME # 2^10 - 2^0
z2_20_0 = pow... | def inv(z) | $= z^{-1} \mod q$, for z != 0 | 2.035751 | 2.027519 | 1.00406 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.