Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _parsed_cmd(self):
if len(self.args.command) < 2:
return " ".join(self.args.command)
return " ".join(self._quote_argument(arg) for arg in self.args.command) | [
"\n We need to take into account two cases:\n\n - ['python code.py foo bar']: Used mainly with dvc as a library\n - ['echo', 'foo bar']: List of arguments received from the CLI\n\n The second case would need quoting, as it was passed through:\n dvc run echo \"foo bar\"\n ... |
Please provide a description of the function:def add_parser(subparsers, parent_parser):
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."
... | [
"Setup parser for `dvc init`."
] |
Please provide a description of the function:def _format_csv(content, delimiter):
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:{w... | [
"Format delimited text to have same column width.\n\n Args:\n content (str): The content of a metric.\n delimiter (str): Value separator\n\n Returns:\n str: Formatted content.\n\n Example:\n\n >>> content = (\n \"value_mse,deviation_mse,data_set\\n\"\n \"0.... |
Please provide a description of the function:def _format_output(content, typ):
if "csv" in str(typ):
return _format_csv(content, delimiter=",")
if "tsv" in str(typ):
return _format_csv(content, delimiter="\t")
return content | [
"Tabularize the content according to its type.\n\n Args:\n content (str): The content of a metric.\n typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).\n\n Returns:\n str: Content in a raw or tabular format.\n "
] |
Please provide a description of the function:def _collect_metrics(repo, path, recursive, typ, xpath, branch):
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 OutputNotFoundErr... | [
"Gather all the metric outputs.\n\n Args:\n path (str): Path to a metric file or a directory.\n recursive (bool): If path is a directory, do a recursive search for\n metrics on the given path.\n typ (str): The type of metric to search for, could be one of the\n followin... |
Please provide a description of the function:def _read_metrics(repo, metrics, branch):
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 = ... | [
"Read the content of each metric file and format it.\n\n Args:\n metrics (list): List of metric touples\n branch (str): Branch to look up for metrics.\n\n Returns:\n A dict mapping keys with metrics path name and content.\n For example:\n\n {'metric.csv': (\"value_mse devia... |
Please provide a description of the function:def graph(self, stages=None, from_directory=None):
import networkx as nx
from dvc.exceptions import (
OutputDuplicationError,
StagePathAsOutputError,
OverlappingOutputPathsError,
)
G = nx.DiGraph()... | [
"Generate a graph by using the given stages on the given directory\n\n The nodes of the graph are the stage's path relative to the root.\n\n Edges are created when the output of one stage is used as a\n dependency in other stage.\n\n The direction of the edges goes from the stage to its ... |
Please provide a description of the function:def stages(self, from_directory=None, check_dag=True):
from dvc.stage import Stage
if not from_directory:
from_directory = self.root_dir
elif not os.path.isdir(from_directory):
raise TargetNotDirectoryError(from_direc... | [
"\n Walks down the root directory looking for Dvcfiles,\n skipping the directories that are related with\n any SCM (e.g. `.git`), DVC itself (`.dvc`), or directories\n tracked by DVC (e.g. `dvc add data` would skip `data/`)\n\n NOTE: For large repos, this could be an expensive\n ... |
Please provide a description of the function:def _progress_aware(self):
from dvc.progress import progress
if not progress.is_finished:
progress._print()
progress.clearln() | [
"Add a new line if progress bar hasn't finished"
] |
Please provide a description of the function:def open(self, path, binary=False):
if binary:
return open(path, "rb")
return open(path, encoding="utf-8") | [
"Open file and return a stream."
] |
Please provide a description of the function:def walk(self, top, topdown=True, ignore_file_handler=None):
def onerror(e):
raise e
for root, dirs, files in dvc_walk(
os.path.abspath(top),
topdown=topdown,
onerror=onerror,
ignore_file_... | [
"Directory tree generator.\n\n See `os.walk` for the docs. Differences:\n - no support for symlinks\n - it could raise exceptions, there is no onerror argument\n "
] |
Please provide a description of the function:def _list_paths(self, bucket, prefix):
s3 = self.s3
kwargs = {"Bucket": bucket, "Prefix": prefix}
if self.list_objects:
list_objects_api = "list_objects"
else:
list_objects_api = "list_objects_v2"
pagin... | [
" Read config for list object api, paginate through list objects."
] |
Please provide a description of the function:def resolve_path(path, config_file):
if os.path.isabs(path):
return path
return os.path.relpath(path, os.path.dirname(config_file)) | [
"Resolve path relative to config file location.\n\n Args:\n path: Path to be resolved.\n config_file: Path to config file, which `path` is specified\n relative to.\n\n Returns:\n Path relative to the `config_file` location. If `path` is an\n a... |
Please provide a description of the function:def get_diff_trees(self, a_ref, b_ref=None):
diff_dct = {DIFF_EQUAL: False}
trees, commit_refs = self._get_diff_trees(a_ref, b_ref)
diff_dct[DIFF_A_REF] = commit_refs[0]
diff_dct[DIFF_B_REF] = commit_refs[1]
if commit_refs[0] ... | [
"Method for getting two repo trees between two git tag commits\n returns the dvc hash names of changed file/directory\n\n Args:\n a_ref(str) - git reference\n b_ref(str) - optional second git reference, default None\n\n Returns:\n dict - dictionary with keys: (a... |
Please provide a description of the function:def changed(self, path_info, checksum_info):
logger.debug(
"checking if '{}'('{}') has changed.".format(
path_info, checksum_info
)
)
if not self.exists(path_info):
logger.debug("'{}' does... | [
"Checks if data has changed.\n\n A file is considered changed if:\n - It doesn't exist on the working directory (was unlinked)\n - Checksum is not computed (saving a new file)\n - The checkusm stored in the State is different from the given one\n - There's no file ... |
Please provide a description of the function:def confirm(statement):
prompt = "{statement} [y/n]".format(statement=statement)
answer = _ask(prompt, limited_to=["yes", "no", "y", "n"])
return answer and answer.startswith("y") | [
"Ask the user for confirmation about the specified statement.\n\n Args:\n statement (unicode): statement to ask the user confirmation about.\n\n Returns:\n bool: whether or not specified statement was confirmed.\n "
] |
Please provide a description of the function:def main(argv=None):
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)
... | [
"Run dvc CLI command.\n\n Args:\n argv: optional list of arguments to parse. sys.argv is used by default.\n\n Returns:\n int: command's return code.\n "
] |
Please provide a description of the function:def supported_cache_type(types):
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 | [
"Checks if link type config option has a valid value.\n\n Args:\n types (list/string): type(s) of links that dvc should try out.\n "
] |
Please provide a description of the function:def get_global_config_dir():
from appdirs import user_config_dir
return user_config_dir(
appname=Config.APPNAME, appauthor=Config.APPAUTHOR
) | [
"Returns global config location. E.g. ~/.config/dvc/config.\n\n Returns:\n str: path to the global config directory.\n "
] |
Please provide a description of the function:def get_system_config_dir():
from appdirs import site_config_dir
return site_config_dir(
appname=Config.APPNAME, appauthor=Config.APPAUTHOR
) | [
"Returns system config location. E.g. /etc/dvc.conf.\n\n Returns:\n str: path to the system config directory.\n "
] |
Please provide a description of the function:def init(dvc_dir):
config_file = os.path.join(dvc_dir, Config.CONFIG)
open(config_file, "w+").close()
return Config(dvc_dir) | [
"Initializes dvc config.\n\n Args:\n dvc_dir (str): path to .dvc directory.\n\n Returns:\n dvc.config.Config: config object.\n "
] |
Please provide a description of the function:def load(self, validate=True):
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)
l... | [
"Loads config from all the config files.\n\n Args:\n validate (bool): optional flag to tell dvc if it should validate\n the config or just load it as is. 'True' by default.\n\n\n Raises:\n dvc.config.ConfigError: thrown if config has invalid format.\n "
] |
Please provide a description of the function:def save(self, config=None):
if config is not None:
clist = [config]
else:
clist = [
self._system_config,
self._global_config,
self._repo_config,
self._local_conf... | [
"Saves config to config files.\n\n Args:\n config (configobj.ConfigObj): optional config object to save.\n\n Raises:\n dvc.config.ConfigError: thrown if failed to write config file.\n "
] |
Please provide a description of the function:def get_remote_settings(self, name):
import posixpath
settings = self.config[self.SECTION_REMOTE_FMT.format(name)]
parsed = urlparse(settings["url"])
# Support for cross referenced remotes.
# This will merge the settings, gi... | [
"\n Args:\n name (str): The name of the remote that we want to retrieve\n\n Returns:\n dict: The content beneath the given remote name.\n\n Example:\n >>> config = {'remote \"server\"': {'url': 'ssh://localhost/'}}\n >>> get_remote_settings(\"server\"... |
Please provide a description of the function:def unset(config, section, opt=None):
if section not in config.keys():
raise ConfigError("section '{}' doesn't exist".format(section))
if opt is None:
del config[section]
return
if opt not in config[secti... | [
"Unsets specified option and/or section in the config.\n\n Args:\n config (configobj.ConfigObj): config to work on.\n section (str): section name.\n opt (str): optional option name.\n "
] |
Please provide a description of the function:def set(config, section, opt, value):
if section not in config.keys():
config[section] = {}
config[section][opt] = value | [
"Sets specified option in the config.\n\n Args:\n config (configobj.ConfigObj): config to work on.\n section (str): section name.\n opt (str): option name.\n value: value to set option to.\n "
] |
Please provide a description of the function:def show(config, section, 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... | [
"Prints option value from the config.\n\n Args:\n config (configobj.ConfigObj): config to work on.\n section (str): section name.\n opt (str): option name.\n "
] |
Please provide a description of the function:def move(self, from_path, to_path):
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)
... | [
"\n Renames an output file and modifies the stage associated\n to reflect the change on the pipeline.\n\n If the output has the same name as its stage, it would\n also rename the corresponding stage file.\n\n E.g.\n Having: (hello, hello.dvc)\n\n $ dvc move hello greetings\n\n ... |
Please provide a description of the function:def init(root_dir=os.curdir, no_scm=False, force=False):
root_dir = os.path.abspath(root_dir)
dvc_dir = os.path.join(root_dir, Repo.DVC_DIR)
scm = SCM(root_dir)
if isinstance(scm, NoSCM) and not no_scm:
raise InitError(
"{repo} is not... | [
"\n Creates an empty repo on the given directory -- basically a\n `.dvc` directory with subdirectories for configuration and cache.\n\n It should be tracked by a SCM or use the `--no-scm` flag.\n\n If the given directory is not empty, you must use the `--force`\n flag to override it.\n\n Args:\n ... |
Please provide a description of the function:def _generate_version(base_version):
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):
... | [
"Generate a version with information about the git repository"
] |
Please provide a description of the function:def _is_dirty(dir_path):
try:
subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path)
return False
except subprocess.CalledProcessError:
return True | [
"Check whether a git repository has uncommitted changes."
] |
Please provide a description of the function:def file_md5(fname):
from dvc.progress import progress
from dvc.istextfile import istextfile
if os.path.exists(fname):
hash_md5 = hashlib.md5()
binary = not istextfile(fname)
size = os.path.getsize(fname)
bar = False
... | [
" get the (md5 hexdigest, md5 digest) of a file "
] |
Please provide a description of the function:def dict_filter(d, exclude=[]):
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... | [
"\n Exclude specified keys from a nested dict\n "
] |
Please provide a description of the function:def copyfile(src, dest, no_progress_bar=False, name=None):
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.b... | [
"Copy file with progress bar"
] |
Please provide a description of the function:def dvc_walk(
top,
topdown=True,
onerror=None,
followlinks=False,
ignore_file_handler=None,
):
ignore_filter = None
if topdown:
from dvc.ignore import DvcIgnoreFilter
ignore_filter = DvcIgnoreFilter(
top, ignore_f... | [
"\n Proxy for `os.walk` directory tree generator.\n Utilizes DvcIgnoreFilter functionality.\n "
] |
Please provide a description of the function:def colorize(message, color=None):
if not color:
return message
colors = {
"green": colorama.Fore.GREEN,
"yellow": colorama.Fore.YELLOW,
"blue": colorama.Fore.BLUE,
"red": colorama.Fore.RED,
}
return "{color}{mes... | [
"Returns a message in a specified color."
] |
Please provide a description of the function:def boxify(message, border_color=None):
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"... | [
"Put a message inside a box.\n\n Args:\n message (unicode): message to decorate.\n border_color (unicode): name of the color to outline the box with.\n "
] |
Please provide a description of the function:def _visual_width(line):
return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line)) | [
"Get the the number of columns required to display a string"
] |
Please provide a description of the function:def _visual_center(line, width):
spaces = max(width - _visual_width(line), 0)
left_padding = int(spaces / 2)
right_padding = spaces - left_padding
return (left_padding * " ") + line + (right_padding * " ") | [
"Center align string according to it's visual width"
] |
Please provide a description of the function:def fix_subparsers(subparsers):
from dvc.utils.compat import is_py3
if is_py3: # pragma: no cover
subparsers.required = True
subparsers.dest = "cmd" | [
"Workaround for bug in Python 3. See more info at:\n https://bugs.python.org/issue16308\n https://github.com/iterative/dvc/issues/769\n\n Args:\n subparsers: subparsers to fix.\n "
] |
Please provide a description of the function:def default_targets(self):
from dvc.stage import Stage
msg = "assuming default target '{}'.".format(Stage.STAGE_FILE)
logger.warning(msg)
return [Stage.STAGE_FILE] | [
"Default targets for `dvc repro` and `dvc pipeline`."
] |
Please provide a description of the function:def SCM(root_dir, repo=None): # pylint: disable=invalid-name
if Git.is_repo(root_dir) or Git.is_submodule(root_dir):
return Git(root_dir, repo=repo)
return NoSCM(root_dir, repo=repo) | [
"Returns SCM instance that corresponds to a repo at the specified\n path.\n\n Args:\n root_dir (str): path to a root directory of the repo.\n repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.\n\n Returns:\n dvc.scm.base.Base: SCM instance.\n "
] |
Please provide a description of the function:def get_parent_parser():
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."
)... | [
"Create instances of a parser containing common arguments shared among\n all the commands.\n\n When overwritting `-q` or `-v`, you need to instantiate a new object\n in order to prevent some weird behavior.\n "
] |
Please provide a description of the function:def parse_args(argv=None):
parent_parser = get_parent_parser()
# Main parser
desc = "Data Version Control"
parser = DvcParser(
prog="dvc",
description=desc,
parents=[parent_parser],
formatter_class=argparse.RawTextHelpFor... | [
"Parses CLI arguments.\n\n Args:\n argv: optional list of arguments to parse. sys.argv is used by default.\n\n Raises:\n dvc.exceptions.DvcParserError: raised for argument parsing errors.\n "
] |
Please provide a description of the function:def apply_diff(src, dest):
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, ... | [
"Recursively apply changes from src to dest.\n\n Preserves dest type and hidden info in dest structure,\n like ruamel.yaml leaves when parses files. This includes comments,\n ordering and line foldings.\n\n Used in Stage load/dump cycle to preserve comments and custom formatting.\n "
] |
Please provide a description of the function:def percent_cb(name, complete, total):
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) | [
" Callback for updating target progress "
] |
Please provide a description of the function:def md5(self, path):
uname = self.execute("uname").strip()
command = {
"Darwin": "md5 {}".format(path),
"Linux": "md5sum --tag {}".format(path),
}.get(uname)
if not command:
raise DvcException(
... | [
"\n Use different md5 commands depending on the OS:\n\n - Darwin's `md5` returns BSD-style checksums by default\n - Linux's `md5sum` needs the `--tag` flag for a similar output\n\n Example:\n MD5 (foo.txt) = f3d220a856b52aabbf294351e8a24300\n "
] |
Please provide a description of the function:def load(path):
with open(path, "r") as fobj:
analytics = Analytics(info=json.load(fobj))
os.unlink(path)
return analytics | [
"Loads analytics report from json file specified by path.\n\n Args:\n path (str): path to json file with analytics report.\n "
] |
Please provide a description of the function:def collect(self):
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_B... | [
"Collect analytics report."
] |
Please provide a description of the function:def collect_cmd(self, args, ret):
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 hasa... | [
"Collect analytics info from a CLI command."
] |
Please provide a description of the function:def dump(self):
import tempfile
with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
json.dump(self.info, fobj)
return fobj.name | [
"Save analytics report to a temporary file.\n\n Returns:\n str: path to the temporary file that contains the analytics report.\n "
] |
Please provide a description of the function:def send_cmd(cmd, args, ret):
from dvc.daemon import daemon
if not Analytics._is_enabled(cmd):
return
analytics = Analytics()
analytics.collect_cmd(args, ret)
daemon(["analytics", analytics.dump()]) | [
"Collect and send analytics for CLI command.\n\n Args:\n args (list): parsed args for the CLI command.\n ret (int): return value of the CLI command.\n "
] |
Please provide a description of the function:def send(self):
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.TIM... | [
"Collect and send analytics."
] |
Please provide a description of the function:def walk(self, top, topdown=True, ignore_file_handler=None):
tree = self.git_object_by_path(top)
if tree is None:
raise IOError(errno.ENOENT, "No such file")
for x in self._walk(tree, topdown):
yield x | [
"Directory tree generator.\n\n See `os.walk` for the docs. Differences:\n - no support for symlinks\n - it could raise exceptions, there is no onerror argument\n "
] |
Please provide a description of the function:def push(self, targets, jobs=None, remote=None, show_checksums=False):
return self.repo.cache.local.push(
targets,
jobs=jobs,
remote=self._get_cloud(remote, "push"),
show_checksums=show_checksums,
) | [
"Push data items in a cloud-agnostic way.\n\n Args:\n targets (list): list of targets to push to the cloud.\n jobs (int): number of jobs that can be running simultaneously.\n remote (dvc.remote.base.RemoteBase): optional remote to push to.\n By default remote f... |
Please provide a description of the function:def status(self, targets, jobs=None, remote=None, show_checksums=False):
cloud = self._get_cloud(remote, "status")
return self.repo.cache.local.status(
targets, jobs=jobs, remote=cloud, show_checksums=show_checksums
) | [
"Check status of data items in a cloud-agnostic way.\n\n Args:\n targets (list): list of targets to check status for.\n jobs (int): number of jobs that can be running simultaneously.\n remote (dvc.remote.base.RemoteBase): optional remote to compare\n targets to... |
Please provide a description of the function:def brancher( # noqa: E302
self, branches=None, all_branches=False, tags=None, all_tags=False
):
if not any([branches, all_branches, tags, all_tags]):
yield ""
return
saved_tree = self.tree
revs = []
scm = self.scm
if self.scm... | [
"Generator that iterates over specified revisions.\n\n Args:\n branches (list): a list of branches to iterate over.\n all_branches (bool): iterate over all available branches.\n tags (list): a list of tags to iterate over.\n all_tags (bool): iterate over all available tags.\n\n Yie... |
Please provide a description of the function:def changed(self, path, md5):
actual = self.update(path)
msg = "File '{}', md5 '{}', actual '{}'"
logger.debug(msg.format(path, md5, actual))
if not md5 or not actual:
return True
return actual.split(".")[0] != ... | [
"Check if file/directory has the expected md5.\n\n Args:\n path (str): path to the file/directory to check.\n md5 (str): expected md5.\n\n Returns:\n bool: True if path has the expected md5, False otherwise.\n "
] |
Please provide a description of the function:def load(self):
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.c... | [
"Loads state database."
] |
Please provide a description of the function:def dump(self):
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... | [
"Saves state database."
] |
Please provide a description of the function:def save(self, path_info, checksum):
assert path_info["scheme"] == "local"
assert checksum is not None
path = path_info["path"]
assert os.path.exists(path)
actual_mtime, actual_size = get_mtime_and_size(path)
actual_... | [
"Save checksum for the specified path info.\n\n Args:\n path_info (dict): path_info to save checksum for.\n checksum (str): checksum to save.\n "
] |
Please provide a description of the function:def get(self, path_info):
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return None
actual_mtime, actual_size = get_mtime_and_size(path)
actual_inode = get_inode(path... | [
"Gets the checksum for the specified path info. Checksum will be\n retrieved from the state database if available.\n\n Args:\n path_info (dict): path info to get the checksum for.\n\n Returns:\n str or None: checksum for the specified path info or None if it\n d... |
Please provide a description of the function:def save_link(self, path_info):
assert path_info["scheme"] == "local"
path = path_info["path"]
if not os.path.exists(path):
return
mtime, _ = get_mtime_and_size(path)
inode = get_inode(path)
relpath = os.... | [
"Adds the specified path to the list of links created by dvc. This\n list is later used on `dvc checkout` to cleanup old links.\n\n Args:\n path_info (dict): path info to add to the list of links.\n "
] |
Please provide a description of the function:def remove_unused_links(self, used):
unused = []
self._execute("SELECT * FROM {}".format(self.LINK_STATE_TABLE))
for row in self.cursor:
relpath, inode, mtime = row
inode = self._from_sqlite(inode)
path = ... | [
"Removes all saved links except the ones that are used.\n\n Args:\n used (list): list of used links that should not be removed.\n "
] |
Please provide a description of the function:def show_metrics(metrics, all_branches=False, all_tags=False):
for branch, val in metrics.items():
if all_branches or all_tags:
logger.info("{branch}:".format(branch=branch))
for fname, metric in val.items():
lines = metric i... | [
"\n Args:\n metrics (list): Where each element is either a `list`\n if an xpath was specified, otherwise a `str`\n "
] |
Please provide a description of the function:def lock(self):
try:
self._do_lock()
return
except LockError:
time.sleep(self.TIMEOUT)
self._do_lock() | [
"Acquire lock for dvc repo."
] |
Please provide a description of the function:def read_mail(window):
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
(retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
mail.list()
typ, data = mail.select('Inbox')
n = 0
now = datetime.now()
# get messages from today
search_strin... | [
"\n Reads late emails from IMAP server and displays them in the Window\n :param window: window to display emails in\n :return:\n "
] |
Please provide a description of the function:def runCommand(cmd, timeout=None):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ''
out, err = p.communicate()
p.wait(timeout)
return (out, err) | [
" run shell command\n\n\t@param cmd: command to execute\n\t@param timeout: timeout for command execution\n\n\t@return: (return code from command, command output)\n\t"
] |
Please provide a description of the function:def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True,
timeout=None, on_terminate=None):
if pid == os.getpid():
raise RuntimeError("I refuse to kill myself")
parent = psutil.Process(pid)
children = parent.children(recursi... | [
"Kill a process tree (including grandchildren) with signal\n \"sig\" and return a (gone, still_alive) tuple.\n \"on_terminate\", if specified, is a callabck function which is\n called as soon as a child terminates.\n "
] |
Please provide a description of the function:def Popup(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
... | [
"\n Popup - Display a popup box with as many parms as you wish to include\n :param args:\n :param button_color:\n :param background_color:\n :param text_color:\n :param button_type:\n :param auto_close:\n :param auto_close_duration:\n :param non_blocking:\n :param icon:\n :param lin... |
Please provide a description of the function:def PopupNoButtons(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_... | [
"\n Show a Popup but without any buttons\n :param args:\n :param button_color:\n :param background_color:\n :param text_color:\n :param auto_close:\n :param auto_close_duration:\n :param non_blocking:\n :param icon:\n :param line_width:\n :param font:\n :param no_titlebar:\n :... |
Please provide a description of the function:def PopupError(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_t... | [
"\n Popup with colored button and 'Error' as button text\n :param args:\n :param button_color:\n :param background_color:\n :param text_color:\n :param auto_close:\n :param auto_close_duration:\n :param non_blocking:\n :param icon:\n :param line_width:\n :param font:\n :param no_... |
Please provide a description of the function:def set_scrollregion(self, event=None):
self.canvas.configure(scrollregion=self.canvas.bbox('all')) | [
" Set the scroll region on the canvas"
] |
Please provide a description of the function:def _show_selection(self, text, bbox):
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
... | [
"Configure canvas for a new selection."
] |
Please provide a description of the function:def _pressed(self, evt):
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or not item in self._items:
# clicked in the weekdays row or just outside the... | [
"Clicked somewhere in the calendar."
] |
Please provide a description of the function:def _prev_month(self):
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | [
"Updated calendar to show the previous month."
] |
Please provide a description of the function:def _next_month(self):
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._d... | [
"Update calendar to show the next month."
] |
Please provide a description of the function:def selection(self):
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0])) | [
"Return a datetime representing the current selected date."
] |
Please provide a description of the function:def AddRow(self, *args):
''' Parms are a variable number of Elements '''
NumRows = len(self.Rows) # number of existing rows is our row number
CurrentRowNumber = NumRows # this row's number
CurrentRow = [] # start with a blank row and build ... | [] |
Please provide a description of the function:def SetAlpha(self, alpha):
'''
Change the window's transparency
:param alpha: From 0 to 1 with 0 being completely transparent
:return:
'''
self._AlphaChannel = alpha
self.TKroot.attributes('-alpha', alpha) | [] |
Please provide a description of the function:def setColor(self, color):
'''Sets Card's color and escape code.'''
if color == 'blue':
self.color = 'blue'
self.colorCode = self.colors['blue']
self.colorCodeDark = self.colors['dblue']
elif color == 'red':
... | [] |
Please provide a description of the function:def get_img_data(f, maxsize = (1200, 850), first = False):
img = Image.open(f)
img.thumbnail(maxsize)
if first: # tkinter is inactive the first time
bio = io.BytesIO()
img.save(bio, format = "PNG")
del img
... | [
"Generate image data using PIL\n "
] |
Please provide a description of the function:def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False):
delay = None
try: # One could use UDP here, but it's obscure
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except sock... | [
"\n Returns either the delay (in ms) or None on timeout.\n "
] |
Please provide a description of the function:def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
myStats = MyStats() # Reset the stats
mySeqNumber = 0 # Starting value
try:
destIP = socket.gethostbyname(hostname)
exc... | [
"\n Same as verbose_ping, but the results are returned as tuple\n "
] |
Please provide a description of the function:def get_page(pno, zoom = False, max_size = None, first = False):
dlist = dlist_tab[pno] # get display list of page number
if not dlist: # create if not yet there
dlist_tab[pno] = doc[pno].getDisplayList()
dlist = dlist_tab[pno]
r... | [
"Return a PNG image for a document page number.\n "
] |
Please provide a description of the function:def live_neighbours(self, i, j):
s = 0 # The total number of live neighbours.
# Loop over all the neighbours.
for x in [i - 1, i, i + 1]:
for y in [j - 1, j, j + 1]:
if (x == i and y == j):
con... | [
" Count the number of live neighbours around point (i, j). "
] |
Please provide a description of the function:def play(self):
# Write the initial configuration to file.
self.t = 1 # Current time level
while self.t <= self.T: # Evolve!
# print( "At time level %d" % t)
# Loop over each cell of the grid and apply Conway's ru... | [
" Play Conway's Game of Life. "
] |
Please provide a description of the function:def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) | [
" Returns a human readable string reprentation of bytes"
] |
Please provide a description of the function:def HowDoI():
'''
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1. Output Element that will show text in a scrolled window
2. Non-Window-Closing Buttons - The... | [] |
Please provide a description of the function:def QueryHowDoI(Query, num_answers, full_text, window:sg.Window):
'''
Kicks off a subprocess to send the 'Query' to HowDoI
Prints the result, which in this program will route to a gooeyGUI window
:param Query: text english question to ask the HowDoI web engin... | [] |
Please provide a description of the function:def list_view_on_selected(self, widget, selected_item_key):
self.lbl.set_text('List selection: ' + self.listView.children[selected_item_key].get_text()) | [
" The selection event of the listView, returns a key of the clicked event.\n You can retrieve the item rapidly\n "
] |
Please provide a description of the function:def PyplotHistogram():
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
n_bins = 10
x = np.random.randn(1000, 3)
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()
colors = ['red', 'tan... | [
"\n =============================================================\n Demo of the histogram (hist) function with multiple data sets\n =============================================================\n\n Plot histogram with multiple sample sets and demonstrate:\n\n * Use of legend with multiple sample ... |
Please provide a description of the function:def PyplotArtistBoxPlots():
import numpy as np
import matplotlib.pyplot as plt
# fake data
np.random.seed(937)
data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)
labels = list('ABCD')
fs = 10 # fontsize
# demonstrate how t... | [
"\n =========================================\n Demo of artist customization in box plots\n =========================================\n\n This example demonstrates how to use the various kwargs\n to fully customize box plots. The first figure demonstrates\n how to remove and add individual compone... |
Please provide a description of the function:def PyplotLineStyles():
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
from matplotlib.transforms import blended_transform_factory
linestyles = OrderedDict(
[('solid', (0, ())),
('loosely dott... | [
"\n ==========\n Linestyles\n ==========\n\n This examples showcases different linestyles copying those of Tikz/PGF.\n "
] |
Please provide a description of the function:def convert_tkinter_size_to_Qt(size):
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pixels (roughly)
qtsize = size[0]*DEFAULT_PIXELS_TO_CHARS_SCALING[0], size[1]*DEFAULT_PIX... | [
"\n Converts size in characters to size in pixels\n :param size: size in characters, rows\n :return: size in pixels, pixels\n "
] |
Please provide a description of the function:def create_style_from_font(font):
if font is None:
return ''
if type(font) is str:
_font = font.split(' ')
else:
_font = font
style = ''
style += 'font-family: %s;\n' % _font[0]
style += 'font-size: %spt;\n' % _font[1]
... | [
"\n Convert from font string/tyuple into a Qt style sheet string\n :param font: \"Arial 10 Bold\" or ('Arial', 10, 'Bold)\n :return: style string that can be combined with other style strings\n "
] |
Please provide a description of the function:def PopupGetFolder(message, title=None, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_... | [
"\n Display popup with text entry field and browse button. Browse for folder\n :param message:\n :param default_path:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param text_color:\n :param icon:\n :param font:\n :param no_titlebar:\n :p... |
Please provide a description of the function:def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_... | [
"\n Display popup with text entry field and browse button. Browse for file\n :param message:\n :param default_path:\n :param default_extension:\n :param save_as:\n :param file_types:\n :param no_window:\n :param size:\n :param button_color:\n :param background_color:\n :param te... |
Please provide a description of the function:def PopupGetText(message, title=None, default_text='', password_char='', size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=F... | [
"\n Display Popup with text entry field\n :param message:\n :param default_text:\n :param password_char:\n :param size:\n :param button_color:\n :param background_color:\n :param text_color:\n :param icon:\n :param font:\n :param no_titlebar:\n :param grab_anywhere:\n :param k... |
Please provide a description of the function:def Read(self, timeout=None):
'''
Reads the context menu
:param timeout: Optional. Any value other than None indicates a non-blocking read
:return:
'''
if not self.Shown:
self.Shown = True
self.TrayIcon... | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.