text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_console_link(region, application_id): """ Print link for the application in AWS Serverless Application Repository console. Parameters region : str AWS...
if not region: region = boto3.Session().region_name console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace('/', '~')) msg = "Click the link below to view your application in AWS console:\n{}".format(console_link) click.secho(msg, fg="yellow")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lambda_failure_response(*args): """ Helper function to create a Lambda Failure Response :return: A Flask Response """
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE) return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lambda_not_found_response(*args): """ Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask Response """
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION) return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progressbar(length, label): """ Creates a progressbar Parameters length int Length of the ProgressBar label str Label to give to the progressbar Returns ----...
return click.progressbar(length=length, label=label, show_pos=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unquote(value): r""" Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing value thru shell. Exampl...
if value and (value[0] == value[-1] == '"'): # Remove quotes only if the string is wrapped in quotes value = value.strip('"') return value.replace("\\ ", " ").replace('\\"', '"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def service_response(body, headers, status_code): """ Constructs a Flask Response from the body, headers, and status_code. :param str body: Response body as a st...
response = Response(body) response.headers = headers response.status_code = status_code return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lambda_output(stdout_stream): """ This method will extract read the given stream and return the response from Lambda function separated out from any log ...
# We only want the last line of stdout, because it's possible that # the function may have written directly to stdout using # System.out.println or similar, before docker-lambda output the result stdout_data = stdout_stream.getvalue().rstrip(b'\n') # Usually the output is just ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self): """ Build the entire application Returns ------- dict Returns the path to where each resource was built as a map of resource's LogicalId to the ...
result = {} for lambda_function in self._functions_to_build: LOG.info("Building resource '%s'", lambda_function.name) result[lambda_function.name] = self._build_function(lambda_function.name, lambda_function.code...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_template(self, template_dict, original_template_path, built_artifacts): """ Given the path to built artifacts, update the template to point appropriat...
original_dir = os.path.dirname(original_template_path) for logical_id, resource in template_dict.get("Resources", {}).items(): if logical_id not in built_artifacts: # this resource was not built. So skip it continue # Artifacts are written rel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_function(self, function_name, codeuri, runtime): """ Given the function information, this method will build the Lambda function. Depending on the conf...
# Create the arguments to pass to the builder # Code is always relative to the given base directory. code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve()) config = get_workflow_config(runtime, code_dir, self._base_dir) # artifacts directory will be created by the bu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_container_dirs(source_dir, manifest_dir): """ Provides paths to directories within the container that is required by the builder Parameters source_dir :...
base = "/tmp/samcli" result = { "source_dir": "{}/source".format(base), "artifacts_dir": "{}/artifacts".format(base), "scratch_dir": "{}/scratch".format(base), "manifest_dir": "{}/manifest".format(base) } if pathlib.PurePath(source_dir) =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping): """ Use this method to convert a list of host paths to a list of equivalen...
if not host_paths_to_convert: # Nothing to do return host_paths_to_convert # Make sure the key is absolute host path. Relative paths are tricky to work with because two different # relative paths can point to the same directory ("../foo", "../../foo") mapping =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command(self, ctx, cmd_name): """ gets the subcommands under the service name Parameters ctx : Context the context object passed into the method cmd_name...
if cmd_name not in self.all_cmds: return None return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command(self, ctx, cmd_name): """ gets the Click Commands underneath a service name Parameters ctx: Context context object passed in cmd_name: string the...
if cmd_name not in self.subcmd_definition: return None parameters = [] for param_name in self.subcmd_definition[cmd_name][self.TAGS].keys(): default = self.subcmd_definition[cmd_name][self.TAGS][param_name]["default"] parameters.append(click.Option( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs): """ calls for value substitution in the event json and returns the cu...
event = events_lib.generate_event(top_level_cmd_name, subcmd_name, kwargs) click.echo(event) return event
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_lars_path(weighted_data, weighted_labels): """Generates the lars path for weighted data. Args: weighted_data: data that has been weighted by kernel ...
x_vector = weighted_data alphas, _, coefs = lars_path(x_vector, weighted_labels, method='lasso', verbose=False) return alphas, coefs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward_selection(self, data, labels, weights, num_features): """Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state) used_features = [] for _ in range(min(num_features, data.shape[1])): max_ = -100000000 best = 0 for feature in range(data.shape[1]): if feature in used_features: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def feature_selection(self, data, labels, weights, num_features, method): """Selects features for the model. see explain_instance_with_data to understand the par...
if method == 'none': return np.array(range(data.shape[1])) elif method == 'forward_selection': return self.forward_selection(data, labels, weights, num_features) elif method == 'highest_weights': clf = Ridge(alpha=0, fit_intercept=True, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, feature_selection='auto', model_regressor=None): """...
weights = self.kernel_fn(distances) labels_column = neighborhood_labels[:, label] used_features = self.feature_selection(neighborhood_data, labels_column, weights, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def id_generator(size=15, random_state=None): """Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits) return ''.join(random_state.choice(chars, size, replace=True))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def available_labels(self): """ Returns the list of classification labels for which we have any explanations. """
try: assert self.mode == "classification" except AssertionError: raise NotImplementedError('Not supported for regression explanations.') else: ans = self.top_labels if self.top_labels else self.local_exp.keys() return list(ans)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_list(self, label=1, **kwargs): """Returns the explanation as a list. Args: label: desired label. If you ask for a label for which an explanation wasn't co...
label_to_use = label if self.mode == "classification" else self.dummy_label ans = self.domain_mapper.map_exp_ids(self.local_exp[label_to_use], **kwargs) ans = [(x[0], float(x[1])) for x in ans] return ans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_pyplot_figure(self, label=1, **kwargs): """Returns the explanation as a pyplot figure. Will throw an error if you don't have matplotlib installed Args: la...
import matplotlib.pyplot as plt exp = self.as_list(label=label, **kwargs) fig = plt.figure() vals = [x[1] for x in exp] names = [x[0] for x in exp] vals.reverse() names.reverse() colors = ['green' if x > 0 else 'red' for x in vals] pos = np.arange...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_in_notebook(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Shows html explanation in ipython notebook. See as_html() fo...
from IPython.core.display import display, HTML display(HTML(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_to_file(self, file_path, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Saves html explanation to file. . Params: file_path: ...
file_ = open(file_path, 'w', encoding='utf8') file_.write(self.as_html(labels=labels, predict_proba=predict_proba, show_predicted_value=show_predicted_value, **kwargs)) file_.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_params(self, parameters): """Checks for mistakes in 'parameters' Args : parameters: dict, parameters to be checked Raises : ValueError: if any paramet...
a_valid_fn = [] if self.target_fn is None: if callable(self): a_valid_fn.append(self.__call__) else: raise TypeError('invalid argument: tested object is not callable,\ please provide a valid target_fn') elif isinstance(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_exp_ids(self, exp, positions=False): """Maps ids to words or word-position strings. Args: exp: list of tuples [(id, weight), (id,weight)] positions: if T...
if positions: exp = [('%s_%s' % ( self.indexed_string.word(x[0]), '-'.join( map(str, self.indexed_string.string_position(x[0])))), x[1]) for x in exp] else: exp = [(self.indexed_string...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inverse_removing(self, words_to_remove): """Returns a string after removing the appropriate words. If self.bow is false, replaces word with UNKWORDZ instead ...
mask = np.ones(self.as_np.shape[0], dtype='bool') mask[self.__get_idxs(words_to_remove)] = False if not self.bow: return ''.join([self.as_list[i] if mask[i] else 'UNKWORDZ' for i in range(mask.shape[0])]) return ''.join([self.as_list[v] for v in m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _segment_with_tokens(text, tokens): """Segment a string around the tokens created by a passed-in tokenizer"""
list_form = [] text_ptr = 0 for token in tokens: inter_token_string = [] while not text[text_ptr:].startswith(token): inter_token_string.append(text[text_ptr]) text_ptr += 1 if text_ptr >= len(text): rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_idxs(self, words): """Returns indexes to appropriate words."""
if self.bow: return list(itertools.chain.from_iterable( [self.positions[z] for z in words])) else: return self.positions[words]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) ""...
names = self.exp_feature_names if self.discretized_feature_names is not None: names = self.discretized_feature_names return [(names[x[0]], x[1]) for x in exp]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visualize_instance_html(self, exp, label, div_name, exp_object_name, show_table=True, show_all=False): """Shows the current example in a table format. Args: ...
if not show_table: return '' weights = [0] * len(self.feature_names) for x in exp: weights[x[0]] = x[1] out_list = list(zip(self.exp_feature_names, self.feature_values, weights)) if not show_all: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_training_data_stats(training_data_stats): """ Method to validate the structure of training data stats """
stat_keys = list(training_data_stats.keys()) valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"] missing_keys = list(set(valid_stat_keys) - set(stat_keys)) if len(missing_keys) > 0: raise Exception("Missing keys in training_data_stats...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_predict_proba(self, func): """ The predict_proba method will expect 3d arrays, but we are reshaping them to 2D so that LIME works correctly. This wraps...
def predict_proba(X): n_samples = X.shape[0] new_shape = (n_samples, self.n_features, self.n_timesteps) X = np.transpose(X.reshape(new_shape), axes=(0, 2, 1)) return func(X) return predict_proba
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_image_and_mask(self, label, positive_only=True, hide_rest=False, num_features=5, min_weight=0.): """Init function. Args: label: label to explain positive...
if label not in self.local_exp: raise KeyError('Label not in explanation') segments = self.segments image = self.image exp = self.local_exp[label] mask = np.zeros(segments.shape, segments.dtype) if hide_rest: temp = np.zeros(self.image.shape) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_labels(self, image, fudged_image, segments, classifier_fn, num_samples, batch_size=10): """Generates images and predictions in the neighborhood of this ...
n_features = np.unique(segments).shape[0] data = self.random_state.randint(0, 2, num_samples * n_features)\ .reshape((num_samples, n_features)) labels = [] data[0, :] = 1 imgs = [] for row in data: temp = copy.deepcopy(image) zeros = n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_arg(fn, arg_name): """Checks if a callable accepts a given keyword argument. Args: fn: callable to inspect arg_name: string, keyword argument name to che...
if sys.version_info < (3,): if isinstance(fn, types.FunctionType) or isinstance(fn, types.MethodType): arg_spec = inspect.getargspec(fn) else: try: arg_spec = inspect.getargspec(fn.__call__) except AttributeError: return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_remote(self, config, name): """ The config file is stored in a way that allows you to have a cache for each remote. This is needed when specifying exter...
from dvc.remote import Remote remote = config.get(name) if not remote: return None settings = self.repo.config.get_remote_settings(remote) return Remote(self.repo, settings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(vertexes, edges): """Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges. """
# pylint: disable=too-many-locals # NOTE: coordinates might me negative, so we need to shift # everything to the positive plane before we actually draw it. Xs = [] # pylint: disable=invalid-name Ys = [] # pylint: disable=invalid-name sug = _build_sugiyama_layout(vertexes, edges) for ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draws ASCII canvas on the screen."""
if sys.stdout.isatty(): # pragma: no cover from asciimatics.screen import Screen Screen.wrapper(self._do_draw) else: for line in self.canvas: print("".join(line))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def point(self, x, y, char): """Create a point on ASCII canvas. Args: x (int): x coordinate. Should be >= 0 and < number of columns in the canvas. y (int): y c...
assert len(char) == 1 assert x >= 0 assert x < self.cols assert y >= 0 assert y < self.lines self.canvas[y][x] = char
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line(self, x0, y0, x1, y1, char): """Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where ...
# pylint: disable=too-many-arguments, too-many-branches if x0 > x1: x1, x0 = x0, x1 y1, y0 = y0, y1 dx = x1 - x0 dy = y1 - y0 if dx == 0 and dy == 0: self.point(x0, y0, char) elif abs(dx) >= abs(dy): for x in range(x0, x1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self, x, y, text): """Print a text on ASCII canvas. Args: x (int): x coordinate where the text should start. y (int): y coordinate where the text shou...
for i, char in enumerate(text): self.point(x + i, y, char)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def box(self, x0, y0, width, height): """Create a box on ASCII canvas. Args: x0 (int): x coordinate of the box corner. y0 (int): y coordinate of the box corner...
assert width > 1 assert height > 1 width -= 1 height -= 1 for x in range(x0, x0 + width): self.point(x, y0, "-") self.point(x, y0 + height, "-") for y in range(y0, y0 + height): self.point(x0, y, "|") self.point(x0 + wid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self, line=None): """Refreshes progress bar."""
# Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not None: self._writeln(line) self._line = line self._lock.rele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_target(self, name, current, total): """Updates progress bar for a specified target."""
self.refresh(self._bar(name, current, total))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish_target(self, name): """Finishes progress bar for a specified target."""
# We have to write a msg about finished target with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self.clearln() self._print(pbar) self._n_finished += 1 self._line = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(self, a_ref, target=None, b_ref=None): """Gerenates diff message string output Args: target(str) - file/directory to check diff of a_ref(str) - first ta...
result = {} diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref) result[DIFF_A_REF] = diff_dct[DIFF_A_REF] result[DIFF_B_REF] = diff_dct[DIFF_B_REF] if diff_dct[DIFF_EQUAL]: result[DIFF_EQUAL] = True return result result[DIFF_LIST] = [] diff_outs = _get_diff_outs(self, dif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reproduce_stages( G, stages, node, force, dry, interactive, ignore_build_cache, no_commit, downstream, ): r"""Derive the evaluation of the given node for th...
import networkx as nx if downstream: # NOTE (py3 only): # Python's `deepcopy` defaults to pickle/unpickle the object. # Stages are complex objects (with references to `repo`, `outs`, # and `deps`) that cause struggles when you try to serialize them. # We need to create...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csv_reader(unicode_csv_data, dialect=None, **kwargs): """csv.reader doesn't support Unicode input, so need to use some tricks to work around this. Source: ht...
import csv dialect = dialect or csv.excel if is_py3: # Python3 supports encoding by default, so just return the object for row in csv.reader(unicode_csv_data, dialect=dialect, **kwargs): yield [cell for cell in row] else: # csv.py doesn't do Unicode; encode tempor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, address, target_dir, select=[], fname=None): """ Install package. The command can be run only from DVC project root. E.g. Having: DVC package i...
if not os.path.isdir(target_dir): raise DvcException( "target directory '{}' does not exist".format(target_dir) ) curr_dir = os.path.realpath(os.curdir) if not os.path.realpath(target_dir).startswith(curr_dir): raise DvcException( "the current directory sho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_import(self): """Whether the stage file was created with `dvc import`."""
return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_cached(self): """ Checks if this stage has been already ran and stored """
from dvc.remote.local import RemoteLOCAL from dvc.remote.s3 import RemoteS3 old = Stage.load(self.repo, self.path) if old._changed_outs(): return False # NOTE: need to save checksums for deps in order to compare them # with what is written in the old stage....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def daemon(args): """Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command. """
if os.environ.get(DVC_DAEMON): logger.debug("skipping launching a new daemon.") return cmd = [sys.executable] if not is_binary(): cmd += ["-m", "dvc"] cmd += ["daemon", "-q"] + args env = fix_env() file_path = os.path.abspath(inspect.stack()[0][1]) env[cast_bytes_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_parser(subparsers, parent_parser): """Setup parser for `dvc init`."""
INIT_HELP = "Initialize DVC in the current directory." INIT_DESCRIPTION = ( "Initialize DVC in the current directory. Expects directory\n" "to be a Git repository unless --no-scm option is specified." ) init_parser = subparsers.add_parser( "init", parents=[parent_parser...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_csv(content, delimiter): """Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value s...
reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter)) rows = [row for row in reader] max_widths = [max(map(len, column)) for column in zip(*rows)] lines = [ " ".join( "{entry:{width}}".format(entry=entry, width=width + 2) for entry, width in zip(row, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_output(content, typ): """Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric ...
if "csv" in str(typ): return _format_csv(content, delimiter=",") if "tsv" in str(typ): return _format_csv(content, delimiter="\t") return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_metrics(repo, path, recursive, typ, xpath, branch): """Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recur...
outs = [out for stage in repo.stages() for out in stage.outs] if path: try: outs = repo.find_outs_by_path(path, outs=outs, recursive=recursive) except OutputNotFoundError: logger.debug( "stage file not for found for '{}' in branch '{}'".format( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_metrics(repo, metrics, branch): """Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Bra...
res = {} for out, typ, xpath in metrics: assert out.scheme == "local" if not typ: typ = os.path.splitext(out.path.lower())[1].replace(".", "") if out.use_cache: open_fun = open path = repo.cache.local.get(out.checksum) else: open_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's pa...
import networkx as nx from dvc.exceptions import ( OutputDuplicationError, StagePathAsOutputError, OverlappingOutputPathsError, ) G = nx.DiGraph() G_active = nx.DiGraph() stages = stages or self.stages(from_directory, check_dag=False)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _progress_aware(self): """Add a new line if progress bar hasn't finished"""
from dvc.progress import progress if not progress.is_finished: progress._print() progress.clearln()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, path, binary=False): """Open file and return a stream."""
if binary: return open(path, "rb") return open(path, encoding="utf-8")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_paths(self, bucket, prefix): """ Read config for list object api, paginate through list objects."""
s3 = self.s3 kwargs = {"Bucket": bucket, "Prefix": prefix} if self.list_objects: list_objects_api = "list_objects" else: list_objects_api = "list_objects_v2" paginator = s3.get_paginator(list_objects_api) for page in paginator.paginate(**kwargs): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_path(path, config_file): """Resolve path relative to config file location. Args: path: Path to be resolved. config_file: Path to config file, which `...
if os.path.isabs(path): return path return os.path.relpath(path, os.path.dirname(config_file))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changed(self, path_info, checksum_info): """Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unl...
logger.debug( "checking if '{}'('{}') has changed.".format( path_info, checksum_info ) ) if not self.exists(path_info): logger.debug("'{}' doesn't exist.".format(path_info)) return True checksum = checksum_info.get(self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm(statement): """Ask the user for confirmation about the specified statement. Args: statement (unicode): statement to ask the user confirmation about....
prompt = "{statement} [y/n]".format(statement=statement) answer = _ask(prompt, limited_to=["yes", "no", "y", "n"]) return answer and answer.startswith("y")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=None): """Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: int: command's return code. "...
args = None cmd = None try: args = parse_args(argv) if args.quiet: logger.setLevel(logging.CRITICAL) elif args.verbose: logger.setLevel(logging.DEBUG) cmd = args.func(args) ret = cmd.run_cmd() except KeyboardInterrupt: logger.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def supported_cache_type(types): """Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out. ""...
if isinstance(types, str): types = [typ.strip() for typ in types.split(",")] for typ in types: if typ not in ["reflink", "hardlink", "symlink", "copy"]: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(dvc_dir): """Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Config: config object. """
config_file = os.path.join(dvc_dir, Config.CONFIG) open(config_file, "w+").close() return Config(dvc_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, validate=True): """Loads config from all the config files. Args: validate (bool): optional flag to tell dvc if it should validate the config or j...
self._load() try: self.config = self._load_config(self.system_config_file) user = self._load_config(self.global_config_file) config = self._load_config(self.config_file) local = self._load_config(self.config_local_file) # NOTE: schema doesn't...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, config=None): """Saves config to config files. Args: config (configobj.ConfigObj): optional config object to save. Raises: dvc.config.ConfigError...
if config is not None: clist = [config] else: clist = [ self._system_config, self._global_config, self._repo_config, self._local_config, ] for conf in clist: if conf.filename is None...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(config, section, opt, value): """Sets specified option in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section nam...
if section not in config.keys(): config[section] = {} config[section][opt] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(config, section, opt): """Prints option value from the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt...
if section not in config.keys(): raise ConfigError("section '{}' doesn't exist".format(section)) if opt not in config[section].keys(): raise ConfigError( "option '{}.{}' doesn't exist".format(section, opt) ) logger.info(config[section][opt])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, from_path, to_path): """ Renames an output file and modifies the stage associated to reflect the change on the pipeline. If the output has the sam...
import dvc.output as Output from dvc.stage import Stage from_out = Output.loads_from(Stage(self), [from_path])[0] to_path = _expand_target_path(from_path, to_path) outs = self.find_outs_by_path(from_out.path) assert len(outs) == 1 out = outs[0] stage = out.stage if not stage.is_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_version(base_version): """Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if not _is_git_repo(pkg_dir) or not _have_git(): return base_version if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir): return base_version return "{base_version}+{short_sha}{dirty}".format( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_dirty(dir_path): """Check whether a git repository has uncommitted changes."""
try: subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path) return False except subprocess.CalledProcessError: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_filter(d, exclude=[]): """ Exclude specified keys from a nested dict """
if isinstance(d, list): ret = [] for e in d: ret.append(dict_filter(e, exclude)) return ret elif isinstance(d, dict): ret = {} for k, v in d.items(): if isinstance(k, builtin_str): k = str(k) assert isinstance(k, str)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyfile(src, dest, no_progress_bar=False, name=None): """Copy file with progress bar"""
from dvc.progress import progress copied = 0 name = name if name else os.path.basename(dest) total = os.stat(src).st_size if os.path.isdir(dest): dest = os.path.join(dest, os.path.basename(src)) with open(src, "rb") as fsrc, open(dest, "wb+") as fdest: while True: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dvc_walk( top, topdown=True, onerror=None, followlinks=False, ignore_file_handler=None, ): """ Proxy for `os.walk` directory tree generator. Utilizes DvcIgno...
ignore_filter = None if topdown: from dvc.ignore import DvcIgnoreFilter ignore_filter = DvcIgnoreFilter( top, ignore_file_handler=ignore_file_handler ) for root, dirs, files in os.walk( top, topdown=topdown, onerror=onerror, followlinks=followlinks ): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorize(message, color=None): """Returns a message in a specified color."""
if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow": colorama.Fore.YELLOW, "blue": colorama.Fore.BLUE, "red": colorama.Fore.RED, } return "{color}{message}{nc}".format( color=colors.get(color, ""), message=message, nc=colorama...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boxify(message, border_color=None): """Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color ...
lines = message.split("\n") max_width = max(_visual_width(line) for line in lines) padding_horizontal = 5 padding_vertical = 1 box_size_horizontal = max_width + (padding_horizontal * 2) chars = {"corner": "+", "horizontal": "-", "vertical": "|", "empty": " "} margin = "{corner}{line}{co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _visual_width(line): """Get the the number of columns required to display a string"""
return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _visual_center(line, width): """Center align string according to it's visual width"""
spaces = max(width - _visual_width(line), 0) left_padding = int(spaces / 2) right_padding = spaces - left_padding return (left_padding * " ") + line + (right_padding * " ")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_targets(self): """Default targets for `dvc repro` and `dvc pipeline`."""
from dvc.stage import Stage msg = "assuming default target '{}'.".format(Stage.STAGE_FILE) logger.warning(msg) return [Stage.STAGE_FILE]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SCM(root_dir, repo=None): # pylint: disable=invalid-name """Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): pat...
if Git.is_repo(root_dir) or Git.is_submodule(root_dir): return Git(root_dir, repo=repo) return NoSCM(root_dir, repo=repo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parent_parser(): """Create instances of a parser containing common arguments shared among all the commands. When overwritting `-q` or `-v`, you need to i...
parent_parser = argparse.ArgumentParser(add_help=False) log_level_group = parent_parser.add_mutually_exclusive_group() log_level_group.add_argument( "-q", "--quiet", action="store_true", default=False, help="Be quiet." ) log_level_group.add_argument( "-v", "--verbose", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_args(argv=None): """Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParse...
parent_parser = get_parent_parser() # Main parser desc = "Data Version Control" parser = DvcParser( prog="dvc", description=desc, parents=[parent_parser], formatter_class=argparse.RawTextHelpFormatter, ) # NOTE: On some python versions action='version' prints t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_diff(src, dest): """Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when par...
Seq = (list, tuple) Container = (Mapping, list, tuple) def is_same_type(a, b): return any( isinstance(a, t) and isinstance(b, t) for t in [str, Mapping, Seq, bool] ) if isinstance(src, Mapping) and isinstance(dest, Mapping): for key, value in src.items(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def percent_cb(name, complete, total): """ Callback for updating target progress """
logger.debug( "{}: {} transferred out of {}".format( name, sizeof_fmt(complete), sizeof_fmt(total) ) ) progress.update_target(name, complete, total)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(path): """Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report. """
with open(path, "r") as fobj: analytics = Analytics(info=json.load(fobj)) os.unlink(path) return analytics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect(self): """Collect analytics report."""
from dvc.scm import SCM from dvc.utils import is_binary from dvc.repo import Repo from dvc.exceptions import NotDvcRepoError self.info[self.PARAM_DVC_VERSION] = __version__ self.info[self.PARAM_IS_BINARY] = is_binary() self.info[self.PARAM_USER_ID] = self._get_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_cmd(self, args, ret): """Collect analytics info from a CLI command."""
from dvc.command.daemon import CmdDaemonAnalytics assert isinstance(ret, int) or ret is None if ret is not None: self.info[self.PARAM_CMD_RETURN_CODE] = ret if args is not None and hasattr(args, "func"): assert args.func != CmdDaemonAnalytics self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self): """Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report. """
import tempfile with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj: json.dump(self.info, fobj) return fobj.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_cmd(cmd, args, ret): """Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the...
from dvc.daemon import daemon if not Analytics._is_enabled(cmd): return analytics = Analytics() analytics.collect_cmd(args, ret) daemon(["analytics", analytics.dump()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self): """Collect and send analytics."""
import requests if not self._is_enabled(): return self.collect() logger.debug("Sending analytics: {}".format(self.info)) try: requests.post(self.URL, json=self.info, timeout=self.TIMEOUT_POST) except requests.exceptions.RequestException as exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, targets, jobs=None, remote=None, show_checksums=False): """Push data items in a cloud-agnostic way. Args: targets (list): list of targets to push...
return self.repo.cache.local.push( targets, jobs=jobs, remote=self._get_cloud(remote, "push"), show_checksums=show_checksums, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, targets, jobs=None, remote=None, show_checksums=False): """Check status of data items in a cloud-agnostic way. Args: targets (list): list of ta...
cloud = self._get_cloud(remote, "status") return self.repo.cache.local.status( targets, jobs=jobs, remote=cloud, show_checksums=show_checksums )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brancher( # noqa: E302 self, branches=None, all_branches=False, tags=None, all_tags=False ): """Generator that iterates over specified revisions. Args: branc...
if not any([branches, all_branches, tags, all_tags]): yield "" return saved_tree = self.tree revs = [] scm = self.scm if self.scm.is_dirty(): from dvc.scm.tree import WorkingTree self.tree = WorkingTree(self.root_dir) yield "Working Tree" if all_bran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self): """Loads state database."""
retries = 1 while True: assert self.database is None assert self.cursor is None assert self.inserts == 0 empty = not os.path.exists(self.state_file) self.database = sqlite3.connect(self.state_file) self.cursor = self.database.curso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self): """Saves state database."""
assert self.database is not None cmd = "SELECT count from {} WHERE rowid={}" self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW)) ret = self._fetchall() assert len(ret) == 1 assert len(ret[0]) == 1 count = self._from_sqlite(ret[0][0]) + self.ins...