output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def save(self): """ Attempts to move the nodes using the selected target and position. If an invalid move is attempted, the related error message will be added to the form's non-field errors and the error will be re-raised. Callers should attempt to catch ``InvalidMove``...
Can you write a function in Python 3 where it saves the current state of the current state of the current node to the selected target and the current position.
You are a Python code generator, capable of creating scripts from specifications.
def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: storage.delete(storage_name) ...
Write a Python 3 function that can delete the selected files from storage and saves the result to self. success_files and self. error_files.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of all the file nodes that are merged into one.
Given the following Python 3 function, write the documentation def get_merged_filenode_list(nodes, filter_media_types=None, exclude_media_types=None, filter=None, ordering=None, processors=None, max_depth=None, max_nodes=None): return __get_filenode_list(nodes, filter_media_types=filter_media_types, exclude_media_t...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''): """ Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. """ link_text = None if use_meta...
Create a Python 3 function to return a formatted HTML link tag to the FileNode s file optionally including some meta information about the file.
As a python code expert, you are capable of creating scripts from specifications.
def delete_selected_tree(self, modeladmin, request, queryset): """ Deletes multiple instances and makes sure the MPTT fields get recalculated properly. (Because merely doing a bulk delete doesn't trigger the post_delete hooks.) """ # If the user has not yet confirmed the deletion...
Write a Python 3 script for deleting selected items from the tree.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a normalized canonical target name for the target_name build_module.
Here you have a function in Python 3, explain what it does def norm_name(build_module: str, target_name: str): if ':' not in target_name: raise ValueError( "Must provide fully-qualified target name (with `:') to avoid " "possible ambiguity - `{}' not valid".format(target_name)) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Expand a target selector into a normalized target name.
Can you tell what is the following Python 3 function doing def expand_target_selector(target_selector: str, conf: Config): if target_selector == '**:*': return target_selector if ':' not in target_selector: target_selector += ':*' build_module, target_name = split(target_selector) build_...
As a Python code analyst, you investigate and solve complex coding mysteries
Return sorted hashes of targets.
Can you generate a brief explanation for the following Python 3 code def hashify_targets(targets: list, build_context) -> list: return sorted(build_context.targets[target_name].hash(build_context) for target_name in listify(targets))
As a Python code analyst, you investigate and solve complex coding mysteries
def hashify_files(files: list) -> dict: """Return mapping from file path to file hash.""" return {filepath.replace('\\', '/'): hash_tree(filepath) for filepath in listify(files)}
Implement a function in Python 3 to return mapping from file path to file hash.
You are a Python code architect, reviewing and designing scalable and efficient code
def process_prop(prop_type: PT, value, build_context): """Return a cachable representation of the prop `value` given its type.""" if prop_type in (PT.Target, PT.TargetList): return hashify_targets(value, build_context) elif prop_type in (PT.File, PT.FileList): return hashify_files(value) ...
Write a Python 3 script for returning a cachable representation of the prop value given its type.
You are a Python code architect, reviewing and designing scalable and efficient code
def compute_json(self, build_context): """Compute and store a JSON serialization of this target for caching purposes. The serialization includes: - The build flavor - The builder name - Target tags - Hashes of target dependencies & buildenv - Processed...
Can you implement a function in Python 3 that computes and store a JSON serialization of this target for caching purposes.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the JSON representation of this target for caching purposes.
Given the following Python 3 function, write the documentation def json(self, build_context) -> str: if self._json is None: self.compute_json(build_context) return self._json
As a python code expert, you are capable of creating scripts from specifications.
def compute_hash(self, build_context): """Compute and store the hash of this target for caching purposes. The hash is computed over the target JSON representation. """ m = md5() m.update(self.json(build_context).encode('utf8')) self._hash = m.hexdigest() m = md5(...
Write a Python 3 script to compute and store the hash of this target for caching purposes.
As a Python code composer, you craft elegant and concise scripts.
Return the hash of this target for caching purposes.
Given the following Python 3 function, write the documentation def hash(self, build_context) -> str: if self._hash is None: self.compute_hash(build_context) return self._hash
As a python code expert, you are capable of creating scripts from specifications.
def handle_build_cache( conf: Config, name: str, tag: str, icb: ImageCachingBehavior): """Handle Docker image build cache. Return image ID if image is cached, and there's no need to redo the build. Return None if need to build the image (whether cached locally or not). Raise RuntimeError if not...
How would you code a function in Python 3 to handle Docker image build cache.
You are a Python code generator, capable of creating scripts from specifications.
Build a Docker image and return a tuple of
How would you explain what the following Python 3 function does def build_docker_image( build_context, name: str, tag: str, base_image, deps: list=None, env: dict=None, work_dir: str=None, entrypoint: list=None, cmd: list=None, full_path_cmd: bool=False, distro: dict=None, image_caching_...
You are a Python code generator, capable of creating scripts from specifications.
def add_stream_handler(logger, stream): """Add a brace-handler stream-handler using `stream` to `logger`.""" handler = logging.StreamHandler(stream=stream) # Using Brace Formatter (see # https://docs.python.org/3.5/howto/logging-cookbook.html#use-of-alternative-formatting-styles) formatter = logging...
Create a Python 3 function to add a brace - handler using stream to logger.
As a Python code translator, you convert algorithms and pseudocode into Python.
def configure_logging(conf): """Initialize and configure logging.""" root_logger = logging.getLogger() root_logger.setLevel(getattr(logging, conf.loglevel.upper())) if conf.logtostderr: add_stream_handler(root_logger, sys.stderr) if conf.logtostdout: add_stream_handler(root_logger, s...
Write a Python 3 script for initializing and configure logging.
You are a Python code analyst, evaluating scripts for potential improvements.
def iglob(pathname, *, recursive=False): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns...
Create a Python 3 function to return an iterator which yields the paths matching a pathname pattern.
You are a Python code architect, reviewing and designing scalable and efficient code
Register a builder signature & docstring for the builder_name.
How would you explain what the following Python 3 function does def register_sig(self, builder_name: str, sig: list, docstring: str, cachable: bool=True, attempts=1): """Register a builder signature & docstring for `builder_name`. The input for the builder signature is a list of "s...
You are a Python code analyst, evaluating scripts for potential improvements.
Remove a registered builder.
Can you generate the documentation for the following Python 3 function def remove_builder(cls, builder_name: str): cls.builders.pop(builder_name, None) for hook_spec in cls.hooks.values(): hook_spec.pop(builder_name, None)
As a Python code analyst, you investigate and solve complex coding mysteries
Return a normalized build module name for build_file_path.
Can you generate the documentation for the following Python 3 function def to_build_module(build_file_path: str, conf: Config) -> str: build_file = Path(build_file_path) root = Path(conf.project_root) return build_file.resolve().relative_to(root).parent.as_posix().strip('.')
As a Python code analyst, you investigate and solve complex coding mysteries
def cmd_version(unused_conf): """Print out version information about YABT and detected builders.""" import pkg_resources print('This is {} version {}, imported from {}' .format(__oneliner__, __version__, __file__)) if len(Plugin.builders) > 0: print('setuptools registered builders:') ...
Write a Python 3 function for printing out version information about YABT and detected builders.
As a Python code translator, you convert algorithms and pseudocode into Python.
def cmd_list(unused_conf: Config): """Print out information on loaded builders and hooks.""" for name, builder in sorted(Plugin.builders.items()): if builder.func: print('+- {0:16s} implemented in {1.__module__}.{1.__name__}()' .format(name, builder.func)) else: ...
Implement a function in Python 3 to print out information on loaded builders and hooks.
You are a Python code architect, reviewing and designing scalable and efficient code
def cmd_build(conf: Config, run_tests: bool=False): """Build requested targets, and their dependencies.""" build_context = BuildContext(conf) populate_targets_graph(build_context, conf) build_context.build_graph(run_tests=run_tests) build_context.write_artifacts_metadata()
Create a Python 3 function to build requested targets and their dependencies.
As a python code expert, you are capable of creating scripts from specifications.
def cmd_dot(conf: Config): """Print out a neat targets dependency tree based on requested targets. Use graphviz to render the dot file, e.g.: > ybt dot :foo :bar | dot -Tpng -o graph.png """ build_context = BuildContext(conf) populate_targets_graph(build_context, conf) if conf.output_dot_f...
Write a Python 3 function for printing out a neat targets dependency tree based on requested targets.
As a python code expert, you are capable of creating scripts from specifications.
Prints out a neat targets dependency tree based on requested targets.
Can you generate the documentation for the following Python 3 function def cmd_tree(conf: Config): build_context = BuildContext(conf) populate_targets_graph(build_context, conf) def print_target_with_deps(target, depth=2): print('{: >{}}{}'.format('+-', depth, target.name)) for dep in sorte...
As a Python code composer, you craft elegant and concise scripts.
Main console script entry point - run YABT from command - line.
Make a summary of the following Python 3 code def main(): conf = init_and_get_conf() logger = make_logger(__name__) logger.info('YaBT version {}', __version__) handlers = { 'build': YabtCommand(func=cmd_build, requires_project=True), 'dot': YabtCommand(func=cmd_dot, requires_project=True...
As a python code expert, you are capable of creating scripts from specifications.
Pack a C ++ binary as a Docker image with its runtime dependencies.
Make a summary of the following Python 3 code def cpp_app_builder(build_context, target): yprint(build_context.conf, 'Build CppApp', target) if target.props.executable and target.props.main: raise KeyError( '`main` and `executable` arguments are mutually exclusive') if target.props.execu...
You are a Python code architect, reviewing and designing scalable and efficient code
def make_pre_build_hook(extra_compiler_config_params): """Return a pre-build hook function for C++ builders. When called, during graph build, it computes and stores the compiler-config object on the target, as well as adding it to the internal_dict prop for hashing purposes. """ def pre_build_...
Create a Python 3 function for returning a pre - build hook function for C ++ builders.
As a Python code analyst, you investigate and solve complex coding mysteries
def compile_cc(build_context, compiler_config, buildenv, sources, workspace_dir, buildenv_workspace, cmd_env): """Compile list of C++ source files in a buildenv image and return list of generated object file. """ objects = [] for src in sources: obj_rel_path = '{}.o'.format...
Create a Python 3 function to compile list of C ++ source files in a buildenv image and return list of generated object file.
You are a Python code analyst, evaluating scripts for potential improvements.
Link required artifacts from dependencies under target workspace dir.
Given the following Python 3 function, write the documentation def link_cpp_artifacts(build_context, target, workspace_dir, include_objects: bool): """Link required artifacts from dependencies under target workspace dir. Return list of object files of dependencies (if `include_objects`...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_source_files(target, build_context) -> list: """Return list of source files for `target`.""" all_sources = list(target.props.sources) for proto_dep_name in target.props.protos: proto_dep = build_context.targets[proto_dep_name] all_sources.extend(proto_dep.artifacts.get(AT.gen_cc).key...
Implement a function in Python 3 to return list of source files for target.
As a Python code translator, you convert algorithms and pseudocode into Python.
def build_cpp(build_context, target, compiler_config, workspace_dir): """Compile and link a C++ binary for `target`.""" rmtree(workspace_dir) binary = join(*split(target.name)) objects = link_cpp_artifacts(build_context, target, workspace_dir, True) buildenv_workspace = build_context.conf.host_to_bu...
How would you code a function in Python 3 to compile and link a C ++ binary for target.
As a Python code translator, you convert algorithms and pseudocode into Python.
def cpp_prog_builder(build_context, target): """Build a C++ binary executable""" yprint(build_context.conf, 'Build CppProg', target) workspace_dir = build_context.get_workspace('CppProg', target.name) build_cpp(build_context, target, target.compiler_config, workspace_dir)
Write a Python 3 function for building a C ++ binary executable
As a Python code analyst, you investigate and solve complex coding mysteries
def cpp_lib_builder(build_context, target): """Build C++ object files""" yprint(build_context.conf, 'Build CppLib', target) workspace_dir = build_context.get_workspace('CppLib', target.name) workspace_src_dir = join(workspace_dir, 'src') rmtree(workspace_src_dir) link_cpp_artifacts(build_context...
Implement a Python 3 function for building C ++ object files
As a Python code analyst, you investigate and solve complex coding mysteries
def get(self, param, config, target, fallback): """Return the value of `param`, according to priority / expansion. First priority - the target itself. Second priority - the project config. Third priority - a global default ("fallback"). In list-params, a '$*' term processed as ...
Can you write a function in Python 3 where it returns the value of param according to priority and expansion.
You are a Python code generator, capable of creating scripts from specifications.
def make_parser(project_config_file: str) -> configargparse.ArgumentParser: """Return the argument parser. :param project_config_file: Absolute path to project-specific config file. If cached parser already exists - return it immediately. Otherwise, initialize a new `ConfigArgParser` that is able to t...
How would you code a function in Python 3 to create an argument parser for the given project - specific config file.
You are a Python code analyst, evaluating scripts for potential improvements.
def find_project_config_file(project_root: str) -> str: """Return absolute path to project-specific config file, if it exists. :param project_root: Absolute path to project root directory. A project config file is a file named `YCONFIG_FILE` found at the top level of the project root dir. Return ...
Implement a Python 3 function for returning absolute path to project - specific config file if it exists.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_user_settings_module(project_root: str): """Return project-specific user settings module, if it exists. :param project_root: Absolute path to project root directory. A project settings file is a file named `YSETTINGS_FILE` found at the top level of the project root dir. Return `None` if p...
Implement a Python 3 function for returning the project - specific user settings module if it exists.
You are a Python code generator, capable of creating scripts from specifications.
def call_user_func(settings_module, func_name, *args, **kwargs): """Call a user-supplied settings function and clean it up afterwards. settings_module may be None, or the function may not exist. If the function exists, it is called with the specified *args and **kwargs, and the result is returned. ...
Can you implement a function in Python 3 that calls a user - supplied settings function and clean it up afterwards.
As a Python code composer, you craft elegant and concise scripts.
Update the flavor arg based on the settings API
Given the following Python 3 function, write the documentation def get_build_flavor(settings_module, args): known_flavors = listify(call_user_func(settings_module, 'known_flavors')) if args.flavor: if args.flavor not in known_flavors: raise ValueError('Unknown build flavor: {}'.format(args.f...
You are a Python code architect, reviewing and designing scalable and efficient code
def init_and_get_conf(argv: list=None) -> Config: """Initialize a YABT CLI environment and return a Config instance. :param argv: Manual override of command-line params to parse (for tests). """ colorama.init() work_dir = os.path.abspath(os.curdir) project_root = search_for_parent_dir(work_dir,...
Can you write a function in Python 3 where it initializes a YABT CLI environment and return a Config instance.
As a Python code analyst, you investigate and solve complex coding mysteries
def stable_reverse_topological_sort(graph): """Return a list of nodes in topological sort order. This topological sort is a **unique** permutation of the nodes such that an edge from u to v implies that u appears before v in the topological sort order. Parameters ---------- graph : Network...
How would you code a function in Python 3 to return a list of nodes in the topological sort order.
As a Python code translator, you convert algorithms and pseudocode into Python.
def raise_unresolved_targets(build_context, conf, unknown_seeds, seed_refs): """Raise error about unresolved targets during graph parsing.""" def format_target(target_name): # TODO: suggest similar known target names build_module = split_build_module(target_name) return '{} (in {})'.for...
Write a Python 3 script to raise error about unresolved targets during graph parsing.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a decorator for registering a SCM provider named scm_name.
Explain what the following Python 3 code does def register_scm_provider(scm_name: str): def register_decorator(scm_class: SourceControl): """Decorator for registering SCM provider.""" if scm_name in ScmManager.providers: raise KeyError('{} already registered!'.format(scm_name)) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_provider(cls, scm_name: str, conf) -> SourceControl: """Load and return named SCM provider instance. :param conf: A yabt.config.Config object used to initialize the SCM provider instance. :raises KeyError: If no SCM provider with name `scm_name` registered. ...
Implement a function in Python 3 to load and return named SCM provider instance.
You are a Python code generator, capable of creating scripts from specifications.
def write_dot(build_context, conf: Config, out_f): """Write build graph in dot format to `out_f` file-like object.""" not_buildenv_targets = get_not_buildenv_targets(build_context) prebuilt_targets = get_prebuilt_targets(build_context) out_f.write('strict digraph {\n') for node in build_context.tar...
Can you write a function in Python 3 where it writes build graph in dot format to out_f file - like object.
As a Python code composer, you craft elegant and concise scripts.
def get_workspace(self, *parts) -> str: """Return a path to a private workspace dir. Create sub-tree of dirs using strings from `parts` inside workspace, and return full path to innermost directory. Upon returning successfully, the directory will exist (potentially changed...
Write a Python 3 script for returning a path to a private workspace dir.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_bin_dir(self, build_module: str) -> str: """Return a path to the binaries dir for a build module dir. Create sub-tree of missing dirs as needed, and return full path to innermost directory. """ bin_dir = os.path.join(self.conf.get_bin_path(), build_module) i...
Implement a function in Python 3 to return a path to the binaries dir for a build module.
As a Python code composer, you craft elegant and concise scripts.
Generate all dependencies of target by topological sort order.
Can you generate the documentation for the following Python 3 function def walk_target_deps_topological_order(self, target: Target): all_deps = get_descendants(self.target_graph, target.name) for dep_name in topological_sort(self.target_graph): if dep_name in all_deps: yield ...
You are a Python code architect, reviewing and designing scalable and efficient code
def generate_direct_deps(self, target: Target): """Generate only direct dependencies of `target`.""" yield from (self.targets[dep_name] for dep_name in sorted(target.deps))
Write a Python 3 function that can generate only direct dependencies of target.
As a Python code composer, you craft elegant and concise scripts.
Generate names of all dependencies of target.
Can you generate the documentation for the following Python 3 function def generate_dep_names(self, target: Target): yield from sorted(get_descendants(self.target_graph, target.name))
You are a Python code architect, reviewing and designing scalable and efficient code
Generate all dependencies of target.
Can you generate a brief explanation for the following Python 3 code def generate_all_deps(self, target: Target): yield from (self.targets[dep_name] for dep_name in self.generate_dep_names(target))
As a python code expert, you are capable of creating scripts from specifications.
Register a target instance in this build context.
Here you have a function in Python 3, explain what it does def register_target(self, target: Target): if target.name in self.targets: first = self.targets[target.name] raise NameError( 'Target with name "{0.name}" ({0.builder_name} from module ' '"{1}") al...
You are a Python code architect, reviewing and designing scalable and efficient code
Removes a target from this build context.
Can you tell what is the following Python 3 function doing def remove_target(self, target_name: str): if target_name in self.targets: del self.targets[target_name] build_module = split_build_module(target_name) if build_module in self.targets_by_module: self.targets_by_mo...
As a Python code composer, you craft elegant and concise scripts.
Return a build file parser target extraction context.
Can you tell what is the following Python 3 function doing def get_target_extraction_context(self, build_file_path: str) -> dict: extraction_context = {} for name, builder in Plugin.builders.items(): extraction_context[name] = extractor(name, builder, ...
As a python code expert, you are capable of creating scripts from specifications.
def get_buildenv_graph(self): """Return a graph induced by buildenv nodes""" # This implementation first obtains all subsets of nodes that all # buildenvs depend on, and then builds a subgraph induced by the union # of these subsets. This can be very non-optimal. # TODO(itamar): ...
Write a Python 3 script for returning a graph induced by buildenv nodes.
As a python code expert, you are capable of creating scripts from specifications.
def ready_nodes_iter(self, graph_copy): """Generate ready targets from the graph `graph_copy`. The input graph is mutated by this method, so it has to be a mutable copy of the graph (e.g. not original copy, or read-only view). Caller **must** call `done()` after processing every genera...
Create a Python 3 function for generating ready targets from the graph_copy.
You are a Python code analyst, evaluating scripts for potential improvements.
def run_in_buildenv( self, buildenv_target_name: str, cmd: list, cmd_env: dict=None, work_dir: str=None, auto_uid: bool=True, runtime: str=None, **kwargs): """Run a command in a named BuildEnv Docker image. :param buildenv_target_name: A named Docker image target in ...
Write a Python 3 function for running a command in a named BuildEnv Docker image.
You are a Python code analyst, evaluating scripts for potential improvements.
Invoke the builder function for a target.
How would you explain what the following Python 3 function does def build_target(self, target: Target): builder = Plugin.builders[target.builder_name] if builder.func: logger.debug('About to invoke the {} builder function for {}', target.builder_name, target.name) ...
You are a Python code generator, capable of creating scripts from specifications.
def register_target_artifact_metadata(self, target: str, metadata: dict): """Register the artifact metadata dictionary for a built target.""" with self.context_lock: self.artifacts_metadata[target.name] = metadata
Implement a Python 3 function for registering the artifact metadata dictionary for a built target.
You are a Python code analyst, evaluating scripts for potential improvements.
def write_artifacts_metadata(self): """Write out a JSON file with all built targets artifact metadata, if such output file is specified.""" if self.conf.artifacts_metadata_file: logger.info('Writing artifacts metadata to file "%s"', self.conf.artifacts_meta...
Implement a Python 3 function for writing out a JSON file with all built targets artifact metadata and any other metadata.
As a Python code translator, you convert algorithms and pseudocode into Python.
def can_use_cache(self, target: Target) -> bool: """Return True if should attempt to load `target` from cache. Return False if `target` has to be built, regardless of its cache status (because cache is disabled, or dependencies are dirty). """ # if caching is disabled for t...
Write a Python 3 function for returning True if target can be used in cache.
You are a Python code architect, reviewing and designing scalable and efficient code
Return a full path to the build file of build_module.
Here you have a function in Python 3, explain what it does def get_build_file_path(self, build_module) -> str: project_root = Path(self.project_root) build_module = norm_proj_path(build_module, '') return str(project_root / build_module / (BUILD_PROJ_FILE if '' == build_module...
As a python code expert, you are capable of creating scripts from specifications.
Return a guess for the URI type based on the URI string uri.
Can you tell what is the following Python 3 function doing def guess_uri_type(uri: str, hint: str=None): # TODO(itamar): do this better if hint: return hint norm_uri = uri.lower() parsed_uri = urlparse(norm_uri) if parsed_uri.path.endswith('.git'): return 'git' if parsed_uri.sche...
You are a Python code generator, capable of creating scripts from specifications.
Handle remote Git repository URI.
Given the following Python 3 function, write the documentation def git_handler(unused_build_context, target, fetch, package_dir, tar): target_name = split_name(target.name) # clone the repository under a private builder workspace repo_dir = join(package_dir, fetch.name) if fetch.name else package_dir tr...
As a Python code analyst, you investigate and solve complex coding mysteries
Handle remote downloadable archive URI.
Can you generate a brief explanation for the following Python 3 code def archive_handler(unused_build_context, target, fetch, package_dir, tar): package_dest = join(package_dir, basename(urlparse(fetch.uri).path)) package_content_dir = join(package_dir, 'content') extract_dir = (join(package_content_dir, fe...
As a Python code analyst, you investigate and solve complex coding mysteries
Handle remote downloadable file URI.
Make a summary of the following Python 3 code def fetch_file_handler(unused_build_context, target, fetch, package_dir, tar): dl_dir = join(package_dir, fetch.name) if fetch.name else package_dir fetch_url(fetch.uri, join(dl_dir, basename(urlparse(fetch.uri).path)), dl_dir) tar.ad...
You are a Python code generator, capable of creating scripts from specifications.
Return a target_name script_name package_tarball tuple for target
Can you generate a brief explanation for the following Python 3 code def get_installer_desc(build_context, target) -> tuple: workspace_dir = build_context.get_workspace('CustomInstaller', target.name) target_name = split_name(target.name) script_name = basename(target.props.script) package_tarball = '{}...
You are a Python code architect, reviewing and designing scalable and efficient code
Return set of target names that are not part of cached base images and are not part of base images and are not part of base images and are not part of base images and are not part of base images and not part of base images.
Here you have a function in Python 3, explain what it does def get_prebuilt_targets(build_context): logger.info('Scanning for cached base images') # deps that are part of cached based images contained_deps = set() # deps that are needed by images that are going to be built, # but are not part of the...
As a Python code translator, you convert algorithms and pseudocode into Python.
Write the summary JSON to cache_dir.
Explain what the following Python 3 code does def write_summary(summary: dict, cache_dir: str): # update the summary last-accessed timestamp summary['accessed'] = time() with open(join(cache_dir, 'summary.json'), 'w') as summary_file: summary_file.write(json.dumps(summary, indent=4, sort_keys=True))
As a Python code analyst, you investigate and solve complex coding mysteries
def load_target_from_cache(target: Target, build_context) -> (bool, bool): """Load `target` from build cache, restoring cached artifacts & summary. Return (build_cached, test_cached) tuple. `build_cached` is True if target restored successfully. `test_cached` is True if build is cached and test_time...
Write a Python 3 script to load target from build cache
As a Python code analyst, you investigate and solve complex coding mysteries
def copy_artifact(src_path: str, artifact_hash: str, conf: Config): """Copy the artifact at `src_path` with hash `artifact_hash` to artifacts cache dir. If an artifact already exists at that location, it is assumed to be identical (since it's based on hash), and the copy is skipped. TODO: pruni...
Can you implement a function in Python 3 that copies the artifact at src_path with hash artifact_hash to artifacts cache dir.
As a Python code translator, you convert algorithms and pseudocode into Python.
Restore the artifact whose hash is artifact_hash to src_path.
Make a summary of the following Python 3 code def restore_artifact(src_path: str, artifact_hash: str, conf: Config): cache_dir = conf.get_artifacts_cache_dir() if not isdir(cache_dir): return False cached_artifact_path = join(cache_dir, artifact_hash) if isfile(cached_artifact_path) or isdir(cac...
You are a Python code analyst, evaluating scripts for potential improvements.
Save target to build cache for future reuse.
How would you explain what the following Python 3 function does def save_target_in_cache(target: Target, build_context): cache_dir = build_context.conf.get_cache_dir(target, build_context) if isdir(cache_dir): rmtree(cache_dir) makedirs(cache_dir) logger.debug('Saving target metadata in cache un...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, key): """Return set of descendants of node named `key` in `target_graph`. Returns from cached dict if exists, otherwise compute over the graph and cache results in the dict. """ if key not in self: self[key] = set(get_descendants(self._target_graph, key...
Write a Python 3 script to return set of descendants of node named key in target_graph.
As a Python code analyst, you investigate and solve complex coding mysteries
Print a red msg to STDERR and exit.
Can you tell what is the following Python 3 function doing def fatal(msg, *args, **kwargs): exc_str = format_exc() if exc_str.strip() != 'NoneType: None': logger.info('{}', format_exc()) fatal_noexc(msg, *args, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
def fatal_noexc(msg, *args, **kwargs): """Print a red `msg` to STDERR and exit. The message is formatted with `args` & `kwargs`. """ print(Fore.RED + 'Fatal: ' + msg.format(*args, **kwargs) + Style.RESET_ALL, file=sys.stderr) sys.exit(1)
Write a Python 3 script to print a red msg to STDERR and exit.
As a Python code composer, you craft elegant and concise scripts.
Sync source node to destination path using hard links.
Can you generate a brief explanation for the following Python 3 code def link_node(abs_src: str, abs_dest: str, force: bool=False): dest_parent_dir = split(abs_dest)[0] if not isdir(dest_parent_dir): # exist_ok=True in case of concurrent creation of the same # parent dir os.makedirs(dest...
You are a Python code analyst, evaluating scripts for potential improvements.
Sync the list of files and directories in files to destination directory specified by workspace_src_dir.
Make a summary of the following Python 3 code def link_files(files: set, workspace_src_dir: str, common_parent: str, conf): """Sync the list of files and directories in `files` to destination directory specified by `workspace_src_dir`. "Sync" in the sense that every file given in `files` ...
You are a Python code analyst, evaluating scripts for potential improvements.
def norm_proj_path(path, build_module): """Return a normalized path for the `path` observed in `build_module`. The normalized path is "normalized" (in the `os.path.normpath` sense), relative from the project root directory, and OS-native. Supports making references from project root directory by prefi...
Write a Python 3 script to return a normalized path for the path observed in build_module.
As a Python code analyst, you investigate and solve complex coding mysteries
Search for the first parent directory of start_at that contains all files and all dirs with_files and with_dirs.
Can you tell what is the following Python 3 function doing def search_for_parent_dir(start_at: str=None, with_files: set=None, with_dirs: set=None) -> str: """Return absolute path of first parent directory of `start_at` that contains all files `with_files` and all dirs `with_dirs` ...
As a python code expert, you are capable of creating scripts from specifications.
def acc_hash(filepath: str, hasher): """Accumulate content of file at `filepath` in `hasher`.""" with open(filepath, 'rb') as f: while True: chunk = f.read(_BUF_SIZE) if not chunk: break hasher.update(chunk)
Write a Python 3 script for accumulating content of file at filepath in hasher.
As a python code expert, you are capable of creating scripts from specifications.
def hash_file(filepath: str) -> str: """Return the hexdigest MD5 hash of content of file at `filepath`.""" md5 = hashlib.md5() acc_hash(filepath, md5) return md5.hexdigest()
How would you implement a function in Python 3 that returns the hexdigest MD5 hash of content of file at filepath.
You are a Python code architect, reviewing and designing scalable and efficient code
def hash_tree(filepath: str) -> str: """Return the hexdigest MD5 hash of file or directory at `filepath`. If file - just hash file content. If directory - walk the directory, and accumulate hashes of all the relative paths + contents of files under the directory. """ if isfile(filepath): ...
Implement a function in Python 3 to return the hexdigest MD5 hash of file or directory at filepath.
You are a Python code architect, reviewing and designing scalable and efficient code
def add(self, artifact_type: ArtifactType, src_path: str, dst_path: str=None): """Add an artifact of type `artifact_type` at `src_path`. `src_path` should be the path of the file relative to project root. `dst_path`, if given, is the desired path of the artifact in dependent ...
Can you create a Python 3 function that adds an artifact of type artifact_type at src_path to the set of dependent objects.
As a Python code translator, you convert algorithms and pseudocode into Python.
def extend(self, artifact_type: ArtifactType, src_paths: list): """Add all `src_paths` as artifact of type `artifact_type`.""" for src_path in src_paths: self.add(artifact_type, src_path, src_path)
Create a Python 3 function for adding all src_paths as artifact of type artifact_type.
As a Python code translator, you convert algorithms and pseudocode into Python.
def link_types(self, base_dir: str, types: list, conf: Config) -> int: """Link all artifacts with types `types` under `base_dir` and return the number of linked artifacts.""" num_linked = 0 for kind in types: artifact_map = self._artifacts.get(kind) if not arti...
Can you create a Python 3 function that links all artifacts with types under base_dir and return the number of linked artifacts.
You are a Python code generator, capable of creating scripts from specifications.
Link all artifacts required for a Docker image under base_dir and return the number of linked artifacts.
Make a summary of the following Python 3 code def link_for_image(self, base_dir: str, conf: Config) -> int: return self.link_types( base_dir, [ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py], conf)
You are a Python code generator, capable of creating scripts from specifications.
def _link(self, base_dir: str, artifact_map: dict, conf: Config): """Link all artifacts in `artifact_map` under `base_dir` and return the number of artifacts linked.""" num_linked = 0 for dst, src in artifact_map.items(): abs_src = join(conf.project_root, src) ...
Create a Python 3 function to link all artifacts in artifact_map under base_dir and return the number of artifacts linked.
You are a Python code generator, capable of creating scripts from specifications.
Read and return the content of the project README file.
Can you generate a brief explanation for the following Python 3 code def get_readme(): base_dir = path.abspath(path.dirname(__file__)) with open(path.join(base_dir, 'README.md'), encoding='utf-8') as readme_f: return readme_f.read()
As a python code expert, you are capable of creating scripts from specifications.
def args_to_props(target: Target, builder: Builder, args: list, kwargs: dict): """Convert build file `args` and `kwargs` to `target` props. Use builder signature to validate builder usage in build-file, raising appropriate exceptions on signature-mismatches. Use builder signature default values to ass...
Can you implement a function in Python 3 that converts build file args and kwargs to target props.
As a Python code analyst, you investigate and solve complex coding mysteries
def extractor( builder_name: str, builder: Builder, build_file_path: str, build_context) -> types.FunctionType: """Return a target extraction function for a specific builder and a specific build file.""" build_module = to_build_module(build_file_path, build_context.conf) def extract_...
Create a Python 3 function to return a target extraction function for a specific builder and a specific build file.
As a Python code composer, you craft elegant and concise scripts.
def rdopkg_runner(): """ default rdopkg action runner including rdopkg action modules """ aman = ActionManager() # assume all actions.* modules are action modules aman.add_actions_modules(actions) aman.fill_aliases() # additional rdopkg action module logic should go here return Actio...
Can you write a function in Python 3 where it defaults rdopkg action runner including rdopkg action modules
As a Python code analyst, you investigate and solve complex coding mysteries
def rdopkg(*cargs): """ rdopkg CLI interface Execute rdopkg action with specified arguments and return shell friendly exit code. This is the default high level way to interact with rdopkg. py> rdopkg('new-version', '1.2.3') is equivalent to $> rdopkg new-version 1.2.3 ""...
Write a Python 3 script to execute rdopkg action with specified arguments and return shell friendly exit code.
You are a Python code architect, reviewing and designing scalable and efficient code
Instantiate and return a complete and working dyndns client.
Explain what the following Python 3 code does def getDynDnsClientForConfig(config, plugins=None): initparams = {} if "interval" in config: initparams["detect_interval"] = config["interval"] if plugins is not None: initparams["plugins"] = plugins if "updater" in config: for upda...
You are a Python code architect, reviewing and designing scalable and efficient code
Synchronize the registered IP with the detected IP.
Here you have a function in Python 3, explain what it does def sync(self): detected_ip = self.detector.detect() if detected_ip is None: LOG.debug("Couldn't detect the current IP using detector %r", self.detector.names()[-1]) # we don't have a value to set it to, so don't update! ...
You are a Python code generator, capable of creating scripts from specifications.
def has_state_changed(self): """ Detect changes in offline detector and real DNS value. Detect a change either in the offline detector or a difference between the real DNS value and what the online detector last got. This is efficient, since it only generates minimal dns...
Can you implement a function in Python 3 that returns True if the online state change has changed.
You are a Python code analyst, evaluating scripts for potential improvements.
Check if enough time has elapsed to perform a check.
Given the following Python 3 function, write the documentation def needs_check(self): if self.lastcheck is None: return True return time.time() - self.lastcheck >= self.ipchangedetection_sleep
As a Python code composer, you craft elegant and concise scripts.