repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.realpath
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( "cannot resolve realpath of '%s' as it is not defined", key) return check = realpath(join(spec.get(WORKING_DIR, ''), spec[key])) if check != spec[key]: spec[key] = check logger.warning( "realpath of '%s' resolved to '%s', spec is updated", key, check ) return check
python
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( "cannot resolve realpath of '%s' as it is not defined", key) return check = realpath(join(spec.get(WORKING_DIR, ''), spec[key])) if check != spec[key]: spec[key] = check logger.warning( "realpath of '%s' resolved to '%s', spec is updated", key, check ) return check
[ "def", "realpath", "(", "self", ",", "spec", ",", "key", ")", ":", "if", "key", "not", "in", "spec", ":", "# do nothing for now", "return", "if", "not", "spec", "[", "key", "]", ":", "logger", ".", "warning", "(", "\"cannot resolve realpath of '%s' as it is ...
Resolve and update the path key in the spec with its realpath, based on the working directory.
[ "Resolve", "and", "update", "the", "path", "key", "in", "the", "spec", "with", "its", "realpath", "based", "on", "the", "working", "directory", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L960-L982
train
45,800
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.setup_prefix_suffix
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 = 'compile_' self.sourcepath_suffix = '_sourcepath' self.modpath_suffix = '_modpaths' self.targetpath_suffix = '_targetpaths'
python
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 = 'compile_' self.sourcepath_suffix = '_sourcepath' self.modpath_suffix = '_modpaths' self.targetpath_suffix = '_targetpaths'
[ "def", "setup_prefix_suffix", "(", "self", ")", ":", "self", ".", "compile_prefix", "=", "'compile_'", "self", ".", "sourcepath_suffix", "=", "'_sourcepath'", "self", ".", "modpath_suffix", "=", "'_modpaths'", "self", ".", "targetpath_suffix", "=", "'_targetpaths'" ...
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.
[ "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",...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1002-L1013
train
45,801
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain._validate_build_target
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)
python
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", "_validate_build_target", "(", "self", ",", "spec", ",", "target", ")", ":", "if", "not", "realpath", "(", "target", ")", ".", "startswith", "(", "spec", "[", "BUILD_DIR", "]", ")", ":", "raise", "ValueError", "(", "'build_target %s is outside build_dir...
Essentially validate that the target is inside the build_dir.
[ "Essentially", "validate", "that", "the", "target", "is", "inside", "the", "build_dir", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1100-L1106
train
45,802
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.transpile_modname_source_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 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 retained, the ' 'subclass may instead override this method to call ' '`simple_transpile_modname_source_target` directly, as ' 'this fallback behavior will be removed by calmjs-4.0.0' % ( self, ) ) return self.simple_transpile_modname_source_target( spec, modname, source, target) # do the new thing here. return self._transpile_modname_source_target( spec, modname, source, target)
python
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 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 retained, the ' 'subclass may instead override this method to call ' '`simple_transpile_modname_source_target` directly, as ' 'this fallback behavior will be removed by calmjs-4.0.0' % ( self, ) ) return self.simple_transpile_modname_source_target( spec, modname, source, target) # do the new thing here. return self._transpile_modname_source_target( spec, modname, source, target)
[ "def", "transpile_modname_source_target", "(", "self", ",", "spec", ",", "modname", ",", "source", ",", "target", ")", ":", "if", "not", "isinstance", "(", "self", ".", "transpiler", ",", "BaseUnparser", ")", ":", "_deprecation_warning", "(", "'transpiler callab...
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.
[ "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", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1122-L1145
train
45,803
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.simple_transpile_modname_source_target
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) 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(spec, reader, writer) if writer.mappings and spec.get(GENERATE_SOURCE_MAP): source_map_path = bd_target + '.map' with open(source_map_path, 'w') as sm_fd: self.dump(encode_sourcemap( filename=bd_target, mappings=writer.mappings, sources=[source], ), sm_fd) # just use basename source_map_url = basename(source_map_path) _writer.write('\n//# sourceMappingURL=') _writer.write(source_map_url) _writer.write('\n')
python
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) 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(spec, reader, writer) if writer.mappings and spec.get(GENERATE_SOURCE_MAP): source_map_path = bd_target + '.map' with open(source_map_path, 'w') as sm_fd: self.dump(encode_sourcemap( filename=bd_target, mappings=writer.mappings, sources=[source], ), sm_fd) # just use basename source_map_url = basename(source_map_path) _writer.write('\n//# sourceMappingURL=') _writer.write(source_map_url) _writer.write('\n')
[ "def", "simple_transpile_modname_source_target", "(", "self", ",", "spec", ",", "modname", ",", "source", ",", "target", ")", ":", "opener", "=", "self", ".", "opener", "bd_target", "=", "self", ".", "_generate_transpile_target", "(", "spec", ",", "target", ")...
The original simple transpile method called by compile_transpile on each target.
[ "The", "original", "simple", "transpile", "method", "called", "by", "compile_transpile", "on", "each", "target", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1160-L1186
train
45,804
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.compile_transpile_entry
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 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, export_module_name
python
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 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, export_module_name
[ "def", "compile_transpile_entry", "(", "self", ",", "spec", ",", "entry", ")", ":", "modname", ",", "source", ",", "target", ",", "modpath", "=", "entry", "transpiled_modpath", "=", "{", "modname", ":", "modpath", "}", "transpiled_target", "=", "{", "modname...
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.
[ "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...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1188-L1200
train
45,805
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.compile_bundle_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: modpath} bundled_target = {modname: target} export_module_name = [] if isfile(source): export_module_name.append(modname) copy_target = join(spec[BUILD_DIR], target) if not exists(dirname(copy_target)): makedirs(dirname(copy_target)) shutil.copy(source, copy_target) elif isdir(source): copy_target = join(spec[BUILD_DIR], modname) shutil.copytree(source, copy_target) return bundled_modpath, bundled_target, export_module_name
python
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: modpath} bundled_target = {modname: target} export_module_name = [] if isfile(source): export_module_name.append(modname) copy_target = join(spec[BUILD_DIR], target) if not exists(dirname(copy_target)): makedirs(dirname(copy_target)) shutil.copy(source, copy_target) elif isdir(source): copy_target = join(spec[BUILD_DIR], modname) shutil.copytree(source, copy_target) return bundled_modpath, bundled_target, export_module_name
[ "def", "compile_bundle_entry", "(", "self", ",", "spec", ",", "entry", ")", ":", "modname", ",", "source", ",", "target", ",", "modpath", "=", "entry", "bundled_modpath", "=", "{", "modname", ":", "modpath", "}", "bundled_target", "=", "{", "modname", ":",...
Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory.
[ "Handler", "for", "each", "entry", "for", "the", "bundle", "method", "of", "the", "compile", "process", ".", "This", "copies", "the", "source", "file", "or", "directory", "into", "the", "build", "directory", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1202-L1223
train
45,806
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.compile_loaderplugin_entry
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 the spec under CALMJS_LOADERPLUGIN_REGISTRY """ 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) return {}, {}, []
python
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 the spec under CALMJS_LOADERPLUGIN_REGISTRY """ 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) return {}, {}, []
[ "def", "compile_loaderplugin_entry", "(", "self", ",", "spec", ",", "entry", ")", ":", "modname", ",", "source", ",", "target", ",", "modpath", "=", "entry", "handler", "=", "spec", "[", "CALMJS_LOADERPLUGIN_REGISTRY", "]", ".", "get", "(", "modname", ")", ...
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 the spec under CALMJS_LOADERPLUGIN_REGISTRY
[ "Generic", "loader", "plugin", "entry", "handler", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1225-L1244
train
45,807
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.modname_source_target_modnamesource_to_modpath
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 construct some other string that is more suitable for the tool that will do the assemble and link step. The modname and source argument provided to aid pedantic tools, but really though this provides more consistency to method signatures. Same as `self.modname_source_target_to_modpath`, but includes the original raw key-value as a 2-tuple. Called by generator method `_gen_modname_source_target_modpath`. """ return self.modname_source_target_to_modpath( spec, modname, source, target)
python
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 construct some other string that is more suitable for the tool that will do the assemble and link step. The modname and source argument provided to aid pedantic tools, but really though this provides more consistency to method signatures. Same as `self.modname_source_target_to_modpath`, but includes the original raw key-value as a 2-tuple. Called by generator method `_gen_modname_source_target_modpath`. """ 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", ")", ":", "return", "self", ".", "modname_source_target_to_modpath", "(", "spec", ",", "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 construct some other string that is more suitable for the tool that will do the assemble and link step. The modname and source argument provided to aid pedantic tools, but really though this provides more consistency to method signatures. Same as `self.modname_source_target_to_modpath`, but includes the original raw key-value as a 2-tuple. Called by generator method `_gen_modname_source_target_modpath`.
[ "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", ...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1341-L1362
train
45,808
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain._gen_modname_source_target_modpath
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 JavaScript module name. source Stands for sourcepath - path to some JavaScript source file. target Stands for targetpath - the target path relative to spec[BUILD_DIR] where the source file will be written to using the method that genearted this entry. modpath The module path that is compatible with tool referencing the target. While this is typically identical with modname, some tools require certain modifications or markers in additional to what is presented (e.g. such as the addition of a '?' symbol to ensure absolute lookup). """ 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) modpath = self.modname_source_target_modnamesource_to_modpath( spec, modname, source, target, modname_source) except ValueError as e: # figure out which of the above 3 functions failed by # acquiring the name from one frame down. f_name = sys.exc_info()[2].tb_next.tb_frame.f_code.co_name if isinstance(e, ValueSkip): # a purposely benign failure. log = partial( logger.info, "toolchain purposely skipping on '%s', " "reason: %s, where modname='%s', source='%s'", ) else: log = partial( logger.warning, "toolchain failed to acquire name with '%s', " "reason: %s, where modname='%s', source='%s'; " "skipping", ) log(f_name, e, *modname_source) continue yield modname, source, target, modpath
python
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 JavaScript module name. source Stands for sourcepath - path to some JavaScript source file. target Stands for targetpath - the target path relative to spec[BUILD_DIR] where the source file will be written to using the method that genearted this entry. modpath The module path that is compatible with tool referencing the target. While this is typically identical with modname, some tools require certain modifications or markers in additional to what is presented (e.g. such as the addition of a '?' symbol to ensure absolute lookup). """ 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) modpath = self.modname_source_target_modnamesource_to_modpath( spec, modname, source, target, modname_source) except ValueError as e: # figure out which of the above 3 functions failed by # acquiring the name from one frame down. f_name = sys.exc_info()[2].tb_next.tb_frame.f_code.co_name if isinstance(e, ValueSkip): # a purposely benign failure. log = partial( logger.info, "toolchain purposely skipping on '%s', " "reason: %s, where modname='%s', source='%s'", ) else: log = partial( logger.warning, "toolchain failed to acquire name with '%s', " "reason: %s, where modname='%s', source='%s'; " "skipping", ) log(f_name, e, *modname_source) continue yield modname, source, target, modpath
[ "def", "_gen_modname_source_target_modpath", "(", "self", ",", "spec", ",", "d", ")", ":", "for", "modname_source", "in", "d", ".", "items", "(", ")", ":", "try", ":", "modname", "=", "self", ".", "modname_source_to_modname", "(", "spec", ",", "*", "modnam...
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 JavaScript module name. source Stands for sourcepath - path to some JavaScript source file. target Stands for targetpath - the target path relative to spec[BUILD_DIR] where the source file will be written to using the method that genearted this entry. modpath The module path that is compatible with tool referencing the target. While this is typically identical with modname, some tools require certain modifications or markers in additional to what is presented (e.g. such as the addition of a '?' symbol to ensure absolute lookup).
[ "Private", "generator", "that", "will", "consume", "those", "above", "functions", ".", "This", "should", "NOT", "be", "overridden", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1366-L1420
train
45,809
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.compile
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] = 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_NAMES, export_module_names) ) def compile_entry(method, read_key, store_key): spec_read_key = read_key + self.sourcepath_suffix spec_modpath_key = store_key + self.modpath_suffix spec_target_key = store_key + self.targetpath_suffix if _check_key_exists(spec, [spec_modpath_key, spec_target_key]): logger.error( "aborting compile step %r due to existing key", entry, ) return sourcepath_dict = spec.get(spec_read_key, {}) entries = self._gen_modname_source_target_modpath( spec, sourcepath_dict) (spec[spec_modpath_key], spec[spec_target_key], new_module_names) = method(spec, entries) logger.debug( "entry %r " "wrote %d entries to spec[%r], " "wrote %d entries to spec[%r], " "added %d export_module_names", entry, len(spec[spec_modpath_key]), spec_modpath_key, len(spec[spec_target_key]), spec_target_key, len(new_module_names), ) export_module_names.extend(new_module_names) for entry in self.compile_entries: if isinstance(entry, ToolchainSpecCompileEntry): log = partial( logging.getLogger(entry.logger).log, entry.log_level, ( entry.store_key + "%s['%s'] is being rewritten from " "'%s' to '%s'; configuration may now be invalid" ), ) if entry.logger else None compile_entry(partial( toolchain_spec_compile_entries, self, process_name=entry.process_name, overwrite_log=log, ), entry.read_key, entry.store_key) continue m, read_key, store_key = entry if callable(m): method = m else: method = getattr(self, self.compile_prefix + m, None) if not callable(method): logger.error( "'%s' not a callable attribute for %r from " "compile_entries entry %r; skipping", m, self, entry ) continue compile_entry(method, read_key, store_key)
python
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] = 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_NAMES, export_module_names) ) def compile_entry(method, read_key, store_key): spec_read_key = read_key + self.sourcepath_suffix spec_modpath_key = store_key + self.modpath_suffix spec_target_key = store_key + self.targetpath_suffix if _check_key_exists(spec, [spec_modpath_key, spec_target_key]): logger.error( "aborting compile step %r due to existing key", entry, ) return sourcepath_dict = spec.get(spec_read_key, {}) entries = self._gen_modname_source_target_modpath( spec, sourcepath_dict) (spec[spec_modpath_key], spec[spec_target_key], new_module_names) = method(spec, entries) logger.debug( "entry %r " "wrote %d entries to spec[%r], " "wrote %d entries to spec[%r], " "added %d export_module_names", entry, len(spec[spec_modpath_key]), spec_modpath_key, len(spec[spec_target_key]), spec_target_key, len(new_module_names), ) export_module_names.extend(new_module_names) for entry in self.compile_entries: if isinstance(entry, ToolchainSpecCompileEntry): log = partial( logging.getLogger(entry.logger).log, entry.log_level, ( entry.store_key + "%s['%s'] is being rewritten from " "'%s' to '%s'; configuration may now be invalid" ), ) if entry.logger else None compile_entry(partial( toolchain_spec_compile_entries, self, process_name=entry.process_name, overwrite_log=log, ), entry.read_key, entry.store_key) continue m, read_key, store_key = entry if callable(m): method = m else: method = getattr(self, self.compile_prefix + m, None) if not callable(method): logger.error( "'%s' not a callable attribute for %r from " "compile_entries entry %r; skipping", m, self, entry ) continue compile_entry(method, read_key, store_key)
[ "def", "compile", "(", "self", ",", "spec", ")", ":", "spec", "[", "EXPORT_MODULE_NAMES", "]", "=", "export_module_names", "=", "spec", ".", "get", "(", "EXPORT_MODULE_NAMES", ",", "[", "]", ")", "if", "not", "isinstance", "(", "export_module_names", ",", ...
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.
[ "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", "proc...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1433-L1506
train
45,810
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain._calf
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)
python
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", ")", ":", "self", ".", "prepare", "(", "spec", ")", "self", ".", "compile", "(", "spec", ")", "self", ".", "assemble", "(", "spec", ")", "self", ".", "link", "(", "spec", ")", "self", ".", "finalize", "("...
The main call, assuming the base spec is prepared. Also, no advices will be triggered.
[ "The", "main", "call", "assuming", "the", "base", "spec", "is", "prepared", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1540-L1551
train
45,811
calmjs/calmjs
src/calmjs/toolchain.py
Toolchain.calf
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 not spec.get(BUILD_DIR): tempdir = realpath(mkdtemp()) spec.advise(CLEANUP, shutil.rmtree, tempdir) build_dir = join(tempdir, 'build') mkdir(build_dir) spec[BUILD_DIR] = build_dir else: build_dir = self.realpath(spec, BUILD_DIR) if not isdir(build_dir): logger.error("build_dir '%s' is not a directory", build_dir) raise_os_error(errno.ENOTDIR, build_dir) self.realpath(spec, EXPORT_TARGET) # Finally, handle setup which may set up the deferred advices, # as all the toolchain (and its runtime and/or its parent # runtime and related toolchains) spec advises should have been # done. spec.handle(SETUP) try: process = ('prepare', 'compile', 'assemble', 'link', 'finalize') for p in process: spec.handle('before_' + p) getattr(self, p)(spec) spec.handle('after_' + p) spec.handle(SUCCESS) except ToolchainCancel: # quietly handle the issue and move on out of here. pass finally: spec.handle(CLEANUP)
python
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 not spec.get(BUILD_DIR): tempdir = realpath(mkdtemp()) spec.advise(CLEANUP, shutil.rmtree, tempdir) build_dir = join(tempdir, 'build') mkdir(build_dir) spec[BUILD_DIR] = build_dir else: build_dir = self.realpath(spec, BUILD_DIR) if not isdir(build_dir): logger.error("build_dir '%s' is not a directory", build_dir) raise_os_error(errno.ENOTDIR, build_dir) self.realpath(spec, EXPORT_TARGET) # Finally, handle setup which may set up the deferred advices, # as all the toolchain (and its runtime and/or its parent # runtime and related toolchains) spec advises should have been # done. spec.handle(SETUP) try: process = ('prepare', 'compile', 'assemble', 'link', 'finalize') for p in process: spec.handle('before_' + p) getattr(self, p)(spec) spec.handle('after_' + p) spec.handle(SUCCESS) except ToolchainCancel: # quietly handle the issue and move on out of here. pass finally: spec.handle(CLEANUP)
[ "def", "calf", "(", "self", ",", "spec", ")", ":", "if", "not", "isinstance", "(", "spec", ",", "Spec", ")", ":", "raise", "TypeError", "(", "'spec must be of type Spec'", ")", "if", "not", "spec", ".", "get", "(", "BUILD_DIR", ")", ":", "tempdir", "="...
Typical safe usage is this, which sets everything that could be problematic up. Requires the filename which everything will be produced to.
[ "Typical", "safe", "usage", "is", "this", "which", "sets", "everything", "that", "could", "be", "problematic", "up", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1553-L1595
train
45,812
calmjs/calmjs
src/calmjs/toolchain.py
NullToolchain.transpile_modname_source_target
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)
python
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", "transpile_modname_source_target", "(", "self", ",", "spec", ",", "modname", ",", "source", ",", "target", ")", ":", "return", "self", ".", "simple_transpile_modname_source_target", "(", "spec", ",", "modname", ",", "source", ",", "target", ")" ]
Calls the original version.
[ "Calls", "the", "original", "version", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/toolchain.py#L1617-L1623
train
45,813
calmjs/calmjs
src/calmjs/cli.py
get_bin_version_str
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] except OSError: logger.warning("failed to execute '%s'", bin_path) return None except Exception: logger.exception( "encountered unexpected error while trying to find version of " "'%s':", bin_path ) return None logger.info("'%s' is version '%s'", bin_path, version_str) return version_str
python
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] except OSError: logger.warning("failed to execute '%s'", bin_path) return None except Exception: logger.exception( "encountered unexpected error while trying to find version of " "'%s':", bin_path ) return None logger.info("'%s' is version '%s'", bin_path, version_str) return version_str
[ "def", "get_bin_version_str", "(", "bin_path", ",", "version_flag", "=", "'-v'", ",", "kw", "=", "{", "}", ")", ":", "try", ":", "prog", "=", "_get_exec_binary", "(", "bin_path", ",", "kw", ")", "version_str", "=", "version_expr", ".", "search", "(", "ch...
Get the version string through the binary.
[ "Get", "the", "version", "string", "through", "the", "binary", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L46-L66
train
45,814
calmjs/calmjs
src/calmjs/cli.py
get_bin_version
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('.'))
python
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", "get_bin_version", "(", "bin_path", ",", "version_flag", "=", "'-v'", ",", "kw", "=", "{", "}", ")", ":", "version_str", "=", "get_bin_version_str", "(", "bin_path", ",", "version_flag", ",", "kw", ")", "if", "version_str", ":", "return", "tuple", "...
Get the version string through the binary and return a tuple of integers.
[ "Get", "the", "version", "string", "through", "the", "binary", "and", "return", "a", "tuple", "of", "integers", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L69-L77
train
45,815
calmjs/calmjs
src/calmjs/cli.py
NodeDriver.node
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)
python
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", "node", "(", "self", ",", "source", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ")", ":", "return", "self", ".", "_exec", "(", "self", ".", "node_bin", ",", "source", ",", "args", "=", "args", ",", "env", "=", "env", ")" ]
Calls node with an inline source. Returns decoded output of stdout and stderr; decoding determine by locale.
[ "Calls", "node", "with", "an", "inline", "source", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L119-L127
train
45,816
calmjs/calmjs
src/calmjs/cli.py
PackageManagerDriver.create_for_module_vars
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. """ 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 and/or update %(PATH)s environment variable " "with one that provides '%(binary)s'; or specify a " "working %(NODE_PATH)s environment variable with " "%(binary)s installed; or have install '%(binary)s' into " "the current working directory (%(cwd)s) either through " "npm or calmjs framework for this package. Restart or " "reload this module once that is done. Alternatively, " "create a manual Driver instance for '%(binary)s' with " "explicitly defined arguments." % { 'binary': inst.binary, 'PATH': 'PATH', 'NODE_PATH': 'NODE_PATH', 'cwd': inst.join_cwd(), } ) warnings.warn(msg, RuntimeWarning) scope_vars.update(inst._aliases) return inst
python
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. """ 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 and/or update %(PATH)s environment variable " "with one that provides '%(binary)s'; or specify a " "working %(NODE_PATH)s environment variable with " "%(binary)s installed; or have install '%(binary)s' into " "the current working directory (%(cwd)s) either through " "npm or calmjs framework for this package. Restart or " "reload this module once that is done. Alternatively, " "create a manual Driver instance for '%(binary)s' with " "explicitly defined arguments." % { 'binary': inst.binary, 'PATH': 'PATH', 'NODE_PATH': 'NODE_PATH', 'cwd': inst.join_cwd(), } ) warnings.warn(msg, RuntimeWarning) scope_vars.update(inst._aliases) return inst
[ "def", "create_for_module_vars", "(", "cls", ",", "scope_vars", ")", ":", "inst", "=", "cls", "(", ")", "if", "not", "inst", ".", "_set_env_path_with_node_modules", "(", ")", ":", "import", "warnings", "msg", "=", "(", "\"Unable to locate the '%(binary)s' binary o...
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.
[ "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",...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L204-L237
train
45,817
calmjs/calmjs
src/calmjs/cli.py
PackageManagerDriver.pkg_manager_view
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. Arguments: package_names The names of the python packages with their requirements to source the package.json from. stream If specified, the generated package.json will be written to there. explicit If True, the package names specified are the explicit list to search for - no dependency resolution will then be done. Returns the manifest json as a dict. """ # 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(package_names) if malformed: msg = 'malformed package name(s) specified: %s' % ', '.join( malformed) raise ValueError(msg) if len(pkg_names) == 1: logger.info( "generating a flattened '%s' for '%s'", self.pkgdef_filename, pkg_names[0], ) else: logger.info( "generating a flattened '%s' for packages {%s}", self.pkgdef_filename, ', '.join(pkg_names), ) # remember the filename is in the context of the distribution, # not the filesystem. dists = to_dists[explicit](pkg_names) pkgdef_json = flatten_dist_egginfo_json( dists, filename=self.pkgdef_filename, dep_keys=self.dep_keys, ) if pkgdef_json.get( self.pkg_name_field, NotImplemented) is NotImplemented: # use the last item. pkg_name = Requirement.parse(pkg_names[-1]).project_name pkgdef_json[self.pkg_name_field] = pkg_name if stream: self.dump(pkgdef_json, stream) stream.write('\n') return pkgdef_json
python
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. Arguments: package_names The names of the python packages with their requirements to source the package.json from. stream If specified, the generated package.json will be written to there. explicit If True, the package names specified are the explicit list to search for - no dependency resolution will then be done. Returns the manifest json as a dict. """ # 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(package_names) if malformed: msg = 'malformed package name(s) specified: %s' % ', '.join( malformed) raise ValueError(msg) if len(pkg_names) == 1: logger.info( "generating a flattened '%s' for '%s'", self.pkgdef_filename, pkg_names[0], ) else: logger.info( "generating a flattened '%s' for packages {%s}", self.pkgdef_filename, ', '.join(pkg_names), ) # remember the filename is in the context of the distribution, # not the filesystem. dists = to_dists[explicit](pkg_names) pkgdef_json = flatten_dist_egginfo_json( dists, filename=self.pkgdef_filename, dep_keys=self.dep_keys, ) if pkgdef_json.get( self.pkg_name_field, NotImplemented) is NotImplemented: # use the last item. pkg_name = Requirement.parse(pkg_names[-1]).project_name pkgdef_json[self.pkg_name_field] = pkg_name if stream: self.dump(pkgdef_json, stream) stream.write('\n') return pkgdef_json
[ "def", "pkg_manager_view", "(", "self", ",", "package_names", ",", "stream", "=", "None", ",", "explicit", "=", "False", ",", "*", "*", "kw", ")", ":", "# For looking up the pkg_name to dist converter for explicit", "to_dists", "=", "{", "False", ":", "find_packag...
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. Arguments: package_names The names of the python packages with their requirements to source the package.json from. stream If specified, the generated package.json will be written to there. explicit If True, the package names specified are the explicit list to search for - no dependency resolution will then be done. Returns the manifest json as a dict.
[ "Returns", "the", "manifest", "JSON", "for", "the", "Python", "package", "name", ".", "Default", "npm", "implementation", "calls", "for", "package", ".", "json", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L243-L310
train
45,818
calmjs/calmjs
src/calmjs/cli.py
PackageManagerDriver.pkg_manager_install
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. If the production argument is supplied, it will be passed to the underlying package manager binary as a true or false value with the --production flag, otherwise it will not be set. Likewise for development. However, the production flag has priority. If the argument 'args' is supplied as a tuple, those will be passed through to the package manager install command as its arguments. This will be very specific to the underlying program; use with care as misuse can result in an environment that is not expected by the other parts of the framework. If the argument 'env' is supplied, they will be additional environment variables that are not already defined by the framework, which are 'NODE_PATH' and 'PATH'. Values set for those will have highest precedence, then the ones passed in through env, then finally whatever was already defined before the execution of this program. All other arguments to this method will be passed forward to the pkg_manager_init method, if the package_name is supplied for the Python package. If no package_name was supplied then just continue with the process anyway, to still enable the shorthand calling. If the package manager could not be invoked, it will simply not be. Arguments: package_names The names of the Python package to generate the manifest for. args The arguments to pass into the command line install. """ 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: logger.warning( "not continuing with '%s %s' as the generation of " "'%s' failed", self.pkg_manager_bin, self.install_cmd, self.pkgdef_filename ) return call_kw = self._gen_call_kws(**env) logger.debug( "invoking '%s %s'", self.pkg_manager_bin, self.install_cmd) if self.env_path: logger.debug( "invoked with env_path '%s'", self.env_path) if self.working_dir: logger.debug( "invoked from working directory '%s'", self.working_dir) try: cmd = [self._get_exec_binary(call_kw), self.install_cmd] cmd.extend(self._prodev_flag( production, development, result.get(self.devkey))) cmd.extend(args) logger.info('invoking %s', ' '.join(cmd)) call(cmd, **call_kw) except (IOError, OSError): logger.error( "invocation of the '%s' binary failed; please ensure it and " "its dependencies are installed and available.", self.binary ) # Still raise the exception as this is a lower level API. raise return True
python
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. If the production argument is supplied, it will be passed to the underlying package manager binary as a true or false value with the --production flag, otherwise it will not be set. Likewise for development. However, the production flag has priority. If the argument 'args' is supplied as a tuple, those will be passed through to the package manager install command as its arguments. This will be very specific to the underlying program; use with care as misuse can result in an environment that is not expected by the other parts of the framework. If the argument 'env' is supplied, they will be additional environment variables that are not already defined by the framework, which are 'NODE_PATH' and 'PATH'. Values set for those will have highest precedence, then the ones passed in through env, then finally whatever was already defined before the execution of this program. All other arguments to this method will be passed forward to the pkg_manager_init method, if the package_name is supplied for the Python package. If no package_name was supplied then just continue with the process anyway, to still enable the shorthand calling. If the package manager could not be invoked, it will simply not be. Arguments: package_names The names of the Python package to generate the manifest for. args The arguments to pass into the command line install. """ 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: logger.warning( "not continuing with '%s %s' as the generation of " "'%s' failed", self.pkg_manager_bin, self.install_cmd, self.pkgdef_filename ) return call_kw = self._gen_call_kws(**env) logger.debug( "invoking '%s %s'", self.pkg_manager_bin, self.install_cmd) if self.env_path: logger.debug( "invoked with env_path '%s'", self.env_path) if self.working_dir: logger.debug( "invoked from working directory '%s'", self.working_dir) try: cmd = [self._get_exec_binary(call_kw), self.install_cmd] cmd.extend(self._prodev_flag( production, development, result.get(self.devkey))) cmd.extend(args) logger.info('invoking %s', ' '.join(cmd)) call(cmd, **call_kw) except (IOError, OSError): logger.error( "invocation of the '%s' binary failed; please ensure it and " "its dependencies are installed and available.", self.binary ) # Still raise the exception as this is a lower level API. raise return True
[ "def", "pkg_manager_install", "(", "self", ",", "package_names", "=", "None", ",", "production", "=", "None", ",", "development", "=", "None", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "if", "not", "packa...
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. If the production argument is supplied, it will be passed to the underlying package manager binary as a true or false value with the --production flag, otherwise it will not be set. Likewise for development. However, the production flag has priority. If the argument 'args' is supplied as a tuple, those will be passed through to the package manager install command as its arguments. This will be very specific to the underlying program; use with care as misuse can result in an environment that is not expected by the other parts of the framework. If the argument 'env' is supplied, they will be additional environment variables that are not already defined by the framework, which are 'NODE_PATH' and 'PATH'. Values set for those will have highest precedence, then the ones passed in through env, then finally whatever was already defined before the execution of this program. All other arguments to this method will be passed forward to the pkg_manager_init method, if the package_name is supplied for the Python package. If no package_name was supplied then just continue with the process anyway, to still enable the shorthand calling. If the package manager could not be invoked, it will simply not be. Arguments: package_names The names of the Python package to generate the manifest for. args The arguments to pass into the command line install.
[ "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", ...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L415-L505
train
45,819
calmjs/calmjs
src/calmjs/cli.py
PackageManagerDriver.run
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)
python
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", "run", "(", "self", ",", "args", "=", "(", ")", ",", "env", "=", "{", "}", ")", ":", "# the following will call self._get_exec_binary", "return", "self", ".", "_exec", "(", "self", ".", "binary", ",", "args", "=", "args", ",", "env", "=", "env",...
Calls the package manager with the arguments. Returns decoded output of stdout and stderr; decoding determine by locale.
[ "Calls", "the", "package", "manager", "with", "the", "arguments", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L540-L549
train
45,820
calmjs/calmjs
src/calmjs/base.py
_get_exec_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 keyword arguments that will be passed into whatever respective subprocess.Popen family of methods. The PATH environment variable will be used if available. """ binary = which(binary, path=kw.get('env', {}).get('PATH')) if binary is None: raise_os_error(errno.ENOENT) return binary
python
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 keyword arguments that will be passed into whatever respective subprocess.Popen family of methods. The PATH environment variable will be used if available. """ 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", ")", ":", "binary", "=", "which", "(", "binary", ",", "path", "=", "kw", ".", "get", "(", "'env'", ",", "{", "}", ")", ".", "get", "(", "'PATH'", ")", ")", "if", "binary", "is", "None", ":", ...
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 keyword arguments that will be passed into whatever respective subprocess.Popen family of methods. The PATH environment variable will be used if available.
[ "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", "...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L59-L75
train
45,821
calmjs/calmjs
src/calmjs/base.py
BaseRegistry._init_entry_points
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: logger.debug( "registering entry point '%s' from '%s'", entry_point, entry_point.dist, ) self._init_entry_point(entry_point) except ImportError: logger.warning( 'ImportError: %s not found; skipping registration', entry_point.module_name) except Exception: logger.exception( "registration of entry point '%s' from '%s' to registry " "'%s' failed with the following exception", entry_point, entry_point.dist, self.registry_name, )
python
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: logger.debug( "registering entry point '%s' from '%s'", entry_point, entry_point.dist, ) self._init_entry_point(entry_point) except ImportError: logger.warning( 'ImportError: %s not found; skipping registration', entry_point.module_name) except Exception: logger.exception( "registration of entry point '%s' from '%s' to registry " "'%s' failed with the following exception", entry_point, entry_point.dist, self.registry_name, )
[ "def", "_init_entry_points", "(", "self", ",", "entry_points", ")", ":", "logger", ".", "debug", "(", "\"registering %d entry points for registry '%s'\"", ",", "len", "(", "entry_points", ")", ",", "self", ".", "registry_name", ",", ")", "for", "entry_point", "in"...
Default initialization loop.
[ "Default", "initialization", "loop", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L153-L178
train
45,822
calmjs/calmjs
src/calmjs/base.py
BasePkgRefRegistry.store_records_for_package
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 namespace; while normally this does not happen, # this default implementation make no assumptions as to whether # or not this is permitted. pkg_module_records = self._dist_to_package_module_map(entry_point) pkg_module_records.extend(records)
python
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 namespace; while normally this does not happen, # this default implementation make no assumptions as to whether # or not this is permitted. pkg_module_records = self._dist_to_package_module_map(entry_point) pkg_module_records.extend(records)
[ "def", "store_records_for_package", "(", "self", ",", "entry_point", ",", "records", ")", ":", "# 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,...
Store the records in a way that permit lookup by package
[ "Store", "the", "records", "in", "a", "way", "that", "permit", "lookup", "by", "package" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L248-L259
train
45,823
calmjs/calmjs
src/calmjs/base.py
BaseModuleRegistry.register_entry_point
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)
python
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", "(", "self", ",", "entry_point", ")", ":", "module", "=", "_import_module", "(", "entry_point", ".", "module_name", ")", "self", ".", "_register_entry_point_module", "(", "entry_point", ",", "module", ")" ]
Register a lone entry_point Will raise ImportError if the entry_point leads to an invalid import.
[ "Register", "a", "lone", "entry_point" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L277-L286
train
45,824
calmjs/calmjs
src/calmjs/base.py
BaseModuleRegistry._register_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())) for module_name, records in records_map.items(): if module_name in self.records: logger.info( "module '%s' was already declared in registry '%s'; " "applying new records on top.", module_name, self.registry_name, ) logger.debug("overwriting keys: %s", sorted( set(self.records[module_name].keys()) & set(records.keys()) )) self.records[module_name].update(records) else: logger.debug( "adding records for module '%s' to registry '%s'", module_name, self.registry_name, ) self.records[module_name] = records
python
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())) for module_name, records in records_map.items(): if module_name in self.records: logger.info( "module '%s' was already declared in registry '%s'; " "applying new records on top.", module_name, self.registry_name, ) logger.debug("overwriting keys: %s", sorted( set(self.records[module_name].keys()) & set(records.keys()) )) self.records[module_name].update(records) else: logger.debug( "adding records for module '%s' to registry '%s'", module_name, self.registry_name, ) self.records[module_name] = records
[ "def", "_register_entry_point_module", "(", "self", ",", "entry_point", ",", "module", ")", ":", "records_map", "=", "self", ".", "_map_entry_point_module", "(", "entry_point", ",", "module", ")", "self", ".", "store_records_for_package", "(", "entry_point", ",", ...
Private method that registers an entry_point with a provided module.
[ "Private", "method", "that", "registers", "an", "entry_point", "with", "a", "provided", "module", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L288-L314
train
45,825
calmjs/calmjs
src/calmjs/base.py
BaseModuleRegistry.get_record
def get_record(self, name): """ Get a record by name """ result = {} result.update(self.records.get(name, {})) return result
python
def get_record(self, name): """ Get a record by name """ result = {} result.update(self.records.get(name, {})) return result
[ "def", "get_record", "(", "self", ",", "name", ")", ":", "result", "=", "{", "}", "result", ".", "update", "(", "self", ".", "records", ".", "get", "(", "name", ",", "{", "}", ")", ")", "return", "result" ]
Get a record by name
[ "Get", "a", "record", "by", "name" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L326-L333
train
45,826
calmjs/calmjs
src/calmjs/base.py
BaseChildModuleRegistry.resolve_parent_registry_name
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 registry name defined with invalid suffix " "('%s' does not end with '%s')" % (registry_name, suffix)) return registry_name[:-len(suffix)]
python
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 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", ")", ":", "if", "not", "registry_name", ".", "endswith", "(", "suffix", ")", ":", "raise", "ValueError", "(", "\"child module registry name defined with invalid suffix \"", "\"('%s'...
Subclasses should override to specify the default suffix, as the invocation is done without a suffix.
[ "Subclasses", "should", "override", "to", "specify", "the", "default", "suffix", "as", "the", "invocation", "is", "done", "without", "a", "suffix", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L379-L389
train
45,827
calmjs/calmjs
src/calmjs/base.py
BaseExternalModuleRegistry.get_record
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()))
python
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_record", "(", "self", ",", "name", ")", ":", "return", "set", "(", ")", ".", "union", "(", "self", ".", "records", ".", "get", "(", "name", ",", "set", "(", ")", ")", ")" ]
Get a record for the registered name, which will be a set of matching desired "module names" for the given path.
[ "Get", "a", "record", "for", "the", "registered", "name", "which", "will", "be", "a", "set", "of", "matching", "desired", "module", "names", "for", "the", "given", "path", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L440-L446
train
45,828
calmjs/calmjs
src/calmjs/base.py
BaseDriver.which
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)
python
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", "which", "(", "self", ")", ":", "if", "self", ".", "binary", "is", "None", ":", "return", "None", "return", "which", "(", "self", ".", "binary", ",", "path", "=", "self", ".", "env_path", ")" ]
Figure out which binary this will execute. Returns None if the binary is not found.
[ "Figure", "out", "which", "binary", "this", "will", "execute", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L508-L518
train
45,829
calmjs/calmjs
src/calmjs/base.py
BaseDriver.find_node_modules_basedir
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' directory. """ 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 global. if self.node_path: paths.extend(self.node_path.split(pathsep)) return paths
python
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' directory. """ 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 global. if self.node_path: paths.extend(self.node_path.split(pathsep)) return paths
[ "def", "find_node_modules_basedir", "(", "self", ")", ":", "paths", "=", "[", "]", "# First do the working dir.", "local_node_path", "=", "self", ".", "join_cwd", "(", "NODE_MODULES", ")", "if", "isdir", "(", "local_node_path", ")", ":", "paths", ".", "append", ...
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' directory.
[ "Find", "all", "node_modules", "directories", "configured", "to", "be", "accessible", "through", "this", "driver", "instance", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L520-L544
train
45,830
calmjs/calmjs
src/calmjs/base.py
BaseDriver.which_with_node_modules
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 attempt to locate '%s' binary from " "%s%s%s%s%s, located through the working directory", self.__class__.__name__, self.binary, self.join_cwd(), sep, NODE_MODULES, sep, NODE_MODULES_BIN, ) if self.node_path: logger.debug( "'%s' instance will attempt to locate '%s' binary from " "its %s of %s", self.__class__.__name__, self.binary, NODE_PATH, self.node_path, ) paths = self.find_node_modules_basedir() whichpaths = pathsep.join(join(p, NODE_MODULES_BIN) for p in paths) if paths: logger.debug( "'%s' instance located %d possible paths to the '%s' binary, " "which are %s", self.__class__.__name__, len(paths), self.binary, whichpaths, ) return which(self.binary, path=whichpaths)
python
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 attempt to locate '%s' binary from " "%s%s%s%s%s, located through the working directory", self.__class__.__name__, self.binary, self.join_cwd(), sep, NODE_MODULES, sep, NODE_MODULES_BIN, ) if self.node_path: logger.debug( "'%s' instance will attempt to locate '%s' binary from " "its %s of %s", self.__class__.__name__, self.binary, NODE_PATH, self.node_path, ) paths = self.find_node_modules_basedir() whichpaths = pathsep.join(join(p, NODE_MODULES_BIN) for p in paths) if paths: logger.debug( "'%s' instance located %d possible paths to the '%s' binary, " "which are %s", self.__class__.__name__, len(paths), self.binary, whichpaths, ) return which(self.binary, path=whichpaths)
[ "def", "which_with_node_modules", "(", "self", ")", ":", "if", "self", ".", "binary", "is", "None", ":", "return", "None", "# first, log down the pedantic things...", "if", "isdir", "(", "self", ".", "join_cwd", "(", "NODE_MODULES", ")", ")", ":", "logger", "....
Which with node_path and node_modules
[ "Which", "with", "node_path", "and", "node_modules" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L546-L580
train
45,831
calmjs/calmjs
src/calmjs/base.py
BaseDriver._set_env_path_with_node_modules
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: raise ValueError( "binary undefined for '%s' instance" % modcls_name) logger.debug( "locating '%s' node binary for %s instance...", self.binary, modcls_name, ) default = self.which() if default is not None: logger.debug( "found '%s'; " "not modifying PATH environment variable in instance of '%s'.", realpath(default), modcls_name) return True target = self.which_with_node_modules() if target: # Only setting the path specific for the binary; side effect # will be whoever else borrowing the _exec in here might not # get the binary they want. That's why it's private. self.env_path = dirname(target) logger.debug( "located '%s' binary at '%s'; setting PATH environment " "variable for '%s' instance.", self.binary, self.env_path, modcls_name ) return True else: logger.debug( "Unable to locate '%s'; not modifying PATH environment " "variable for instance of '%s'.", self.binary, modcls_name ) return False
python
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: raise ValueError( "binary undefined for '%s' instance" % modcls_name) logger.debug( "locating '%s' node binary for %s instance...", self.binary, modcls_name, ) default = self.which() if default is not None: logger.debug( "found '%s'; " "not modifying PATH environment variable in instance of '%s'.", realpath(default), modcls_name) return True target = self.which_with_node_modules() if target: # Only setting the path specific for the binary; side effect # will be whoever else borrowing the _exec in here might not # get the binary they want. That's why it's private. self.env_path = dirname(target) logger.debug( "located '%s' binary at '%s'; setting PATH environment " "variable for '%s' instance.", self.binary, self.env_path, modcls_name ) return True else: logger.debug( "Unable to locate '%s'; not modifying PATH environment " "variable for instance of '%s'.", self.binary, modcls_name ) return False
[ "def", "_set_env_path_with_node_modules", "(", "self", ")", ":", "modcls_name", "=", "':'", ".", "join", "(", "(", "self", ".", "__class__", ".", "__module__", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "if", "self", ".", "binary", "is", "...
Attempt to locate and set the paths to the binary with the working directory defined for this instance.
[ "Attempt", "to", "locate", "and", "set", "the", "paths", "to", "the", "binary", "with", "the", "working", "directory", "defined", "for", "this", "instance", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L593-L638
train
45,832
calmjs/calmjs
src/calmjs/base.py
BaseDriver._exec
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. """ 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)
python
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. """ 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", "=", "{", "}", ")", ":", "call_kw", "=", "self", ".", "_gen_call_kws", "(", "*", "*", "env", ")", "call_args", "=", "[", "self", ".", ...
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.
[ "Executes", "the", "binary", "using", "stdin", "and", "args", "with", "environment", "variables", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L672-L685
train
45,833
calmjs/calmjs
src/calmjs/base.py
BaseDriver.dump
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, )
python
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", "dump", "(", "self", ",", "blob", ",", "stream", ")", ":", "json", ".", "dump", "(", "blob", ",", "stream", ",", "indent", "=", "self", ".", "indent", ",", "sort_keys", "=", "True", ",", "separators", "=", "self", ".", "separators", ",", ")"...
Call json.dump with the attributes of this instance as arguments.
[ "Call", "json", ".", "dump", "with", "the", "attributes", "of", "this", "instance", "as", "arguments", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L691-L700
train
45,834
calmjs/calmjs
src/calmjs/base.py
BaseDriver.dumps
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, )
python
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", "dumps", "(", "self", ",", "blob", ")", ":", "return", "json", ".", "dumps", "(", "blob", ",", "indent", "=", "self", ".", "indent", ",", "sort_keys", "=", "True", ",", "separators", "=", "self", ".", "separators", ",", ")" ]
Call json.dumps with the attributes of this instance as arguments.
[ "Call", "json", ".", "dumps", "with", "the", "attributes", "of", "this", "instance", "as", "arguments", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L702-L711
train
45,835
calmjs/calmjs
src/calmjs/base.py
BaseDriver.join_cwd
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 'working_dir' set to '%s' for join_cwd", type(self).__name__, self.working_dir, ) cwd = self.working_dir else: cwd = getcwd() logger.debug( "'%s' instance 'working_dir' unset; " "default to process '%s' for join_cwd", type(self).__name__, cwd, ) if path: return join(cwd, path) return cwd
python
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 'working_dir' set to '%s' for join_cwd", type(self).__name__, self.working_dir, ) cwd = self.working_dir else: cwd = getcwd() logger.debug( "'%s' instance 'working_dir' unset; " "default to process '%s' for join_cwd", type(self).__name__, cwd, ) if path: return join(cwd, path) return cwd
[ "def", "join_cwd", "(", "self", ",", "path", "=", "None", ")", ":", "if", "self", ".", "working_dir", ":", "logger", ".", "debug", "(", "\"'%s' instance 'working_dir' set to '%s' for join_cwd\"", ",", "type", "(", "self", ")", ".", "__name__", ",", "self", "...
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.
[ "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", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/base.py#L713-L736
train
45,836
weso/CWR-DataApi
cwr/parser/encoder/cwrjson.py
_unicode_handler
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("Unserializable object {} of type {}".format(obj, type(obj))) return result
python
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("Unserializable object {} of type {}".format(obj, type(obj))) return result
[ "def", "_unicode_handler", "(", "obj", ")", ":", "try", ":", "result", "=", "obj", ".", "isoformat", "(", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Unserializable object {} of type {}\"", ".", "format", "(", "obj", ",", "type", "(", ...
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
[ "Transforms", "an", "unicode", "string", "into", "a", "UTF", "-", "8", "equivalent", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/parser/encoder/cwrjson.py#L57-L70
train
45,837
weso/CWR-DataApi
cwr/parser/encoder/cwrjson.py
JSONEncoder.encode
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) 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, ensure_ascii=False, default=_iso_handler) return result
python
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) 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, ensure_ascii=False, default=_iso_handler) return result
[ "def", "encode", "(", "self", ",", "entity", ")", ":", "encoded", "=", "self", ".", "_dict_encoder", ".", "encode", "(", "entity", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "result", "=", "json", ".", "dumps", "(", "enco...
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
[ "Encodes", "the", "data", "creating", "a", "JSON", "structure", "from", "an", "instance", "from", "the", "domain", "model", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/parser/encoder/cwrjson.py#L36-L54
train
45,838
weso/CWR-DataApi
cwr/grammar/field/special.py
ipi_base_number
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 :return: a parser for the IPI Base Number field """ 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.setResultsName('ipi_base_n')
python
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 :return: a parser for the IPI Base Number field """ 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.setResultsName('ipi_base_n')
[ "def", "ipi_base_number", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'IPI Base Number Field'", "field", "=", "pp", ".", "Regex", "(", "'I-[0-9]{9}-[0-9]'", ")", "# Name", "field", ".", "setName", "(", "name", ")", ...
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 :return: a parser for the IPI Base Number field
[ "IPI", "Base", "Number", "field", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L38-L70
train
45,839
weso/CWR-DataApi
cwr/grammar/field/special.py
ipi_name_number
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: name = 'IPI Name Number Field' field = basic.numeric(11) field.setName(name) return field.setResultsName('ipi_name_n')
python
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: name = 'IPI Name Number Field' field = basic.numeric(11) field.setName(name) return field.setResultsName('ipi_name_n')
[ "def", "ipi_name_number", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'IPI Name Number Field'", "field", "=", "basic", ".", "numeric", "(", "11", ")", "field", ".", "setName", "(", "name", ")", "return", "field", ...
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
[ "IPI", "Name", "Number", "field", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L73-L92
train
45,840
weso/CWR-DataApi
cwr/grammar/field/special.py
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 field """ 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')
python
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 field """ 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", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'ISWC Field'", "# T followed by 10 numbers", "field", "=", "pp", ".", "Regex", "(", "'T[0-9]{10}'", ")", "# Name", "field", ".", "setName", "(", "name", ")"...
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 field
[ "ISWC", "field", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L95-L123
train
45,841
weso/CWR-DataApi
cwr/grammar/field/special.py
_assert_is_percentage
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' \ % maximum raise pp.ParseException(message)
python
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' \ % maximum raise pp.ParseException(message)
[ "def", "_assert_is_percentage", "(", "value", ",", "maximum", "=", "100", ")", ":", "if", "value", "<", "0", "or", "value", ">", "maximum", ":", "message", "=", "'The value on a percentage field should be between 0 and %s'", "%", "maximum", "raise", "pp", ".", "...
Makes sure the received value is a percentage. Otherwise an exception is thrown. :param value: the value to check
[ "Makes", "sure", "the", "received", "value", "is", "a", "percentage", ".", "Otherwise", "an", "exception", "is", "thrown", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L160-L171
train
45,842
weso/CWR-DataApi
cwr/grammar/field/special.py
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 """ if name is None: name = 'EAN 13 Field' field = basic.numeric(13) field = field.setName(name) return field.setResultsName('ean_13')
python
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.setName(name) return field.setResultsName('ean_13')
[ "def", "ean_13", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'EAN 13 Field'", "field", "=", "basic", ".", "numeric", "(", "13", ")", "field", "=", "field", ".", "setName", "(", "name", ")", "return", "field", ...
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
[ "Creates", "the", "grammar", "for", "an", "EAN", "13", "code", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L174-L191
train
45,843
weso/CWR-DataApi
cwr/grammar/field/special.py
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 """ if name is None: name = 'ISRC Field' field = _isrc_short(name) | _isrc_long(name) field.setName(name) return field.setResultsName('isrc')
python
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 """ 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", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'ISRC Field'", "field", "=", "_isrc_short", "(", "name", ")", "|", "_isrc_long", "(", "name", ")", "field", ".", "setName", "(", "name", ")", "return", ...
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
[ "Creates", "the", "grammar", "for", "an", "ISRC", "code", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L194-L213
train
45,844
weso/CWR-DataApi
cwr/grammar/field/special.py
_isrc_long
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 means: - CC: country code - XXX: registrant - YY: year - NNNNN: work id :param name: name for the field :return: grammar for an ISRC field """ 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: country_regex += '|' country_regex += c country_regex = '(' + country_regex + ')' field = pp.Regex(country_regex + '.{3}[0-9]{2}[0-9]{5}') # country.setName('ISO-2 Country Code') # registrant.setName('Registrant') # year.setName('Year') # work_id.setName('Work ID') field.setName(name) return field.setResultsName('isrc')
python
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 means: - CC: country code - XXX: registrant - YY: year - NNNNN: work id :param name: name for the field :return: grammar for an ISRC field """ 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: country_regex += '|' country_regex += c country_regex = '(' + country_regex + ')' field = pp.Regex(country_regex + '.{3}[0-9]{2}[0-9]{5}') # country.setName('ISO-2 Country Code') # registrant.setName('Registrant') # year.setName('Year') # work_id.setName('Work ID') field.setName(name) return field.setResultsName('isrc')
[ "def", "_isrc_long", "(", "name", "=", "None", ")", ":", "config", "=", "CWRTables", "(", ")", "if", "name", "is", "None", ":", "name", "=", "'ISRC Field'", "country", "=", "config", ".", "get_data", "(", "'isrc_country_code'", ")", "# registrant = basic.alp...
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 means: - CC: country code - XXX: registrant - YY: year - NNNNN: work id :param name: name for the field :return: grammar for an ISRC field
[ "Creates", "the", "grammar", "for", "a", "short", "ISRC", "code", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L267-L314
train
45,845
weso/CWR-DataApi
cwr/grammar/field/special.py
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 """ if name is None: name = 'V-ISAN Field' field = pp.Regex('[0-9]{25}') field.setName(name) return field.setResultsName('visan')
python
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]{25}') field.setName(name) return field.setResultsName('visan')
[ "def", "visan", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'V-ISAN Field'", "field", "=", "pp", ".", "Regex", "(", "'[0-9]{25}'", ")", "field", ".", "setName", "(", "name", ")", "return", "field", ".", "setResu...
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
[ "Creates", "the", "grammar", "for", "a", "V", "-", "ISAN", "code", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L317-L334
train
45,846
weso/CWR-DataApi
cwr/grammar/field/special.py
audio_visual_key
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' 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.setParseAction(pp.replaceWith('')) av_number = av_number | field_empty av_number = av_number.setName('Audio-Visual Number') \ .setResultsName('av_number') field = pp.Group(society_code + pp.Optional(av_number)) field.setParseAction(lambda v: _to_avi(v[0])) field = field.setName(name) return field.setResultsName('audio_visual_key')
python
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' 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.setParseAction(pp.replaceWith('')) av_number = av_number | field_empty av_number = av_number.setName('Audio-Visual Number') \ .setResultsName('av_number') field = pp.Group(society_code + pp.Optional(av_number)) field.setParseAction(lambda v: _to_avi(v[0])) field = field.setName(name) return field.setResultsName('audio_visual_key')
[ "def", "audio_visual_key", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'AVI Field'", "society_code", "=", "basic", ".", "numeric", "(", "3", ")", "society_code", "=", "society_code", ".", "setName", "(", "'Society Cod...
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
[ "Creates", "the", "grammar", "for", "an", "Audio", "Visual", "Key", "code", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L337-L367
train
45,847
weso/CWR-DataApi
cwr/grammar/field/special.py
lookup_int
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])) return field
python
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])) return field
[ "def", "lookup_int", "(", "values", ",", "name", "=", "None", ")", ":", "field", "=", "basic", ".", "lookup", "(", "values", ",", "name", ")", "field", ".", "addParseAction", "(", "lambda", "l", ":", "int", "(", "l", "[", "0", "]", ")", ")", "ret...
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
[ "Lookup", "field", "which", "transforms", "the", "result", "into", "an", "integer", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L419-L431
train
45,848
calmjs/calmjs
src/calmjs/interrogate.py
extract_function_argument
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 """ tree = parse(text) return list(filter_function_argument(tree, f_name, f_argn, f_argt))
python
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 """ 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", ")", ":", "tree", "=", "parse", "(", "text", ")", "return", "list", "(", "filter_function_argument", "(", "tree", ",", "f_name", "...
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
[ "Extract", "a", "specific", "argument", "from", "a", "specific", "function", "name", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/interrogate.py#L71-L89
train
45,849
calmjs/calmjs
src/calmjs/interrogate.py
yield_amd_require_string_arguments
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. """ 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
python
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. """ 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", ")", ":", "for", "i", ",", "child", "in", "enumerate", "(", "node", ".", "args", ".", "items", "[", "...
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.
[ "This", "yields", "only", "strings", "within", "the", "lists", "provided", "in", "the", "argument", "list", "at", "the", "specified", "position", "from", "a", "function", "call", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/interrogate.py#L110-L127
train
45,850
calmjs/calmjs
src/calmjs/interrogate.py
yield_string_argument
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])
python
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_string_argument", "(", "node", ",", "pos", ")", ":", "if", "not", "isinstance", "(", "node", ".", "args", ".", "items", "[", "pos", "]", ",", "asttypes", ".", "String", ")", ":", "return", "yield", "to_str", "(", "node", ".", "args", "....
Yield just a string argument from position of the function call.
[ "Yield", "just", "a", "string", "argument", "from", "position", "of", "the", "function", "call", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/interrogate.py#L132-L139
train
45,851
calmjs/calmjs
src/calmjs/interrogate.py
yield_module_imports
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('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 continue
python
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('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 continue
[ "def", "yield_module_imports", "(", "root", ",", "checks", "=", "string_imports", "(", ")", ")", ":", "if", "not", "isinstance", "(", "root", ",", "asttypes", ".", "Node", ")", ":", "raise", "TypeError", "(", "'provided root must be a node'", ")", "for", "ch...
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.
[ "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", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/interrogate.py#L184-L199
train
45,852
calmjs/calmjs
src/calmjs/interrogate.py
yield_module_imports_nodes
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: if condition(child): for name in f(child): yield name continue
python
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: if condition(child): for name in f(child): yield name continue
[ "def", "yield_module_imports_nodes", "(", "root", ",", "checks", "=", "import_nodes", "(", ")", ")", ":", "if", "not", "isinstance", "(", "root", ",", "asttypes", ".", "Node", ")", ":", "raise", "TypeError", "(", "'provided root must be a node'", ")", "for", ...
Yield all nodes that provide an import
[ "Yield", "all", "nodes", "that", "provide", "an", "import" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/interrogate.py#L212-L225
train
45,853
calmjs/calmjs
src/calmjs/module.py
resolve_child_module_registries_lineage
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, 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 standard entry point usage, but # non-standard definitions/usage can definitely trigger this # self-referential loop. raise TypeError( "registry '%s' was already recorded in the lineage, " "indicating that it may be some (grand)child of itself, which " "is an illegal reference in the registry system; previously " "resolved lineage is: %r" % (registry.parent.registry_name, [ r.registry_name for r in reversed(children) ]) ) pl = len(registry.parent.registry_name) if len(registry.parent.registry_name) > len(registry.registry_name): logger.warning( "the parent registry '%s' somehow has a longer name than its " "child registry '%s'; the underlying registry class may be " "constructed in an invalid manner", registry.parent.registry_name, registry.registry_name, ) elif registry.registry_name[:pl] != registry.parent.registry_name: logger.warning( "child registry '%s' does not share the same common prefix as " "its parent registry '%s'; there may be errors with how the " "related registries are set up or constructed", registry.registry_name, registry.parent.registry_name, ) children.append(registry.parent) registry = registry.parent # the lineage down from parent to child. return iter(reversed(children))
python
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, 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 standard entry point usage, but # non-standard definitions/usage can definitely trigger this # self-referential loop. raise TypeError( "registry '%s' was already recorded in the lineage, " "indicating that it may be some (grand)child of itself, which " "is an illegal reference in the registry system; previously " "resolved lineage is: %r" % (registry.parent.registry_name, [ r.registry_name for r in reversed(children) ]) ) pl = len(registry.parent.registry_name) if len(registry.parent.registry_name) > len(registry.registry_name): logger.warning( "the parent registry '%s' somehow has a longer name than its " "child registry '%s'; the underlying registry class may be " "constructed in an invalid manner", registry.parent.registry_name, registry.registry_name, ) elif registry.registry_name[:pl] != registry.parent.registry_name: logger.warning( "child registry '%s' does not share the same common prefix as " "its parent registry '%s'; there may be errors with how the " "related registries are set up or constructed", registry.registry_name, registry.parent.registry_name, ) children.append(registry.parent) registry = registry.parent # the lineage down from parent to child. return iter(reversed(children))
[ "def", "resolve_child_module_registries_lineage", "(", "registry", ")", ":", "children", "=", "[", "registry", "]", "while", "isinstance", "(", "registry", ",", "BaseChildModuleRegistry", ")", ":", "if", "registry", ".", "parent", "in", "children", ":", "# this sh...
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.
[ "For", "a", "given", "child", "module", "registry", "attempt", "to", "resolve", "the", "lineage", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/module.py#L74-L119
train
45,854
calmjs/calmjs
src/calmjs/indexer.py
resource_filename_mod_dist
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.DistributionNotFound: logger.warning( "distribution '%s' not found, falling back to resolution using " "module_name '%s'", dist, module_name, ) return pkg_resources.resource_filename(module_name, '')
python
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.DistributionNotFound: logger.warning( "distribution '%s' not found, falling back to resolution using " "module_name '%s'", dist, module_name, ) return pkg_resources.resource_filename(module_name, '')
[ "def", "resource_filename_mod_dist", "(", "module_name", ",", "dist", ")", ":", "try", ":", "return", "pkg_resources", ".", "resource_filename", "(", "dist", ".", "as_requirement", "(", ")", ",", "join", "(", "*", "module_name", ".", "split", "(", "'.'", ")"...
Given a module name and a distribution, attempt to resolve the actual path to the module.
[ "Given", "a", "module", "name", "and", "a", "distribution", "attempt", "to", "resolve", "the", "actual", "path", "to", "the", "module", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L31-L45
train
45,855
calmjs/calmjs
src/calmjs/indexer.py
resource_filename_mod_entry_point
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 distribution. That said, the default resource_filename function does not accept an entry_point, and so we have to chain that back together manually. """ 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.dist) if not result: logger.warning( "resource path cannot be found for module '%s' and entry_point " "'%s'", module_name, entry_point ) return None if not exists(result): logger.warning( "resource path found at '%s' for module '%s' and entry_point " "'%s', but it does not exist", result, module_name, entry_point, ) return None return result
python
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 distribution. That said, the default resource_filename function does not accept an entry_point, and so we have to chain that back together manually. """ 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.dist) if not result: logger.warning( "resource path cannot be found for module '%s' and entry_point " "'%s'", module_name, entry_point ) return None if not exists(result): logger.warning( "resource path found at '%s' for module '%s' and entry_point " "'%s', but it does not exist", result, module_name, entry_point, ) return None return result
[ "def", "resource_filename_mod_entry_point", "(", "module_name", ",", "entry_point", ")", ":", "if", "entry_point", ".", "dist", "is", "None", ":", "# distribution missing is typically caused by mocked entry", "# points from tests; silently falling back to basic lookup", "result", ...
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 distribution. That said, the default resource_filename function does not accept an entry_point, and so we have to chain that back together manually.
[ "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...
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L83-L113
train
45,856
calmjs/calmjs
src/calmjs/indexer.py
modgen
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 resources. Optional Arguments: modpath The name to the registered modpath function that will fetch the paths belonging to the module. Defaults to 'pkg_resources'. globber The name to the registered file globbing function. Defaults to one that will only glob the local path. fext The filename extension to match. Defaults to `.js`. registry The "registry" to extract the functions from Yields 3-tuples of - raw list of module name fragments - the source base path to the python module (equivalent to module) - the relative path to the actual module For each of the module basepath and source files the globber finds. """ 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('.') module_base_paths = modpath_f(module, entry_point) for module_base_path in module_base_paths: logger.debug('searching for *%s files in %s', fext, module_base_path) for path in globber_f(module_base_path, '*' + fext): mod_path = (relpath(path, module_base_path)) yield ( module_frags + mod_path[:-len(fext)].split(sep), module_base_path, mod_path, )
python
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 resources. Optional Arguments: modpath The name to the registered modpath function that will fetch the paths belonging to the module. Defaults to 'pkg_resources'. globber The name to the registered file globbing function. Defaults to one that will only glob the local path. fext The filename extension to match. Defaults to `.js`. registry The "registry" to extract the functions from Yields 3-tuples of - raw list of module name fragments - the source base path to the python module (equivalent to module) - the relative path to the actual module For each of the module basepath and source files the globber finds. """ 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('.') module_base_paths = modpath_f(module, entry_point) for module_base_path in module_base_paths: logger.debug('searching for *%s files in %s', fext, module_base_path) for path in globber_f(module_base_path, '*' + fext): mod_path = (relpath(path, module_base_path)) yield ( module_frags + mod_path[:-len(fext)].split(sep), module_base_path, mod_path, )
[ "def", "modgen", "(", "module", ",", "entry_point", ",", "modpath", "=", "'pkg_resources'", ",", "globber", "=", "'root'", ",", "fext", "=", "JS_EXT", ",", "registry", "=", "_utils", ")", ":", "globber_f", "=", "globber", "if", "callable", "(", "globber", ...
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 resources. Optional Arguments: modpath The name to the registered modpath function that will fetch the paths belonging to the module. Defaults to 'pkg_resources'. globber The name to the registered file globbing function. Defaults to one that will only glob the local path. fext The filename extension to match. Defaults to `.js`. registry The "registry" to extract the functions from Yields 3-tuples of - raw list of module name fragments - the source base path to the python module (equivalent to module) - the relative path to the actual module For each of the module basepath and source files the globber finds.
[ "JavaScript", "styled", "module", "location", "listing", "generator", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L116-L177
train
45,857
calmjs/calmjs
src/calmjs/indexer.py
register
def register(util_type, registry=_utils): """ Crude, local registration decorator for a crude local registry of all utilities local to this module. """ 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
python
def register(util_type, registry=_utils): """ Crude, local registration decorator for a crude local registry of all utilities local to this module. """ 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", ")", ":", "def", "marker", "(", "f", ")", ":", "mark", "=", "util_type", "+", "'_'", "if", "not", "f", ".", "__name__", ".", "startswith", "(", "mark", ")", ":", "raise", "TypeError...
Crude, local registration decorator for a crude local registry of all utilities local to this module.
[ "Crude", "local", "registration", "decorator", "for", "a", "crude", "local", "registry", "of", "all", "utilities", "local", "to", "this", "module", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L180-L193
train
45,858
calmjs/calmjs
src/calmjs/indexer.py
modpath_pkg_resources
def modpath_pkg_resources(module, entry_point): """ Goes through pkg_resources for compliance with various PEPs. This one accepts a module as argument. """ 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: if path: result.append(path) return result
python
def modpath_pkg_resources(module, entry_point): """ Goes through pkg_resources for compliance with various PEPs. This one accepts a module as argument. """ 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: if path: result.append(path) return result
[ "def", "modpath_pkg_resources", "(", "module", ",", "entry_point", ")", ":", "result", "=", "[", "]", "try", ":", "path", "=", "resource_filename_mod_entry_point", "(", "module", ".", "__name__", ",", "entry_point", ")", "except", "ImportError", ":", "logger", ...
Goes through pkg_resources for compliance with various PEPs. This one accepts a module as argument.
[ "Goes", "through", "pkg_resources", "for", "compliance", "with", "various", "PEPs", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L234-L251
train
45,859
calmjs/calmjs
src/calmjs/indexer.py
mapper_python
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. """ return mapper( module, entry_point=entry_point, modpath='pkg_resources', globber=globber, modname='python', fext=fext)
python
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. """ 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", ")", ":", "return", "mapper", "(", "module", ",", "entry_point", "=", "entry_point", ",", "modpath", "=", "'pkg_resources'", ",", "globber",...
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.
[ "Default", "mapper", "using", "python", "style", "globber" ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/indexer.py#L319-L329
train
45,860
weso/CWR-DataApi
cwr/other.py
_ThreePartsCode._printable_id_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 """ code = str(self.id_code) while len(code) < self._code_size: code = '0' + code return code
python
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 """ code = str(self.id_code) while len(code) < self._code_size: code = '0' + code return code
[ "def", "_printable_id_code", "(", "self", ")", ":", "code", "=", "str", "(", "self", ".", "id_code", ")", "while", "len", "(", "code", ")", "<", "self", ".", "_code_size", ":", "code", "=", "'0'", "+", "code", "return", "code" ]
Returns the code in a printable form, filling with zeros if needed. :return: the ID code in a printable form
[ "Returns", "the", "code", "in", "a", "printable", "form", "filling", "with", "zeros", "if", "needed", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/other.py#L39-L49
train
45,861
weso/CWR-DataApi
cwr/other.py
ISWCCode._printable_id_code
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 """ code = super(ISWCCode, self)._printable_id_code() code1 = code[:3] code2 = code[3:6] code3 = code[-3:] return '%s.%s.%s' % (code1, code2, code3)
python
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 """ 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", ")", ":", "code", "=", "super", "(", "ISWCCode", ",", "self", ")", ".", "_printable_id_code", "(", ")", "code1", "=", "code", "[", ":", "3", "]", "code2", "=", "code", "[", "3", ":", "6", "]", "code3", "=",...
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
[ "Returns", "the", "code", "in", "a", "printable", "form", "separating", "it", "into", "groups", "of", "three", "characters", "using", "a", "point", "between", "them", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/other.py#L128-L141
train
45,862
calmjs/calmjs
src/calmjs/vlqsm.py
SourceWriter.write
def write(self, s): """ Standard write, for standard sources part of the original file. """ 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() self.row = 1 self.col_current = 0 else: self.col_current += len(line) self.generated_col = self.col_last = len(line)
python
def write(self, s): """ Standard write, for standard sources part of the original file. """ 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() self.row = 1 self.col_current = 0 else: self.col_current += len(line) self.generated_col = self.col_last = len(line)
[ "def", "write", "(", "self", ",", "s", ")", ":", "lines", "=", "s", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", ":", "self", ".", "current_mapping", ".", "append", "(", "(", "self", ".", "generated_col", ",", "self", ".", "in...
Standard write, for standard sources part of the original file.
[ "Standard", "write", "for", "standard", "sources", "part", "of", "the", "original", "file", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/vlqsm.py#L73-L90
train
45,863
calmjs/calmjs
src/calmjs/vlqsm.py
SourceWriter.discard
def discard(self, s): """ Discard from original file. """ 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 level' ) self.warn = True else: # simply increment row self.row += 1
python
def discard(self, s): """ Discard from original file. """ 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 level' ) self.warn = True else: # simply increment row self.row += 1
[ "def", "discard", "(", "self", ",", "s", ")", ":", "lines", "=", "s", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", ":", "if", "line", "[", "-", "1", "]", "not", "in", "'\\r\\n'", ":", "if", "not", "self", ".", "warn", ":",...
Discard from original file.
[ "Discard", "from", "original", "file", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/vlqsm.py#L92-L108
train
45,864
calmjs/calmjs
src/calmjs/vlqsm.py
SourceWriter.write_padding
def write_padding(self, s): """ Write string that are not part of the original file. """ 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)
python
def write_padding(self, s): """ Write string that are not part of the original file. """ 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", ")", ":", "lines", "=", "s", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", ":", "self", ".", "stream", ".", "write", "(", "line", ")", "if", "line", "[", "-", "1", "]", "in", "...
Write string that are not part of the original file.
[ "Write", "string", "that", "are", "not", "part", "of", "the", "original", "file", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/vlqsm.py#L110-L122
train
45,865
Suor/django-easymoney
easymoney.py
format_currency
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``. """ 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 currency format type" % format_type) if force_frac is None: fractions = babel.core.get_global('currency_fractions') try: digits = fractions[currency][0] except KeyError: digits = fractions['DEFAULT'][0] frac = (digits, digits) else: frac = force_frac return pattern.apply(number, locale, currency=currency, force_frac=frac)
python
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``. """ 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 currency format type" % format_type) if force_frac is None: fractions = babel.core.get_global('currency_fractions') try: digits = fractions[currency][0] except KeyError: digits = fractions['DEFAULT'][0] frac = (digits, digits) else: frac = force_frac return pattern.apply(number, locale, currency=currency, force_frac=frac)
[ "def", "format_currency", "(", "number", ",", "currency", ",", "format", ",", "locale", "=", "babel", ".", "numbers", ".", "LC_NUMERIC", ",", "force_frac", "=", "None", ",", "format_type", "=", "'standard'", ")", ":", "locale", "=", "babel", ".", "core", ...
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``.
[ "Same", "as", "babel", ".", "numbers", ".", "format_currency", "but", "has", "force_frac", "argument", "instead", "of", "currency_digits", "." ]
c32d024a3c0e8d41f9f55e1f37ceea5e65c419e3
https://github.com/Suor/django-easymoney/blob/c32d024a3c0e8d41f9f55e1f37ceea5e65c419e3/easymoney.py#L52-L78
train
45,866
cihai/cihai
cihai/db.py
Database.reflect_db
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). """ self.metadata.reflect(views=True, extend_existing=True) self.base = automap_base(metadata=self.metadata) self.base.prepare()
python
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). """ self.metadata.reflect(views=True, extend_existing=True) self.base = automap_base(metadata=self.metadata) self.base.prepare()
[ "def", "reflect_db", "(", "self", ")", ":", "self", ".", "metadata", ".", "reflect", "(", "views", "=", "True", ",", "extend_existing", "=", "True", ")", "self", ".", "base", "=", "automap_base", "(", "metadata", "=", "self", ".", "metadata", ")", "sel...
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).
[ "No", "-", "op", "to", "reflect", "db", "info", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/db.py#L24-L33
train
45,867
favalex/python-asciimathml
asciimathml.py
trace_parser
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. """ 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_private(copy(n))) except Exception as e: return n def print_trace(*args): import sys sys.stderr.write(" " * tracing_level) for arg in args: sys.stderr.write(str(arg)) sys.stderr.write(' ') sys.stderr.write('\n') sys.stderr.flush() def wrapped(s, *args, **kwargs): global tracing_level print_trace(p.__name__, repr(s)) tracing_level += 1 s, n = p(s, *args, **kwargs) tracing_level -= 1 print_trace("-> ", repr(s), nodes_to_string(n)) return s, n return wrapped
python
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. """ 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_private(copy(n))) except Exception as e: return n def print_trace(*args): import sys sys.stderr.write(" " * tracing_level) for arg in args: sys.stderr.write(str(arg)) sys.stderr.write(' ') sys.stderr.write('\n') sys.stderr.flush() def wrapped(s, *args, **kwargs): global tracing_level print_trace(p.__name__, repr(s)) tracing_level += 1 s, n = p(s, *args, **kwargs) tracing_level -= 1 print_trace("-> ", repr(s), nodes_to_string(n)) return s, n return wrapped
[ "def", "trace_parser", "(", "p", ")", ":", "def", "nodes_to_string", "(", "n", ")", ":", "if", "isinstance", "(", "n", ",", "list", ")", ":", "result", "=", "'[ '", "for", "m", "in", "map", "(", "nodes_to_string", ",", "n", ")", ":", "result", "+="...
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.
[ "Decorator", "for", "tracing", "the", "parser", "." ]
d6b6740a143947452339a7829a18b55315574b2d
https://github.com/favalex/python-asciimathml/blob/d6b6740a143947452339a7829a18b55315574b2d/asciimathml.py#L157-L208
train
45,868
baccuslab/shannon
shannon/bottleneck.py
change_response
def change_response(x, prob, index): ''' 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)
python
def change_response(x, prob, index): ''' 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", ")", ":", "#pdb.set_trace()", "N", "=", "(", "x", "==", "index", ")", ".", "sum", "(", ")", "#x[x==index]=9", "x", "[", "x", "==", "index", "]", "=", "dist", ".", "sample", "(", "N", ...
change every response in x that matches 'index' by randomly sampling from prob
[ "change", "every", "response", "in", "x", "that", "matches", "index", "by", "randomly", "sampling", "from", "prob" ]
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/bottleneck.py#L31-L38
train
45,869
cihai/cihai
cihai/utils.py
merge_dict
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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ 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 isinstance(value, collections.Mapping): merged[key] = merge_dict(merged.get(key), value) else: merged[key] = value return merged
python
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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ 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 isinstance(value, collections.Mapping): merged[key] = merge_dict(merged.get(key), value) else: merged[key] = value return merged
[ "def", "merge_dict", "(", "base", ",", "additional", ")", ":", "if", "base", "is", "None", ":", "return", "additional", "if", "additional", "is", "None", ":", "return", "base", "if", "not", "(", "isinstance", "(", "base", ",", "collections", ".", "Mappin...
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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Combine", "two", "dictionary", "-", "like", "objects", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/utils.py#L14-L54
train
45,870
cihai/cihai
cihai/config.py
expand_config
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}`` would be replaced by the current PWD in the shell, ``${USER}`` would be the user running the app. *XDG variables* are expanded via :py:meth:`str.format`. These do not have a dollar sign. They are: - ``{user_cache_dir}`` - ``{user_config_dir}`` - ``{user_data_dir}`` - ``{user_log_dir}`` - ``{site_config_dir}`` - ``{site_data_dir}`` See Also -------- os.path.expanduser, os.path.expandvars : Standard library functions for expanding variables. Same concept, used inside. """ 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 in d.items(): if isinstance(v, dict): expand_config(v, dirs) if isinstance(v, string_types): d[k] = os.path.expanduser(os.path.expandvars(d[k])) d[k] = d[k].format(**context)
python
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}`` would be replaced by the current PWD in the shell, ``${USER}`` would be the user running the app. *XDG variables* are expanded via :py:meth:`str.format`. These do not have a dollar sign. They are: - ``{user_cache_dir}`` - ``{user_config_dir}`` - ``{user_data_dir}`` - ``{user_log_dir}`` - ``{site_config_dir}`` - ``{site_data_dir}`` See Also -------- os.path.expanduser, os.path.expandvars : Standard library functions for expanding variables. Same concept, used inside. """ 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 in d.items(): if isinstance(v, dict): expand_config(v, dirs) if isinstance(v, string_types): d[k] = os.path.expanduser(os.path.expandvars(d[k])) d[k] = d[k].format(**context)
[ "def", "expand_config", "(", "d", ",", "dirs", ")", ":", "context", "=", "{", "'user_cache_dir'", ":", "dirs", ".", "user_cache_dir", ",", "'user_config_dir'", ":", "dirs", ".", "user_config_dir", ",", "'user_data_dir'", ":", "dirs", ".", "user_data_dir", ",",...
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}`` would be replaced by the current PWD in the shell, ``${USER}`` would be the user running the app. *XDG variables* are expanded via :py:meth:`str.format`. These do not have a dollar sign. They are: - ``{user_cache_dir}`` - ``{user_config_dir}`` - ``{user_data_dir}`` - ``{user_log_dir}`` - ``{site_config_dir}`` - ``{site_data_dir}`` See Also -------- os.path.expanduser, os.path.expandvars : Standard library functions for expanding variables. Same concept, used inside.
[ "Expand", "configuration", "XDG", "variables", "environmental", "variables", "and", "tildes", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/config.py#L11-L57
train
45,871
cihai/cihai
cihai/data/unihan/bootstrap.py
bootstrap_unihan
def bootstrap_unihan(metadata, options={}): """Download, extract and import unihan to database.""" 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)
python
def bootstrap_unihan(metadata, options={}): """Download, extract and import unihan to database.""" 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", "=", "{", "}", ")", ":", "options", "=", "merge_dict", "(", "UNIHAN_ETL_DEFAULT_OPTIONS", ".", "copy", "(", ")", ",", "options", ")", "p", "=", "unihan", ".", "Packager", "(", "options", ")", "p...
Download, extract and import unihan to database.
[ "Download", "extract", "and", "import", "unihan", "to", "database", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/data/unihan/bootstrap.py#L13-L22
train
45,872
cihai/cihai
cihai/data/unihan/bootstrap.py
is_bootstrapped
def is_bootstrapped(metadata): """Return True if cihai is correctly bootstrapped.""" 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
python
def is_bootstrapped(metadata): """Return True if cihai is correctly bootstrapped.""" 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", ")", ":", "fields", "=", "UNIHAN_FIELDS", "+", "DEFAULT_COLUMNS", "if", "TABLE_NAME", "in", "metadata", ".", "tables", ".", "keys", "(", ")", ":", "table", "=", "metadata", ".", "tables", "[", "TABLE_NAME", "]", "...
Return True if cihai is correctly bootstrapped.
[ "Return", "True", "if", "cihai", "is", "correctly", "bootstrapped", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/data/unihan/bootstrap.py#L39-L50
train
45,873
namuyan/nem-ed25519
nem_ed25519/key.py
get_address
def get_address(pk, main_net=True, prefix=None): """ compute the nem-py address from the public one """ 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(prefix, bytes), 'Set prefix 1 bytes' body = prefix + ripe checksum = keccak_256(body).digest()[0:4] return b32encode(body + checksum).decode()
python
def get_address(pk, main_net=True, prefix=None): """ compute the nem-py address from the public one """ 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(prefix, bytes), 'Set prefix 1 bytes' body = prefix + ripe checksum = keccak_256(body).digest()[0:4] return b32encode(body + checksum).decode()
[ "def", "get_address", "(", "pk", ",", "main_net", "=", "True", ",", "prefix", "=", "None", ")", ":", "if", "isinstance", "(", "pk", ",", "str", ")", ":", "pk", "=", "unhexlify", "(", "pk", ".", "encode", "(", ")", ")", "assert", "len", "(", "pk",...
compute the nem-py address from the public one
[ "compute", "the", "nem", "-", "py", "address", "from", "the", "public", "one" ]
4f506a5335eb860a4cf1d102f76fcad93f9a55fc
https://github.com/namuyan/nem-ed25519/blob/4f506a5335eb860a4cf1d102f76fcad93f9a55fc/nem_ed25519/key.py#L39-L52
train
45,874
cihai/cihai
cihai/data/unihan/dataset.py
Unihan.lookup_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 """ Unihan = self.sql.base.classes.Unihan return self.sql.session.query(Unihan).filter_by(char=char)
python
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 """ Unihan = self.sql.base.classes.Unihan return self.sql.session.query(Unihan).filter_by(char=char)
[ "def", "lookup_char", "(", "self", ",", "char", ")", ":", "Unihan", "=", "self", ".", "sql", ".", "base", ".", "classes", ".", "Unihan", "return", "self", ".", "sql", ".", "session", ".", "query", "(", "Unihan", ")", ".", "filter_by", "(", "char", ...
Return character information from datasets. Parameters ---------- char : str character / string to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : list of matches
[ "Return", "character", "information", "from", "datasets", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/data/unihan/dataset.py#L17-L31
train
45,875
cihai/cihai
cihai/data/unihan/dataset.py
Unihan.reverse_char
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 """ 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]) )
python
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 """ 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", ")", ":", "if", "isinstance", "(", "hints", ",", "string_types", ")", ":", "hints", "=", "[", "hints", "]", "Unihan", "=", "self", ".", "sql", ".", "base", ".", "classes", ".", "Unihan", "columns", "=...
Return QuerySet of objects from SQLAlchemy of results. Parameters ---------- hints: list of str strings to lookup Returns ------- :class:`sqlalchemy.orm.query.Query` : reverse matches
[ "Return", "QuerySet", "of", "objects", "from", "SQLAlchemy", "of", "results", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/data/unihan/dataset.py#L33-L53
train
45,876
cihai/cihai
cihai/data/unihan/dataset.py
Unihan.with_fields
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 """ 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
python
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 """ 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", ")", ":", "Unihan", "=", "self", ".", "sql", ".", "base", ".", "classes", ".", "Unihan", "query", "=", "self", ".", "sql", ".", "session", ".", "query", "(", "Unihan", ")", "for", "field", "in"...
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
[ "Returns", "list", "of", "characters", "with", "information", "for", "certain", "fields", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/data/unihan/dataset.py#L55-L72
train
45,877
baccuslab/shannon
shannon/discrete.py
symbols_to_prob
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 ''' myCounter = Counter(symbols) N = float(len(list(symbols))) # symbols might be a zip object in python 3 for k in myCounter: myCounter[k] /= N return myCounter
python
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 ''' myCounter = Counter(symbols) N = float(len(list(symbols))) # symbols might be a zip object in python 3 for k in myCounter: myCounter[k] /= N return myCounter
[ "def", "symbols_to_prob", "(", "symbols", ")", ":", "myCounter", "=", "Counter", "(", "symbols", ")", "N", "=", "float", "(", "len", "(", "list", "(", "symbols", ")", ")", ")", "# symbols might be a zip object in python 3", "for", "k", "in", "myCounter", ":"...
Return a dict mapping symbols to probability. input: ----- symbols: iterable of hashable items works well if symbols is a zip of iterables
[ "Return", "a", "dict", "mapping", "symbols", "to", "probability", "." ]
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L52-L68
train
45,878
baccuslab/shannon
shannon/discrete.py
combine_symbols
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) z = combine_symbols(x,y) 2) combine a letter and a number s = 'abcd' x = numpy.random.randint(0,4,1000) y = [s[randint(4)] for i in range(1000)] z = combine_symbols(x,y) 3) suppose you are running an experiment and for each sample, you measure 3 different properties and you put the data into a 2d ndarray such that: samples_N, properties_N = data.shape and you want to combine all 3 different properties into just 1 symbol In this case you have to find a way to impute each property as an independent array combined_symbol = combine_symbols(*data.T) 4) if data from 3) is such that: properties_N, samples_N = data.shape then run: combined_symbol = combine_symbols(*data) ''' for arg in args: if len(arg)!=len(args[0]): raise ValueError("combine_symbols got inputs with different sizes") return tuple(zip(*args))
python
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) z = combine_symbols(x,y) 2) combine a letter and a number s = 'abcd' x = numpy.random.randint(0,4,1000) y = [s[randint(4)] for i in range(1000)] z = combine_symbols(x,y) 3) suppose you are running an experiment and for each sample, you measure 3 different properties and you put the data into a 2d ndarray such that: samples_N, properties_N = data.shape and you want to combine all 3 different properties into just 1 symbol In this case you have to find a way to impute each property as an independent array combined_symbol = combine_symbols(*data.T) 4) if data from 3) is such that: properties_N, samples_N = data.shape then run: combined_symbol = combine_symbols(*data) ''' for arg in args: if len(arg)!=len(args[0]): raise ValueError("combine_symbols got inputs with different sizes") return tuple(zip(*args))
[ "def", "combine_symbols", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "len", "(", "arg", ")", "!=", "len", "(", "args", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "\"combine_symbols got inputs with different sizes\"", ")", ...
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) z = combine_symbols(x,y) 2) combine a letter and a number s = 'abcd' x = numpy.random.randint(0,4,1000) y = [s[randint(4)] for i in range(1000)] z = combine_symbols(x,y) 3) suppose you are running an experiment and for each sample, you measure 3 different properties and you put the data into a 2d ndarray such that: samples_N, properties_N = data.shape and you want to combine all 3 different properties into just 1 symbol In this case you have to find a way to impute each property as an independent array combined_symbol = combine_symbols(*data.T) 4) if data from 3) is such that: properties_N, samples_N = data.shape then run: combined_symbol = combine_symbols(*data)
[ "Combine", "different", "symbols", "into", "a", "super", "-", "symbol" ]
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L71-L113
train
45,879
baccuslab/shannon
shannon/discrete.py
mi_chain_rule
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: terms of chaing rule Implemenation notes: I(X; y) = I(x0, x1, ..., xn; y) = I(x0; y) + I(x1;y | x0) + I(x2; y | x0, x1) + ... + I(xn; y | x0, x1, ..., xn-1) ''' # allocate ndarray output chain = np.zeros(len(X)) # first term in the expansion is not a conditional information, but the information between the first x and y chain[0] = mi(X[0], y) for i in range(1, len(X)): chain[i] = cond_mi(X[i], y, X[:i]) return chain
python
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: terms of chaing rule Implemenation notes: I(X; y) = I(x0, x1, ..., xn; y) = I(x0; y) + I(x1;y | x0) + I(x2; y | x0, x1) + ... + I(xn; y | x0, x1, ..., xn-1) ''' # allocate ndarray output chain = np.zeros(len(X)) # first term in the expansion is not a conditional information, but the information between the first x and y chain[0] = mi(X[0], y) for i in range(1, len(X)): chain[i] = cond_mi(X[i], y, X[:i]) return chain
[ "def", "mi_chain_rule", "(", "X", ",", "y", ")", ":", "# allocate ndarray output", "chain", "=", "np", ".", "zeros", "(", "len", "(", "X", ")", ")", "# first term in the expansion is not a conditional information, but the information between the first x and y", "chain", "...
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: terms of chaing rule Implemenation notes: I(X; y) = I(x0, x1, ..., xn; y) = I(x0; y) + I(x1;y | x0) + I(x2; y | x0, x1) + ... + I(xn; y | x0, x1, ..., xn-1)
[ "Decompose", "the", "information", "between", "all", "X", "and", "y", "according", "to", "the", "chain", "rule", "and", "return", "all", "the", "terms", "in", "the", "chain", "rule", "." ]
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L180-L208
train
45,880
baccuslab/shannon
shannon/discrete.py
KL_divergence
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. ''' assert(P.keys()==Q.keys()) distance = 0 for k in P.keys(): distance += P[k] * log(P[k]/Q[k]) return distance
python
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. ''' assert(P.keys()==Q.keys()) distance = 0 for k in P.keys(): distance += P[k] * log(P[k]/Q[k]) return distance
[ "def", "KL_divergence", "(", "P", ",", "Q", ")", ":", "assert", "(", "P", ".", "keys", "(", ")", "==", "Q", ".", "keys", "(", ")", ")", "distance", "=", "0", "for", "k", "in", "P", ".", "keys", "(", ")", ":", "distance", "+=", "P", "[", "k"...
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.
[ "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", "." ]
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L211-L224
train
45,881
baccuslab/shannon
shannon/discrete.py
bin
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: ----- x: signal to be binned, some sort of iterable bins: int, number of bins iterable, bin edges maxX: clips data above maxX minX: clips data below maxX output: ------ binnedX: x after being binned bins: bins used for binning. if input 'bins' is already an iterable it just returns the same iterable example: # make 10 bins of equal length spanning from x.min() to x.max() bin(x, 10) # use predefined bins such that each bin has the same number of points (maximize entropy) binsN = 10 percentiles = list(np.arange(0, 100.1, 100/binsN)) bins = np.percentile(x, percentiles) bin(x, bins) ''' if maxX is None: maxX = x.max() if minX is None: minX = x.min() if not np.iterable(bins): bins = np.linspace(minX, maxX+1e-5, bins+1) # digitize works on 1d array but not nd arrays. # So I pass the flattened version of x and then reshape back into x's original shape return np.digitize(x.ravel(), bins).reshape(x.shape), bins
python
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: ----- x: signal to be binned, some sort of iterable bins: int, number of bins iterable, bin edges maxX: clips data above maxX minX: clips data below maxX output: ------ binnedX: x after being binned bins: bins used for binning. if input 'bins' is already an iterable it just returns the same iterable example: # make 10 bins of equal length spanning from x.min() to x.max() bin(x, 10) # use predefined bins such that each bin has the same number of points (maximize entropy) binsN = 10 percentiles = list(np.arange(0, 100.1, 100/binsN)) bins = np.percentile(x, percentiles) bin(x, bins) ''' if maxX is None: maxX = x.max() if minX is None: minX = x.min() if not np.iterable(bins): bins = np.linspace(minX, maxX+1e-5, bins+1) # digitize works on 1d array but not nd arrays. # So I pass the flattened version of x and then reshape back into x's original shape return np.digitize(x.ravel(), bins).reshape(x.shape), bins
[ "def", "bin", "(", "x", ",", "bins", ",", "maxX", "=", "None", ",", "minX", "=", "None", ")", ":", "if", "maxX", "is", "None", ":", "maxX", "=", "x", ".", "max", "(", ")", "if", "minX", "is", "None", ":", "minX", "=", "x", ".", "min", "(", ...
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: ----- x: signal to be binned, some sort of iterable bins: int, number of bins iterable, bin edges maxX: clips data above maxX minX: clips data below maxX output: ------ binnedX: x after being binned bins: bins used for binning. if input 'bins' is already an iterable it just returns the same iterable example: # make 10 bins of equal length spanning from x.min() to x.max() bin(x, 10) # use predefined bins such that each bin has the same number of points (maximize entropy) binsN = 10 percentiles = list(np.arange(0, 100.1, 100/binsN)) bins = np.percentile(x, percentiles) bin(x, bins)
[ "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", ...
38abb4d9e53208ffd1c4149ef9fdf3abceccac48
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L227-L275
train
45,882
namuyan/nem-ed25519
nem_ed25519/utils.py
recover
def recover(y): """ given a value y, recover the preimage x """ p = (y*y - 1) * inverse(D*y*y + 1) x = powmod(p, (PRIME+3) // 8, PRIME) if (x*x - p) % PRIME != 0: i = powmod(2, (PRIME-1) // 4, PRIME) x = (x*i) % PRIME if x % 2 != 0: x = PRIME - x return x
python
def recover(y): """ given a value y, recover the preimage x """ p = (y*y - 1) * inverse(D*y*y + 1) x = powmod(p, (PRIME+3) // 8, PRIME) if (x*x - p) % PRIME != 0: i = powmod(2, (PRIME-1) // 4, PRIME) x = (x*i) % PRIME if x % 2 != 0: x = PRIME - x return x
[ "def", "recover", "(", "y", ")", ":", "p", "=", "(", "y", "*", "y", "-", "1", ")", "*", "inverse", "(", "D", "*", "y", "*", "y", "+", "1", ")", "x", "=", "powmod", "(", "p", ",", "(", "PRIME", "+", "3", ")", "//", "8", ",", "PRIME", "...
given a value y, recover the preimage x
[ "given", "a", "value", "y", "recover", "the", "preimage", "x" ]
4f506a5335eb860a4cf1d102f76fcad93f9a55fc
https://github.com/namuyan/nem-ed25519/blob/4f506a5335eb860a4cf1d102f76fcad93f9a55fc/nem_ed25519/utils.py#L263-L272
train
45,883
bmcfee/pyrubberband
pyrubberband/pyrb.py
time_stretch
def time_stretch(y, sr, rate, rbargs=None): '''Apply a time stretch of `rate` to an audio time series. This uses the `tempo` form for rubberband, so the higher the rate, the faster the playback. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` rate : float > 0 Desired playback rate. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `rate <= 0` ''' if rate <= 0: raise ValueError('rate must be strictly positive') if rate == 1.0: return y if rbargs is None: rbargs = dict() rbargs.setdefault('--tempo', rate) return __rubberband(y, sr, **rbargs)
python
def time_stretch(y, sr, rate, rbargs=None): '''Apply a time stretch of `rate` to an audio time series. This uses the `tempo` form for rubberband, so the higher the rate, the faster the playback. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` rate : float > 0 Desired playback rate. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `rate <= 0` ''' if rate <= 0: raise ValueError('rate must be strictly positive') if rate == 1.0: return y if rbargs is None: rbargs = dict() rbargs.setdefault('--tempo', rate) return __rubberband(y, sr, **rbargs)
[ "def", "time_stretch", "(", "y", ",", "sr", ",", "rate", ",", "rbargs", "=", "None", ")", ":", "if", "rate", "<=", "0", ":", "raise", "ValueError", "(", "'rate must be strictly positive'", ")", "if", "rate", "==", "1.0", ":", "return", "y", "if", "rbar...
Apply a time stretch of `rate` to an audio time series. This uses the `tempo` form for rubberband, so the higher the rate, the faster the playback. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` rate : float > 0 Desired playback rate. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `rate <= 0`
[ "Apply", "a", "time", "stretch", "of", "rate", "to", "an", "audio", "time", "series", "." ]
3644d1688be27e334b0b06744e7b1149eaea47e0
https://github.com/bmcfee/pyrubberband/blob/3644d1688be27e334b0b06744e7b1149eaea47e0/pyrubberband/pyrb.py#L97-L142
train
45,884
bmcfee/pyrubberband
pyrubberband/pyrb.py
timemap_stretch
def timemap_stretch(y, sr, time_map, rbargs=None): '''Apply a timemap stretch to an audio time series. A timemap stretch allows non-linear time-stretching by mapping source to target sample frame numbers for fixed time points within the audio data. This uses the `time` and `timemap` form for rubberband. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` time_map : list Each element is a tuple `t` of length 2 which corresponds to the source sample position and target sample position. If `t[1] < t[0]` the track will be sped up in this area. `time_map[-1]` must correspond to the lengths of the source audio and target audio. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `time_map` is not monotonic if `time_map` is not non-negative if `time_map[-1][0]` is not the input audio length ''' if rbargs is None: rbargs = dict() is_positive = all(time_map[i][0] >= 0 and time_map[i][1] >= 0 for i in range(len(time_map))) is_monotonic = all(time_map[i][0] <= time_map[i+1][0] and time_map[i][1] <= time_map[i+1][1] for i in range(len(time_map)-1)) if not is_positive: raise ValueError('time_map should be non-negative') if not is_monotonic: raise ValueError('time_map is not monotonic') if time_map[-1][0] != len(y): raise ValueError('time_map[-1] should correspond to the last sample') time_stretch = time_map[-1][1] * 1.0 / time_map[-1][0] rbargs.setdefault('--time', time_stretch) stretch_file = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) try: for t in time_map: stretch_file.write('{:0} {:1}\n'.format(t[0], t[1])) stretch_file.close() rbargs.setdefault('--timemap', stretch_file.name) y_stretch = __rubberband(y, sr, **rbargs) finally: # Remove temp file os.unlink(stretch_file.name) return y_stretch
python
def timemap_stretch(y, sr, time_map, rbargs=None): '''Apply a timemap stretch to an audio time series. A timemap stretch allows non-linear time-stretching by mapping source to target sample frame numbers for fixed time points within the audio data. This uses the `time` and `timemap` form for rubberband. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` time_map : list Each element is a tuple `t` of length 2 which corresponds to the source sample position and target sample position. If `t[1] < t[0]` the track will be sped up in this area. `time_map[-1]` must correspond to the lengths of the source audio and target audio. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `time_map` is not monotonic if `time_map` is not non-negative if `time_map[-1][0]` is not the input audio length ''' if rbargs is None: rbargs = dict() is_positive = all(time_map[i][0] >= 0 and time_map[i][1] >= 0 for i in range(len(time_map))) is_monotonic = all(time_map[i][0] <= time_map[i+1][0] and time_map[i][1] <= time_map[i+1][1] for i in range(len(time_map)-1)) if not is_positive: raise ValueError('time_map should be non-negative') if not is_monotonic: raise ValueError('time_map is not monotonic') if time_map[-1][0] != len(y): raise ValueError('time_map[-1] should correspond to the last sample') time_stretch = time_map[-1][1] * 1.0 / time_map[-1][0] rbargs.setdefault('--time', time_stretch) stretch_file = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) try: for t in time_map: stretch_file.write('{:0} {:1}\n'.format(t[0], t[1])) stretch_file.close() rbargs.setdefault('--timemap', stretch_file.name) y_stretch = __rubberband(y, sr, **rbargs) finally: # Remove temp file os.unlink(stretch_file.name) return y_stretch
[ "def", "timemap_stretch", "(", "y", ",", "sr", ",", "time_map", ",", "rbargs", "=", "None", ")", ":", "if", "rbargs", "is", "None", ":", "rbargs", "=", "dict", "(", ")", "is_positive", "=", "all", "(", "time_map", "[", "i", "]", "[", "0", "]", ">...
Apply a timemap stretch to an audio time series. A timemap stretch allows non-linear time-stretching by mapping source to target sample frame numbers for fixed time points within the audio data. This uses the `time` and `timemap` form for rubberband. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` time_map : list Each element is a tuple `t` of length 2 which corresponds to the source sample position and target sample position. If `t[1] < t[0]` the track will be sped up in this area. `time_map[-1]` must correspond to the lengths of the source audio and target audio. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_stretch : np.ndarray Time-stretched audio Raises ------ ValueError if `time_map` is not monotonic if `time_map` is not non-negative if `time_map[-1][0]` is not the input audio length
[ "Apply", "a", "timemap", "stretch", "to", "an", "audio", "time", "series", "." ]
3644d1688be27e334b0b06744e7b1149eaea47e0
https://github.com/bmcfee/pyrubberband/blob/3644d1688be27e334b0b06744e7b1149eaea47e0/pyrubberband/pyrb.py#L145-L221
train
45,885
bmcfee/pyrubberband
pyrubberband/pyrb.py
pitch_shift
def pitch_shift(y, sr, n_steps, rbargs=None): '''Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_steps` semitones. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_shift : np.ndarray Pitch-shifted audio ''' if n_steps == 0: return y if rbargs is None: rbargs = dict() rbargs.setdefault('--pitch', n_steps) return __rubberband(y, sr, **rbargs)
python
def pitch_shift(y, sr, n_steps, rbargs=None): '''Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_steps` semitones. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_shift : np.ndarray Pitch-shifted audio ''' if n_steps == 0: return y if rbargs is None: rbargs = dict() rbargs.setdefault('--pitch', n_steps) return __rubberband(y, sr, **rbargs)
[ "def", "pitch_shift", "(", "y", ",", "sr", ",", "n_steps", ",", "rbargs", "=", "None", ")", ":", "if", "n_steps", "==", "0", ":", "return", "y", "if", "rbargs", "is", "None", ":", "rbargs", "=", "dict", "(", ")", "rbargs", ".", "setdefault", "(", ...
Apply a pitch shift to an audio time series. Parameters ---------- y : np.ndarray [shape=(n,) or (n, c)] Audio time series, either single or multichannel sr : int > 0 Sampling rate of `y` n_steps : float Shift by `n_steps` semitones. rbargs Additional keyword parameters for rubberband See `rubberband -h` for details. Returns ------- y_shift : np.ndarray Pitch-shifted audio
[ "Apply", "a", "pitch", "shift", "to", "an", "audio", "time", "series", "." ]
3644d1688be27e334b0b06744e7b1149eaea47e0
https://github.com/bmcfee/pyrubberband/blob/3644d1688be27e334b0b06744e7b1149eaea47e0/pyrubberband/pyrb.py#L224-L257
train
45,886
cihai/cihai
cihai/conversion.py
python_to_ucn
def python_to_ucn(uni_char, as_bytes=False): """ Return UCN character from Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding Unicode UCN ('U+4E00'). """ ucn = uni_char.encode('unicode_escape').decode('latin1') ucn = text_type(ucn).replace('\\', '').upper().lstrip('U') if len(ucn) > int(4): # get rid of the zeroes that Python uses to pad 32 byte UCNs ucn = ucn.lstrip("0") ucn = "U+" + ucn.upper() if as_bytes: ucn = ucn.encode('latin1') return ucn
python
def python_to_ucn(uni_char, as_bytes=False): """ Return UCN character from Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding Unicode UCN ('U+4E00'). """ ucn = uni_char.encode('unicode_escape').decode('latin1') ucn = text_type(ucn).replace('\\', '').upper().lstrip('U') if len(ucn) > int(4): # get rid of the zeroes that Python uses to pad 32 byte UCNs ucn = ucn.lstrip("0") ucn = "U+" + ucn.upper() if as_bytes: ucn = ucn.encode('latin1') return ucn
[ "def", "python_to_ucn", "(", "uni_char", ",", "as_bytes", "=", "False", ")", ":", "ucn", "=", "uni_char", ".", "encode", "(", "'unicode_escape'", ")", ".", "decode", "(", "'latin1'", ")", "ucn", "=", "text_type", "(", "ucn", ")", ".", "replace", "(", "...
Return UCN character from Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding Unicode UCN ('U+4E00').
[ "Return", "UCN", "character", "from", "Python", "Unicode", "character", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/conversion.py#L196-L213
train
45,887
cihai/cihai
cihai/conversion.py
python_to_euc
def python_to_euc(uni_char, as_bytes=False): """ Return EUC character from a Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding EUC hex ('d2bb'). """ euc = repr(uni_char.encode("gb2312"))[1:-1].replace("\\x", "").strip("'") if as_bytes: euc = euc.encode('utf-8') assert isinstance(euc, bytes) return euc
python
def python_to_euc(uni_char, as_bytes=False): """ Return EUC character from a Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding EUC hex ('d2bb'). """ euc = repr(uni_char.encode("gb2312"))[1:-1].replace("\\x", "").strip("'") if as_bytes: euc = euc.encode('utf-8') assert isinstance(euc, bytes) return euc
[ "def", "python_to_euc", "(", "uni_char", ",", "as_bytes", "=", "False", ")", ":", "euc", "=", "repr", "(", "uni_char", ".", "encode", "(", "\"gb2312\"", ")", ")", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "\"\\\\x\"", ",", "\"\"", ")", "."...
Return EUC character from a Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding EUC hex ('d2bb').
[ "Return", "EUC", "character", "from", "a", "Python", "Unicode", "character", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/conversion.py#L216-L229
train
45,888
cihai/cihai
cihai/conversion.py
ucnstring_to_unicode
def ucnstring_to_unicode(ucn_string): """Return ucnstring as Unicode.""" ucn_string = ucnstring_to_python(ucn_string).decode('utf-8') assert isinstance(ucn_string, text_type) return ucn_string
python
def ucnstring_to_unicode(ucn_string): """Return ucnstring as Unicode.""" ucn_string = ucnstring_to_python(ucn_string).decode('utf-8') assert isinstance(ucn_string, text_type) return ucn_string
[ "def", "ucnstring_to_unicode", "(", "ucn_string", ")", ":", "ucn_string", "=", "ucnstring_to_python", "(", "ucn_string", ")", ".", "decode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "ucn_string", ",", "text_type", ")", "return", "ucn_string" ]
Return ucnstring as Unicode.
[ "Return", "ucnstring", "as", "Unicode", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/conversion.py#L232-L237
train
45,889
cihai/cihai
cihai/conversion.py
parse_var
def parse_var(var): """ Returns a tuple consisting of a string and a tag, or None, if none is specified. """ bits = var.split("<", 1) if len(bits) < 2: tag = None else: tag = bits[1] return ucn_to_unicode(bits[0]), tag
python
def parse_var(var): """ Returns a tuple consisting of a string and a tag, or None, if none is specified. """ bits = var.split("<", 1) if len(bits) < 2: tag = None else: tag = bits[1] return ucn_to_unicode(bits[0]), tag
[ "def", "parse_var", "(", "var", ")", ":", "bits", "=", "var", ".", "split", "(", "\"<\"", ",", "1", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "tag", "=", "None", "else", ":", "tag", "=", "bits", "[", "1", "]", "return", "ucn_to_unicode...
Returns a tuple consisting of a string and a tag, or None, if none is specified.
[ "Returns", "a", "tuple", "consisting", "of", "a", "string", "and", "a", "tag", "or", "None", "if", "none", "is", "specified", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/conversion.py#L255-L265
train
45,890
cihai/cihai
cihai/core.py
Cihai.from_file
def from_file(cls, config_path=None, *args, **kwargs): """ Create a Cihai instance from a JSON or YAML config. Parameters ---------- config_path : str, optional path to custom config file Returns ------- :class:`Cihai` : application object """ config_reader = kaptan.Kaptan() config = {} if config_path: if not os.path.exists(config_path): raise exc.CihaiException( '{0} does not exist.'.format(os.path.abspath(config_path)) ) if not any( config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini') ): raise exc.CihaiException( '{0} does not have a yaml,yml,json,ini extend.'.format( os.path.abspath(config_path) ) ) else: custom_config = config_reader.import_config(config_path).get() config = merge_dict(config, custom_config) return cls(config)
python
def from_file(cls, config_path=None, *args, **kwargs): """ Create a Cihai instance from a JSON or YAML config. Parameters ---------- config_path : str, optional path to custom config file Returns ------- :class:`Cihai` : application object """ config_reader = kaptan.Kaptan() config = {} if config_path: if not os.path.exists(config_path): raise exc.CihaiException( '{0} does not exist.'.format(os.path.abspath(config_path)) ) if not any( config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini') ): raise exc.CihaiException( '{0} does not have a yaml,yml,json,ini extend.'.format( os.path.abspath(config_path) ) ) else: custom_config = config_reader.import_config(config_path).get() config = merge_dict(config, custom_config) return cls(config)
[ "def", "from_file", "(", "cls", ",", "config_path", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "config_reader", "=", "kaptan", ".", "Kaptan", "(", ")", "config", "=", "{", "}", "if", "config_path", ":", "if", "not", "os", "."...
Create a Cihai instance from a JSON or YAML config. Parameters ---------- config_path : str, optional path to custom config file Returns ------- :class:`Cihai` : application object
[ "Create", "a", "Cihai", "instance", "from", "a", "JSON", "or", "YAML", "config", "." ]
43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/core.py#L114-L150
train
45,891
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTxSync._process_locale
def _process_locale(self, locale): """Return True if this locale should be processed.""" if locale.lower().startswith('en'): return False return (locale in self.enabled_locales or self.reverse_locale_map.get(locale.lower(), None) in self.enabled_locales or locale in self.lower_locales or self.reverse_locale_map.get(locale.lower(), None) in self.lower_locales )
python
def _process_locale(self, locale): """Return True if this locale should be processed.""" if locale.lower().startswith('en'): return False return (locale in self.enabled_locales or self.reverse_locale_map.get(locale.lower(), None) in self.enabled_locales or locale in self.lower_locales or self.reverse_locale_map.get(locale.lower(), None) in self.lower_locales )
[ "def", "_process_locale", "(", "self", ",", "locale", ")", ":", "if", "locale", ".", "lower", "(", ")", ".", "startswith", "(", "'en'", ")", ":", "return", "False", "return", "(", "locale", "in", "self", ".", "enabled_locales", "or", "self", ".", "reve...
Return True if this locale should be processed.
[ "Return", "True", "if", "this", "locale", "should", "be", "processed", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L42-L57
train
45,892
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTxSync.desk_locale
def desk_locale(self, locale): """Return the Desk-style locale for locale.""" locale = locale.lower().replace('-', '_') return self.vendor_locale_map.get(locale, locale)
python
def desk_locale(self, locale): """Return the Desk-style locale for locale.""" locale = locale.lower().replace('-', '_') return self.vendor_locale_map.get(locale, locale)
[ "def", "desk_locale", "(", "self", ",", "locale", ")", ":", "locale", "=", "locale", ".", "lower", "(", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", "return", "self", ".", "vendor_locale_map", ".", "get", "(", "locale", ",", "locale", ")" ]
Return the Desk-style locale for locale.
[ "Return", "the", "Desk", "-", "style", "locale", "for", "locale", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L59-L63
train
45,893
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTopics.push
def push(self): """Push topics to Transifex.""" tx = Tx(self.tx_project_slug) # asssemble the template catalog template = babel.messages.catalog.Catalog() for topic in self.desk.topics(): if topic.show_in_portal: template.add(topic.name) # serialize the catalog as a PO file template_po = StringIO() babel.messages.pofile.write_po(template_po, template) # upload/update the catalog resource tx.create_or_update_resource( self.TOPIC_STRINGS_SLUG, DEFAULT_SOURCE_LANGUAGE, "Help Center Topics", template_po.getvalue(), i18n_type='PO', project_slug=self.tx_project_slug, )
python
def push(self): """Push topics to Transifex.""" tx = Tx(self.tx_project_slug) # asssemble the template catalog template = babel.messages.catalog.Catalog() for topic in self.desk.topics(): if topic.show_in_portal: template.add(topic.name) # serialize the catalog as a PO file template_po = StringIO() babel.messages.pofile.write_po(template_po, template) # upload/update the catalog resource tx.create_or_update_resource( self.TOPIC_STRINGS_SLUG, DEFAULT_SOURCE_LANGUAGE, "Help Center Topics", template_po.getvalue(), i18n_type='PO', project_slug=self.tx_project_slug, )
[ "def", "push", "(", "self", ")", ":", "tx", "=", "Tx", "(", "self", ".", "tx_project_slug", ")", "# asssemble the template catalog", "template", "=", "babel", ".", "messages", ".", "catalog", ".", "Catalog", "(", ")", "for", "topic", "in", "self", ".", "...
Push topics to Transifex.
[ "Push", "topics", "to", "Transifex", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L191-L214
train
45,894
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTopics.pull
def pull(self): """Pull topics from Transifex.""" topic_stats = txlib.api.statistics.Statistics.get( project_slug=self.tx_project_slug, resource_slug=self.TOPIC_STRINGS_SLUG, ) translated = {} # for each language for locale in self.enabled_locales: if not self._process_locale(locale): continue locale_stats = getattr(topic_stats, locale, None) if locale_stats is None: self.log.debug('Locale %s not present when pulling topics.' % (locale,)) continue if locale_stats['completed'] == '100%': # get the resource from Tx translation = txlib.api.translations.Translation.get( project_slug=self.tx_project_slug, slug=self.TOPIC_STRINGS_SLUG, lang=locale, ) translated[locale] = babel.messages.pofile.read_po( StringIO(translation.content.encode('utf-8')) ) # now that we've pulled everything from Tx, upload to Desk for topic in self.desk.topics(): for locale in translated: if topic.name in translated[locale]: self.log.debug( 'Updating topic (%s) for locale (%s)' % (topic.name, locale), ) if locale in topic.translations: topic.translations[locale].update( name=translated[locale][topic.name].string, ) else: topic.translations.create( locale=locale, name=translated[locale][topic.name].string, ) else: self.log.error( 'Topic name (%s) does not exist in locale (%s)' % (topic['name'], locale), )
python
def pull(self): """Pull topics from Transifex.""" topic_stats = txlib.api.statistics.Statistics.get( project_slug=self.tx_project_slug, resource_slug=self.TOPIC_STRINGS_SLUG, ) translated = {} # for each language for locale in self.enabled_locales: if not self._process_locale(locale): continue locale_stats = getattr(topic_stats, locale, None) if locale_stats is None: self.log.debug('Locale %s not present when pulling topics.' % (locale,)) continue if locale_stats['completed'] == '100%': # get the resource from Tx translation = txlib.api.translations.Translation.get( project_slug=self.tx_project_slug, slug=self.TOPIC_STRINGS_SLUG, lang=locale, ) translated[locale] = babel.messages.pofile.read_po( StringIO(translation.content.encode('utf-8')) ) # now that we've pulled everything from Tx, upload to Desk for topic in self.desk.topics(): for locale in translated: if topic.name in translated[locale]: self.log.debug( 'Updating topic (%s) for locale (%s)' % (topic.name, locale), ) if locale in topic.translations: topic.translations[locale].update( name=translated[locale][topic.name].string, ) else: topic.translations.create( locale=locale, name=translated[locale][topic.name].string, ) else: self.log.error( 'Topic name (%s) does not exist in locale (%s)' % (topic['name'], locale), )
[ "def", "pull", "(", "self", ")", ":", "topic_stats", "=", "txlib", ".", "api", ".", "statistics", ".", "Statistics", ".", "get", "(", "project_slug", "=", "self", ".", "tx_project_slug", ",", "resource_slug", "=", "self", ".", "TOPIC_STRINGS_SLUG", ",", ")...
Pull topics from Transifex.
[ "Pull", "topics", "from", "Transifex", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L216-L276
train
45,895
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTutorials.parse_resource_document
def parse_resource_document(self, content): """Return a dict with the keys title, content, tags for content.""" content = content.strip() if not content.startswith('<html>'): # this is not a full HTML doc, probably content w/o title, tags, etc return dict(body=content) result = {} if '<title>' in content and '</title>' in content: result['subject'] = content[content.find('<title>') + 7:content.find('</title>')].strip() result['body'] = content[content.find('<body>') + 6:content.find('</body>')].strip() return result
python
def parse_resource_document(self, content): """Return a dict with the keys title, content, tags for content.""" content = content.strip() if not content.startswith('<html>'): # this is not a full HTML doc, probably content w/o title, tags, etc return dict(body=content) result = {} if '<title>' in content and '</title>' in content: result['subject'] = content[content.find('<title>') + 7:content.find('</title>')].strip() result['body'] = content[content.find('<body>') + 6:content.find('</body>')].strip() return result
[ "def", "parse_resource_document", "(", "self", ",", "content", ")", ":", "content", "=", "content", ".", "strip", "(", ")", "if", "not", "content", ".", "startswith", "(", "'<html>'", ")", ":", "# this is not a full HTML doc, probably content w/o title, tags, etc", ...
Return a dict with the keys title, content, tags for content.
[ "Return", "a", "dict", "with", "the", "keys", "title", "content", "tags", "for", "content", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L311-L325
train
45,896
eventbrite/localization_shuttle
src/shuttle/sync.py
DeskTutorials.push
def push(self): """Push tutorials to Transifex.""" tx = Tx(self.tx_project_slug) if self.options.resources: articles = [ self.desk.articles().by_id(r.strip()) for r in self.options.resources.split(',') ] else: articles = self.desk.articles() for a in articles: self.log.debug( 'Inspecting Desk resource %s', a.api_href ) for translation in a.translations.items().values(): our_locale = self.desk_to_our_locale(translation.locale) self.log.debug('Checking locale %s', translation.locale) if not self._process_locale(translation.locale): self.log.debug('Skipping locale.') continue # make sure the project exists in Tx tx.get_project(our_locale) a_id = a.api_href.rsplit('/', 1)[1] if (self.options.force or not tx.resource_exists(a_id, our_locale) or translation.outdated ): self.log.info('Resource %(id)s out of date in %(locale)s; updating.' % {'id': a_id, 'locale': our_locale, }, ) tx.create_or_update_resource( a_id, our_locale, self.make_resource_title(a), self.make_resource_document(a.subject, a.body), )
python
def push(self): """Push tutorials to Transifex.""" tx = Tx(self.tx_project_slug) if self.options.resources: articles = [ self.desk.articles().by_id(r.strip()) for r in self.options.resources.split(',') ] else: articles = self.desk.articles() for a in articles: self.log.debug( 'Inspecting Desk resource %s', a.api_href ) for translation in a.translations.items().values(): our_locale = self.desk_to_our_locale(translation.locale) self.log.debug('Checking locale %s', translation.locale) if not self._process_locale(translation.locale): self.log.debug('Skipping locale.') continue # make sure the project exists in Tx tx.get_project(our_locale) a_id = a.api_href.rsplit('/', 1)[1] if (self.options.force or not tx.resource_exists(a_id, our_locale) or translation.outdated ): self.log.info('Resource %(id)s out of date in %(locale)s; updating.' % {'id': a_id, 'locale': our_locale, }, ) tx.create_or_update_resource( a_id, our_locale, self.make_resource_title(a), self.make_resource_document(a.subject, a.body), )
[ "def", "push", "(", "self", ")", ":", "tx", "=", "Tx", "(", "self", ".", "tx_project_slug", ")", "if", "self", ".", "options", ".", "resources", ":", "articles", "=", "[", "self", ".", "desk", ".", "articles", "(", ")", ".", "by_id", "(", "r", "....
Push tutorials to Transifex.
[ "Push", "tutorials", "to", "Transifex", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/sync.py#L338-L385
train
45,897
eventbrite/localization_shuttle
src/shuttle/transifex.py
Tx.get_project
def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs): """ Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_code: The language of the original untranslated content (i.e. Spanish), defaults to DEFAULT_SOURCE_LANGUAGE, which is English :type source_language_code: string, optional :return: The Transifex project to which resources can be pushed or pulled :rtype: project.Project """ try: locale_project = project.Project.get(slug=self.get_project_slug(locale)) except NotFoundError: locale_project = project.Project( slug=self.get_project_slug(locale), ) defaults = { 'name': 'Help Center (%s)' % (locale, ), 'description': 'Help Center pages to translate to %s' % ( locale, ), 'source_language_code': source_language_code, 'private': True, } valid_keys = ('name','description') defaults.update( dict((k,v) for k,v in kwargs.iteritems() if k in valid_keys) ) for k,v in defaults.iteritems(): setattr(locale_project, k, v) locale_project.save() return locale_project
python
def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs): """ Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_code: The language of the original untranslated content (i.e. Spanish), defaults to DEFAULT_SOURCE_LANGUAGE, which is English :type source_language_code: string, optional :return: The Transifex project to which resources can be pushed or pulled :rtype: project.Project """ try: locale_project = project.Project.get(slug=self.get_project_slug(locale)) except NotFoundError: locale_project = project.Project( slug=self.get_project_slug(locale), ) defaults = { 'name': 'Help Center (%s)' % (locale, ), 'description': 'Help Center pages to translate to %s' % ( locale, ), 'source_language_code': source_language_code, 'private': True, } valid_keys = ('name','description') defaults.update( dict((k,v) for k,v in kwargs.iteritems() if k in valid_keys) ) for k,v in defaults.iteritems(): setattr(locale_project, k, v) locale_project.save() return locale_project
[ "def", "get_project", "(", "self", ",", "locale", ",", "source_language_code", "=", "DEFAULT_SOURCE_LANGUAGE", ",", "*", "*", "kwargs", ")", ":", "try", ":", "locale_project", "=", "project", ".", "Project", ".", "get", "(", "slug", "=", "self", ".", "get_...
Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_code: The language of the original untranslated content (i.e. Spanish), defaults to DEFAULT_SOURCE_LANGUAGE, which is English :type source_language_code: string, optional :return: The Transifex project to which resources can be pushed or pulled :rtype: project.Project
[ "Gets", "or", "creates", "the", "Transifex", "project", "for", "the", "current", "project", "prefix", "and", "locale" ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/transifex.py#L34-L75
train
45,898
eventbrite/localization_shuttle
src/shuttle/transifex.py
Tx.translation_exists
def translation_exists(self, slug, lang): """Return True if the translation exists for this slug.""" try: return translations.Translation.get( project_slug=self.get_project_slug(lang), slug=slug, lang=lang, ) except (NotFoundError, RemoteServerError): pass return False
python
def translation_exists(self, slug, lang): """Return True if the translation exists for this slug.""" try: return translations.Translation.get( project_slug=self.get_project_slug(lang), slug=slug, lang=lang, ) except (NotFoundError, RemoteServerError): pass return False
[ "def", "translation_exists", "(", "self", ",", "slug", ",", "lang", ")", ":", "try", ":", "return", "translations", ".", "Translation", ".", "get", "(", "project_slug", "=", "self", ".", "get_project_slug", "(", "lang", ")", ",", "slug", "=", "slug", ","...
Return True if the translation exists for this slug.
[ "Return", "True", "if", "the", "translation", "exists", "for", "this", "slug", "." ]
1e97e313b0dd75244d84eaa6e7a5fa63ee375e68
https://github.com/eventbrite/localization_shuttle/blob/1e97e313b0dd75244d84eaa6e7a5fa63ee375e68/src/shuttle/transifex.py#L143-L156
train
45,899