repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dylanaraps/pywal | pywal/__main__.py | parse_args | def parse_args(parser):
"""Process args."""
args = parser.parse_args()
if args.q:
logging.getLogger().disabled = True
sys.stdout = sys.stderr = open(os.devnull, "w")
if args.a:
util.Color.alpha_num = args.a
if args.i:
image_file = image.get(args.i, iterative=args.iterative)
colors_plain = colors.get(image_file, args.l, args.backend,
sat=args.saturate)
if args.theme:
colors_plain = theme.file(args.theme, args.l)
if args.R:
colors_plain = theme.file(os.path.join(CACHE_DIR, "colors.json"))
if args.b:
args.b = "#%s" % (args.b.strip("#"))
colors_plain["special"]["background"] = args.b
colors_plain["colors"]["color0"] = args.b
if not args.n:
wallpaper.change(colors_plain["wallpaper"])
sequences.send(colors_plain, to_send=not args.s, vte_fix=args.vte)
if sys.stdout.isatty():
colors.palette()
export.every(colors_plain)
if not args.e:
reload.env(tty_reload=not args.t)
if args.o:
for cmd in args.o:
util.disown([cmd])
if not args.e:
reload.gtk() | python | def parse_args(parser):
"""Process args."""
args = parser.parse_args()
if args.q:
logging.getLogger().disabled = True
sys.stdout = sys.stderr = open(os.devnull, "w")
if args.a:
util.Color.alpha_num = args.a
if args.i:
image_file = image.get(args.i, iterative=args.iterative)
colors_plain = colors.get(image_file, args.l, args.backend,
sat=args.saturate)
if args.theme:
colors_plain = theme.file(args.theme, args.l)
if args.R:
colors_plain = theme.file(os.path.join(CACHE_DIR, "colors.json"))
if args.b:
args.b = "#%s" % (args.b.strip("#"))
colors_plain["special"]["background"] = args.b
colors_plain["colors"]["color0"] = args.b
if not args.n:
wallpaper.change(colors_plain["wallpaper"])
sequences.send(colors_plain, to_send=not args.s, vte_fix=args.vte)
if sys.stdout.isatty():
colors.palette()
export.every(colors_plain)
if not args.e:
reload.env(tty_reload=not args.t)
if args.o:
for cmd in args.o:
util.disown([cmd])
if not args.e:
reload.gtk() | [
"def",
"parse_args",
"(",
"parser",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"args",
".",
"q",
":",
"logging",
".",
"getLogger",
"(",
")",
".",
"disabled",
"=",
"True",
"sys",
".",
"stdout",
"=",
"sys",
".",
"stderr",
"="... | Process args. | [
"Process",
"args",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/__main__.py#L150-L195 | train | 219,300 |
dylanaraps/pywal | pywal/sequences.py | set_special | def set_special(index, color, iterm_name="h", alpha=100):
"""Convert a hex color to a special sequence."""
if OS == "Darwin" and iterm_name:
return "\033]P%s%s\033\\" % (iterm_name, color.strip("#"))
if index in [11, 708] and alpha != "100":
return "\033]%s;[%s]%s\033\\" % (index, alpha, color)
return "\033]%s;%s\033\\" % (index, color) | python | def set_special(index, color, iterm_name="h", alpha=100):
"""Convert a hex color to a special sequence."""
if OS == "Darwin" and iterm_name:
return "\033]P%s%s\033\\" % (iterm_name, color.strip("#"))
if index in [11, 708] and alpha != "100":
return "\033]%s;[%s]%s\033\\" % (index, alpha, color)
return "\033]%s;%s\033\\" % (index, color) | [
"def",
"set_special",
"(",
"index",
",",
"color",
",",
"iterm_name",
"=",
"\"h\"",
",",
"alpha",
"=",
"100",
")",
":",
"if",
"OS",
"==",
"\"Darwin\"",
"and",
"iterm_name",
":",
"return",
"\"\\033]P%s%s\\033\\\\\"",
"%",
"(",
"iterm_name",
",",
"color",
"."... | Convert a hex color to a special sequence. | [
"Convert",
"a",
"hex",
"color",
"to",
"a",
"special",
"sequence",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L12-L20 | train | 219,301 |
dylanaraps/pywal | pywal/sequences.py | set_color | def set_color(index, color):
"""Convert a hex color to a text color sequence."""
if OS == "Darwin" and index < 20:
return "\033]P%1x%s\033\\" % (index, color.strip("#"))
return "\033]4;%s;%s\033\\" % (index, color) | python | def set_color(index, color):
"""Convert a hex color to a text color sequence."""
if OS == "Darwin" and index < 20:
return "\033]P%1x%s\033\\" % (index, color.strip("#"))
return "\033]4;%s;%s\033\\" % (index, color) | [
"def",
"set_color",
"(",
"index",
",",
"color",
")",
":",
"if",
"OS",
"==",
"\"Darwin\"",
"and",
"index",
"<",
"20",
":",
"return",
"\"\\033]P%1x%s\\033\\\\\"",
"%",
"(",
"index",
",",
"color",
".",
"strip",
"(",
"\"#\"",
")",
")",
"return",
"\"\\033]4;%... | Convert a hex color to a text color sequence. | [
"Convert",
"a",
"hex",
"color",
"to",
"a",
"text",
"color",
"sequence",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L23-L28 | train | 219,302 |
dylanaraps/pywal | pywal/sequences.py | create_sequences | def create_sequences(colors, vte_fix=False):
"""Create the escape sequences."""
alpha = colors["alpha"]
# Colors 0-15.
sequences = [set_color(index, colors["colors"]["color%s" % index])
for index in range(16)]
# Special colors.
# Source: https://goo.gl/KcoQgP
# 10 = foreground, 11 = background, 12 = cursor foregound
# 13 = mouse foreground, 708 = background border color.
sequences.extend([
set_special(10, colors["special"]["foreground"], "g"),
set_special(11, colors["special"]["background"], "h", alpha),
set_special(12, colors["special"]["cursor"], "l"),
set_special(13, colors["special"]["foreground"], "j"),
set_special(17, colors["special"]["foreground"], "k"),
set_special(19, colors["special"]["background"], "m"),
set_color(232, colors["special"]["background"]),
set_color(256, colors["special"]["foreground"])
])
if not vte_fix:
sequences.extend(
set_special(708, colors["special"]["background"], "", alpha)
)
if OS == "Darwin":
sequences += set_iterm_tab_color(colors["special"]["background"])
return "".join(sequences) | python | def create_sequences(colors, vte_fix=False):
"""Create the escape sequences."""
alpha = colors["alpha"]
# Colors 0-15.
sequences = [set_color(index, colors["colors"]["color%s" % index])
for index in range(16)]
# Special colors.
# Source: https://goo.gl/KcoQgP
# 10 = foreground, 11 = background, 12 = cursor foregound
# 13 = mouse foreground, 708 = background border color.
sequences.extend([
set_special(10, colors["special"]["foreground"], "g"),
set_special(11, colors["special"]["background"], "h", alpha),
set_special(12, colors["special"]["cursor"], "l"),
set_special(13, colors["special"]["foreground"], "j"),
set_special(17, colors["special"]["foreground"], "k"),
set_special(19, colors["special"]["background"], "m"),
set_color(232, colors["special"]["background"]),
set_color(256, colors["special"]["foreground"])
])
if not vte_fix:
sequences.extend(
set_special(708, colors["special"]["background"], "", alpha)
)
if OS == "Darwin":
sequences += set_iterm_tab_color(colors["special"]["background"])
return "".join(sequences) | [
"def",
"create_sequences",
"(",
"colors",
",",
"vte_fix",
"=",
"False",
")",
":",
"alpha",
"=",
"colors",
"[",
"\"alpha\"",
"]",
"# Colors 0-15.",
"sequences",
"=",
"[",
"set_color",
"(",
"index",
",",
"colors",
"[",
"\"colors\"",
"]",
"[",
"\"color%s\"",
... | Create the escape sequences. | [
"Create",
"the",
"escape",
"sequences",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L38-L69 | train | 219,303 |
dylanaraps/pywal | pywal/sequences.py | send | def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False):
"""Send colors to all open terminals."""
if OS == "Darwin":
tty_pattern = "/dev/ttys00[0-9]*"
else:
tty_pattern = "/dev/pts/[0-9]*"
sequences = create_sequences(colors, vte_fix)
# Writing to "/dev/pts/[0-9] lets you send data to open terminals.
if to_send:
for term in glob.glob(tty_pattern):
util.save_file(sequences, term)
util.save_file(sequences, os.path.join(cache_dir, "sequences"))
logging.info("Set terminal colors.") | python | def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False):
"""Send colors to all open terminals."""
if OS == "Darwin":
tty_pattern = "/dev/ttys00[0-9]*"
else:
tty_pattern = "/dev/pts/[0-9]*"
sequences = create_sequences(colors, vte_fix)
# Writing to "/dev/pts/[0-9] lets you send data to open terminals.
if to_send:
for term in glob.glob(tty_pattern):
util.save_file(sequences, term)
util.save_file(sequences, os.path.join(cache_dir, "sequences"))
logging.info("Set terminal colors.") | [
"def",
"send",
"(",
"colors",
",",
"cache_dir",
"=",
"CACHE_DIR",
",",
"to_send",
"=",
"True",
",",
"vte_fix",
"=",
"False",
")",
":",
"if",
"OS",
"==",
"\"Darwin\"",
":",
"tty_pattern",
"=",
"\"/dev/ttys00[0-9]*\"",
"else",
":",
"tty_pattern",
"=",
"\"/de... | Send colors to all open terminals. | [
"Send",
"colors",
"to",
"all",
"open",
"terminals",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L72-L88 | train | 219,304 |
dylanaraps/pywal | pywal/export.py | template | def template(colors, input_file, output_file=None):
"""Read template file, substitute markers and
save the file elsewhere."""
template_data = util.read_file_raw(input_file)
try:
template_data = "".join(template_data).format(**colors)
except ValueError:
logging.error("Syntax error in template file '%s'.", input_file)
return
util.save_file(template_data, output_file) | python | def template(colors, input_file, output_file=None):
"""Read template file, substitute markers and
save the file elsewhere."""
template_data = util.read_file_raw(input_file)
try:
template_data = "".join(template_data).format(**colors)
except ValueError:
logging.error("Syntax error in template file '%s'.", input_file)
return
util.save_file(template_data, output_file) | [
"def",
"template",
"(",
"colors",
",",
"input_file",
",",
"output_file",
"=",
"None",
")",
":",
"template_data",
"=",
"util",
".",
"read_file_raw",
"(",
"input_file",
")",
"try",
":",
"template_data",
"=",
"\"\"",
".",
"join",
"(",
"template_data",
")",
".... | Read template file, substitute markers and
save the file elsewhere. | [
"Read",
"template",
"file",
"substitute",
"markers",
"and",
"save",
"the",
"file",
"elsewhere",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L11-L22 | train | 219,305 |
dylanaraps/pywal | pywal/export.py | every | def every(colors, output_dir=CACHE_DIR):
"""Export all template files."""
colors = flatten_colors(colors)
template_dir = os.path.join(MODULE_DIR, "templates")
template_dir_user = os.path.join(CONF_DIR, "templates")
util.create_dir(template_dir_user)
join = os.path.join # Minor optimization.
for file in [*os.scandir(template_dir),
*os.scandir(template_dir_user)]:
if file.name != ".DS_Store" and not file.name.endswith(".swp"):
template(colors, file.path, join(output_dir, file.name))
logging.info("Exported all files.")
logging.info("Exported all user files.") | python | def every(colors, output_dir=CACHE_DIR):
"""Export all template files."""
colors = flatten_colors(colors)
template_dir = os.path.join(MODULE_DIR, "templates")
template_dir_user = os.path.join(CONF_DIR, "templates")
util.create_dir(template_dir_user)
join = os.path.join # Minor optimization.
for file in [*os.scandir(template_dir),
*os.scandir(template_dir_user)]:
if file.name != ".DS_Store" and not file.name.endswith(".swp"):
template(colors, file.path, join(output_dir, file.name))
logging.info("Exported all files.")
logging.info("Exported all user files.") | [
"def",
"every",
"(",
"colors",
",",
"output_dir",
"=",
"CACHE_DIR",
")",
":",
"colors",
"=",
"flatten_colors",
"(",
"colors",
")",
"template_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"MODULE_DIR",
",",
"\"templates\"",
")",
"template_dir_user",
"=",
... | Export all template files. | [
"Export",
"all",
"template",
"files",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L62-L76 | train | 219,306 |
dylanaraps/pywal | pywal/export.py | color | def color(colors, export_type, output_file=None):
"""Export a single template file."""
all_colors = flatten_colors(colors)
template_name = get_export_type(export_type)
template_file = os.path.join(MODULE_DIR, "templates", template_name)
output_file = output_file or os.path.join(CACHE_DIR, template_name)
if os.path.isfile(template_file):
template(all_colors, template_file, output_file)
logging.info("Exported %s.", export_type)
else:
logging.warning("Template '%s' doesn't exist.", export_type) | python | def color(colors, export_type, output_file=None):
"""Export a single template file."""
all_colors = flatten_colors(colors)
template_name = get_export_type(export_type)
template_file = os.path.join(MODULE_DIR, "templates", template_name)
output_file = output_file or os.path.join(CACHE_DIR, template_name)
if os.path.isfile(template_file):
template(all_colors, template_file, output_file)
logging.info("Exported %s.", export_type)
else:
logging.warning("Template '%s' doesn't exist.", export_type) | [
"def",
"color",
"(",
"colors",
",",
"export_type",
",",
"output_file",
"=",
"None",
")",
":",
"all_colors",
"=",
"flatten_colors",
"(",
"colors",
")",
"template_name",
"=",
"get_export_type",
"(",
"export_type",
")",
"template_file",
"=",
"os",
".",
"path",
... | Export a single template file. | [
"Export",
"a",
"single",
"template",
"file",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L79-L91 | train | 219,307 |
dylanaraps/pywal | pywal/reload.py | tty | def tty(tty_reload):
"""Load colors in tty."""
tty_script = os.path.join(CACHE_DIR, "colors-tty.sh")
term = os.environ.get("TERM")
if tty_reload and term == "linux":
subprocess.Popen(["sh", tty_script]) | python | def tty(tty_reload):
"""Load colors in tty."""
tty_script = os.path.join(CACHE_DIR, "colors-tty.sh")
term = os.environ.get("TERM")
if tty_reload and term == "linux":
subprocess.Popen(["sh", tty_script]) | [
"def",
"tty",
"(",
"tty_reload",
")",
":",
"tty_script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CACHE_DIR",
",",
"\"colors-tty.sh\"",
")",
"term",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"TERM\"",
")",
"if",
"tty_reload",
"and",
"term",
"==",... | Load colors in tty. | [
"Load",
"colors",
"in",
"tty",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L13-L19 | train | 219,308 |
dylanaraps/pywal | pywal/reload.py | xrdb | def xrdb(xrdb_files=None):
"""Merge the colors into the X db so new terminals use them."""
xrdb_files = xrdb_files or \
[os.path.join(CACHE_DIR, "colors.Xresources")]
if shutil.which("xrdb") and OS != "Darwin":
for file in xrdb_files:
subprocess.run(["xrdb", "-merge", "-quiet", file]) | python | def xrdb(xrdb_files=None):
"""Merge the colors into the X db so new terminals use them."""
xrdb_files = xrdb_files or \
[os.path.join(CACHE_DIR, "colors.Xresources")]
if shutil.which("xrdb") and OS != "Darwin":
for file in xrdb_files:
subprocess.run(["xrdb", "-merge", "-quiet", file]) | [
"def",
"xrdb",
"(",
"xrdb_files",
"=",
"None",
")",
":",
"xrdb_files",
"=",
"xrdb_files",
"or",
"[",
"os",
".",
"path",
".",
"join",
"(",
"CACHE_DIR",
",",
"\"colors.Xresources\"",
")",
"]",
"if",
"shutil",
".",
"which",
"(",
"\"xrdb\"",
")",
"and",
"O... | Merge the colors into the X db so new terminals use them. | [
"Merge",
"the",
"colors",
"into",
"the",
"X",
"db",
"so",
"new",
"terminals",
"use",
"them",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L22-L29 | train | 219,309 |
dylanaraps/pywal | pywal/reload.py | gtk | def gtk():
"""Reload GTK theme on the fly."""
# Here we call a Python 2 script to reload the GTK themes.
# This is done because the Python 3 GTK/Gdk libraries don't
# provide a way of doing this.
if shutil.which("python2"):
gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py")
util.disown(["python2", gtk_reload])
else:
logging.warning("GTK2 reload support requires Python 2.") | python | def gtk():
"""Reload GTK theme on the fly."""
# Here we call a Python 2 script to reload the GTK themes.
# This is done because the Python 3 GTK/Gdk libraries don't
# provide a way of doing this.
if shutil.which("python2"):
gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py")
util.disown(["python2", gtk_reload])
else:
logging.warning("GTK2 reload support requires Python 2.") | [
"def",
"gtk",
"(",
")",
":",
"# Here we call a Python 2 script to reload the GTK themes.",
"# This is done because the Python 3 GTK/Gdk libraries don't",
"# provide a way of doing this.",
"if",
"shutil",
".",
"which",
"(",
"\"python2\"",
")",
":",
"gtk_reload",
"=",
"os",
".",
... | Reload GTK theme on the fly. | [
"Reload",
"GTK",
"theme",
"on",
"the",
"fly",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L32-L42 | train | 219,310 |
dylanaraps/pywal | pywal/reload.py | env | def env(xrdb_file=None, tty_reload=True):
"""Reload environment."""
xrdb(xrdb_file)
i3()
bspwm()
kitty()
sway()
polybar()
logging.info("Reloaded environment.")
tty(tty_reload) | python | def env(xrdb_file=None, tty_reload=True):
"""Reload environment."""
xrdb(xrdb_file)
i3()
bspwm()
kitty()
sway()
polybar()
logging.info("Reloaded environment.")
tty(tty_reload) | [
"def",
"env",
"(",
"xrdb_file",
"=",
"None",
",",
"tty_reload",
"=",
"True",
")",
":",
"xrdb",
"(",
"xrdb_file",
")",
"i3",
"(",
")",
"bspwm",
"(",
")",
"kitty",
"(",
")",
"sway",
"(",
")",
"polybar",
"(",
")",
"logging",
".",
"info",
"(",
"\"Rel... | Reload environment. | [
"Reload",
"environment",
"."
] | c823e3c9dbd0100ca09caf824e77d296685a1c1e | https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L86-L95 | train | 219,311 |
IDSIA/sacred | sacred/run.py | Run.add_resource | def add_resource(self, filename):
"""Add a file as a resource.
In Sacred terminology a resource is a file that the experiment needed
to access during a run. In case of a MongoObserver that means making
sure the file is stored in the database (but avoiding duplicates) along
its path and md5 sum.
See also :py:meth:`sacred.Experiment.add_resource`.
Parameters
----------
filename : str
name of the file to be stored as a resource
"""
filename = os.path.abspath(filename)
self._emit_resource_added(filename) | python | def add_resource(self, filename):
"""Add a file as a resource.
In Sacred terminology a resource is a file that the experiment needed
to access during a run. In case of a MongoObserver that means making
sure the file is stored in the database (but avoiding duplicates) along
its path and md5 sum.
See also :py:meth:`sacred.Experiment.add_resource`.
Parameters
----------
filename : str
name of the file to be stored as a resource
"""
filename = os.path.abspath(filename)
self._emit_resource_added(filename) | [
"def",
"add_resource",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"self",
".",
"_emit_resource_added",
"(",
"filename",
")"
] | Add a file as a resource.
In Sacred terminology a resource is a file that the experiment needed
to access during a run. In case of a MongoObserver that means making
sure the file is stored in the database (but avoiding duplicates) along
its path and md5 sum.
See also :py:meth:`sacred.Experiment.add_resource`.
Parameters
----------
filename : str
name of the file to be stored as a resource | [
"Add",
"a",
"file",
"as",
"a",
"resource",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/run.py#L142-L158 | train | 219,312 |
IDSIA/sacred | sacred/initialize.py | find_best_match | def find_best_match(path, prefixes):
"""Find the Ingredient that shares the longest prefix with path."""
path_parts = path.split('.')
for p in prefixes:
if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
return '.'.join(p), '.'.join(path_parts[len(p):])
return '', path | python | def find_best_match(path, prefixes):
"""Find the Ingredient that shares the longest prefix with path."""
path_parts = path.split('.')
for p in prefixes:
if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
return '.'.join(p), '.'.join(path_parts[len(p):])
return '', path | [
"def",
"find_best_match",
"(",
"path",
",",
"prefixes",
")",
":",
"path_parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"for",
"p",
"in",
"prefixes",
":",
"if",
"len",
"(",
"p",
")",
"<=",
"len",
"(",
"path_parts",
")",
"and",
"p",
"==",
"path_... | Find the Ingredient that shares the longest prefix with path. | [
"Find",
"the",
"Ingredient",
"that",
"shares",
"the",
"longest",
"prefix",
"with",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/initialize.py#L316-L322 | train | 219,313 |
IDSIA/sacred | sacred/commands.py | _non_unicode_repr | def _non_unicode_repr(objekt, context, maxlevels, level):
"""
Used to override the pprint format method to get rid of unicode prefixes.
E.g.: 'John' instead of u'John'.
"""
repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context,
maxlevels, level)
if repr_string.startswith('u"') or repr_string.startswith("u'"):
repr_string = repr_string[1:]
return repr_string, isreadable, isrecursive | python | def _non_unicode_repr(objekt, context, maxlevels, level):
"""
Used to override the pprint format method to get rid of unicode prefixes.
E.g.: 'John' instead of u'John'.
"""
repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context,
maxlevels, level)
if repr_string.startswith('u"') or repr_string.startswith("u'"):
repr_string = repr_string[1:]
return repr_string, isreadable, isrecursive | [
"def",
"_non_unicode_repr",
"(",
"objekt",
",",
"context",
",",
"maxlevels",
",",
"level",
")",
":",
"repr_string",
",",
"isreadable",
",",
"isrecursive",
"=",
"pprint",
".",
"_safe_repr",
"(",
"objekt",
",",
"context",
",",
"maxlevels",
",",
"level",
")",
... | Used to override the pprint format method to get rid of unicode prefixes.
E.g.: 'John' instead of u'John'. | [
"Used",
"to",
"override",
"the",
"pprint",
"format",
"method",
"to",
"get",
"rid",
"of",
"unicode",
"prefixes",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L40-L50 | train | 219,314 |
IDSIA/sacred | sacred/commands.py | print_config | def print_config(_run):
"""
Print the updated configuration and exit.
Text is highlighted:
green: value modified
blue: value added
red: value modified but type changed
"""
final_config = _run.config
config_mods = _run.config_modifications
print(_format_config(final_config, config_mods)) | python | def print_config(_run):
"""
Print the updated configuration and exit.
Text is highlighted:
green: value modified
blue: value added
red: value modified but type changed
"""
final_config = _run.config
config_mods = _run.config_modifications
print(_format_config(final_config, config_mods)) | [
"def",
"print_config",
"(",
"_run",
")",
":",
"final_config",
"=",
"_run",
".",
"config",
"config_mods",
"=",
"_run",
".",
"config_modifications",
"print",
"(",
"_format_config",
"(",
"final_config",
",",
"config_mods",
")",
")"
] | Print the updated configuration and exit.
Text is highlighted:
green: value modified
blue: value added
red: value modified but type changed | [
"Print",
"the",
"updated",
"configuration",
"and",
"exit",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L57-L68 | train | 219,315 |
IDSIA/sacred | sacred/commands.py | print_named_configs | def print_named_configs(ingredient):
"""
Returns a command function that prints the available named configs for the
ingredient and all sub-ingredients and exits.
The output is highlighted:
white: config names
grey: doc
"""
def print_named_configs():
"""Print the available named configs and exit."""
named_configs = OrderedDict(ingredient.gather_named_configs())
print(_format_named_configs(named_configs, 2))
return print_named_configs | python | def print_named_configs(ingredient):
"""
Returns a command function that prints the available named configs for the
ingredient and all sub-ingredients and exits.
The output is highlighted:
white: config names
grey: doc
"""
def print_named_configs():
"""Print the available named configs and exit."""
named_configs = OrderedDict(ingredient.gather_named_configs())
print(_format_named_configs(named_configs, 2))
return print_named_configs | [
"def",
"print_named_configs",
"(",
"ingredient",
")",
":",
"def",
"print_named_configs",
"(",
")",
":",
"\"\"\"Print the available named configs and exit.\"\"\"",
"named_configs",
"=",
"OrderedDict",
"(",
"ingredient",
".",
"gather_named_configs",
"(",
")",
")",
"print",
... | Returns a command function that prints the available named configs for the
ingredient and all sub-ingredients and exits.
The output is highlighted:
white: config names
grey: doc | [
"Returns",
"a",
"command",
"function",
"that",
"prints",
"the",
"available",
"named",
"configs",
"for",
"the",
"ingredient",
"and",
"all",
"sub",
"-",
"ingredients",
"and",
"exits",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L94-L109 | train | 219,316 |
IDSIA/sacred | sacred/commands.py | print_dependencies | def print_dependencies(_run):
"""Print the detected source-files and dependencies."""
print('Dependencies:')
for dep in _run.experiment_info['dependencies']:
pack, _, version = dep.partition('==')
print(' {:<20} == {}'.format(pack, version))
print('\nSources:')
for source, digest in _run.experiment_info['sources']:
print(' {:<43} {}'.format(source, digest))
if _run.experiment_info['repositories']:
repos = _run.experiment_info['repositories']
print('\nVersion Control:')
for repo in repos:
mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' '
print('{} {:<43} {}'.format(mod, repo['url'], repo['commit']) +
ENDC)
print('') | python | def print_dependencies(_run):
"""Print the detected source-files and dependencies."""
print('Dependencies:')
for dep in _run.experiment_info['dependencies']:
pack, _, version = dep.partition('==')
print(' {:<20} == {}'.format(pack, version))
print('\nSources:')
for source, digest in _run.experiment_info['sources']:
print(' {:<43} {}'.format(source, digest))
if _run.experiment_info['repositories']:
repos = _run.experiment_info['repositories']
print('\nVersion Control:')
for repo in repos:
mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' '
print('{} {:<43} {}'.format(mod, repo['url'], repo['commit']) +
ENDC)
print('') | [
"def",
"print_dependencies",
"(",
"_run",
")",
":",
"print",
"(",
"'Dependencies:'",
")",
"for",
"dep",
"in",
"_run",
".",
"experiment_info",
"[",
"'dependencies'",
"]",
":",
"pack",
",",
"_",
",",
"version",
"=",
"dep",
".",
"partition",
"(",
"'=='",
")... | Print the detected source-files and dependencies. | [
"Print",
"the",
"detected",
"source",
"-",
"files",
"and",
"dependencies",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L119-L137 | train | 219,317 |
IDSIA/sacred | sacred/commands.py | save_config | def save_config(_config, _log, config_filename='config.json'):
"""
Store the updated configuration in a file.
By default uses the filename "config.json", but that can be changed by
setting the config_filename config entry.
"""
if 'config_filename' in _config:
del _config['config_filename']
_log.info('Saving config to "{}"'.format(config_filename))
save_config_file(flatten(_config), config_filename) | python | def save_config(_config, _log, config_filename='config.json'):
"""
Store the updated configuration in a file.
By default uses the filename "config.json", but that can be changed by
setting the config_filename config entry.
"""
if 'config_filename' in _config:
del _config['config_filename']
_log.info('Saving config to "{}"'.format(config_filename))
save_config_file(flatten(_config), config_filename) | [
"def",
"save_config",
"(",
"_config",
",",
"_log",
",",
"config_filename",
"=",
"'config.json'",
")",
":",
"if",
"'config_filename'",
"in",
"_config",
":",
"del",
"_config",
"[",
"'config_filename'",
"]",
"_log",
".",
"info",
"(",
"'Saving config to \"{}\"'",
".... | Store the updated configuration in a file.
By default uses the filename "config.json", but that can be changed by
setting the config_filename config entry. | [
"Store",
"the",
"updated",
"configuration",
"in",
"a",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L140-L150 | train | 219,318 |
IDSIA/sacred | sacred/observers/file_storage.py | FileStorageObserver.log_metrics | def log_metrics(self, metrics_by_name, info):
"""Store new measurements into metrics.json.
"""
try:
metrics_path = os.path.join(self.dir, "metrics.json")
with open(metrics_path, 'r') as f:
saved_metrics = json.load(f)
except IOError:
# We haven't recorded anything yet. Start Collecting.
saved_metrics = {}
for metric_name, metric_ptr in metrics_by_name.items():
if metric_name not in saved_metrics:
saved_metrics[metric_name] = {"values": [],
"steps": [],
"timestamps": []}
saved_metrics[metric_name]["values"] += metric_ptr["values"]
saved_metrics[metric_name]["steps"] += metric_ptr["steps"]
# Manually convert them to avoid passing a datetime dtype handler
# when we're trying to convert into json.
timestamps_norm = [ts.isoformat()
for ts in metric_ptr["timestamps"]]
saved_metrics[metric_name]["timestamps"] += timestamps_norm
self.save_json(saved_metrics, 'metrics.json') | python | def log_metrics(self, metrics_by_name, info):
"""Store new measurements into metrics.json.
"""
try:
metrics_path = os.path.join(self.dir, "metrics.json")
with open(metrics_path, 'r') as f:
saved_metrics = json.load(f)
except IOError:
# We haven't recorded anything yet. Start Collecting.
saved_metrics = {}
for metric_name, metric_ptr in metrics_by_name.items():
if metric_name not in saved_metrics:
saved_metrics[metric_name] = {"values": [],
"steps": [],
"timestamps": []}
saved_metrics[metric_name]["values"] += metric_ptr["values"]
saved_metrics[metric_name]["steps"] += metric_ptr["steps"]
# Manually convert them to avoid passing a datetime dtype handler
# when we're trying to convert into json.
timestamps_norm = [ts.isoformat()
for ts in metric_ptr["timestamps"]]
saved_metrics[metric_name]["timestamps"] += timestamps_norm
self.save_json(saved_metrics, 'metrics.json') | [
"def",
"log_metrics",
"(",
"self",
",",
"metrics_by_name",
",",
"info",
")",
":",
"try",
":",
"metrics_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
",",
"\"metrics.json\"",
")",
"with",
"open",
"(",
"metrics_path",
",",
"'r'",
"... | Store new measurements into metrics.json. | [
"Store",
"new",
"measurements",
"into",
"metrics",
".",
"json",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/file_storage.py#L217-L244 | train | 219,319 |
IDSIA/sacred | sacred/config/custom_containers.py | is_different | def is_different(old_value, new_value):
"""Numpy aware comparison between two values."""
if opt.has_numpy:
return not opt.np.array_equal(old_value, new_value)
else:
return old_value != new_value | python | def is_different(old_value, new_value):
"""Numpy aware comparison between two values."""
if opt.has_numpy:
return not opt.np.array_equal(old_value, new_value)
else:
return old_value != new_value | [
"def",
"is_different",
"(",
"old_value",
",",
"new_value",
")",
":",
"if",
"opt",
".",
"has_numpy",
":",
"return",
"not",
"opt",
".",
"np",
".",
"array_equal",
"(",
"old_value",
",",
"new_value",
")",
"else",
":",
"return",
"old_value",
"!=",
"new_value"
] | Numpy aware comparison between two values. | [
"Numpy",
"aware",
"comparison",
"between",
"two",
"values",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/custom_containers.py#L273-L278 | train | 219,320 |
IDSIA/sacred | sacred/experiment.py | Experiment.main | def main(self, function):
"""
Decorator to define the main function of the experiment.
The main function of an experiment is the default command that is being
run when no command is specified, or when calling the run() method.
Usually it is more convenient to use ``automain`` instead.
"""
captured = self.command(function)
self.default_command = captured.__name__
return captured | python | def main(self, function):
"""
Decorator to define the main function of the experiment.
The main function of an experiment is the default command that is being
run when no command is specified, or when calling the run() method.
Usually it is more convenient to use ``automain`` instead.
"""
captured = self.command(function)
self.default_command = captured.__name__
return captured | [
"def",
"main",
"(",
"self",
",",
"function",
")",
":",
"captured",
"=",
"self",
".",
"command",
"(",
"function",
")",
"self",
".",
"default_command",
"=",
"captured",
".",
"__name__",
"return",
"captured"
] | Decorator to define the main function of the experiment.
The main function of an experiment is the default command that is being
run when no command is specified, or when calling the run() method.
Usually it is more convenient to use ``automain`` instead. | [
"Decorator",
"to",
"define",
"the",
"main",
"function",
"of",
"the",
"experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L96-L107 | train | 219,321 |
IDSIA/sacred | sacred/experiment.py | Experiment.option_hook | def option_hook(self, function):
"""
Decorator for adding an option hook function.
An option hook is a function that is called right before a run
is created. It receives (and potentially modifies) the options
dictionary. That is, the dictionary of commandline options used for
this run.
.. note::
The decorated function MUST have an argument called options.
The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,
but changing them has no effect. Only modification on
flags (entries starting with ``'--'``) are considered.
"""
sig = Signature(function)
if "options" not in sig.arguments:
raise KeyError("option_hook functions must have an argument called"
" 'options', but got {}".format(sig.arguments))
self.option_hooks.append(function)
return function | python | def option_hook(self, function):
"""
Decorator for adding an option hook function.
An option hook is a function that is called right before a run
is created. It receives (and potentially modifies) the options
dictionary. That is, the dictionary of commandline options used for
this run.
.. note::
The decorated function MUST have an argument called options.
The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,
but changing them has no effect. Only modification on
flags (entries starting with ``'--'``) are considered.
"""
sig = Signature(function)
if "options" not in sig.arguments:
raise KeyError("option_hook functions must have an argument called"
" 'options', but got {}".format(sig.arguments))
self.option_hooks.append(function)
return function | [
"def",
"option_hook",
"(",
"self",
",",
"function",
")",
":",
"sig",
"=",
"Signature",
"(",
"function",
")",
"if",
"\"options\"",
"not",
"in",
"sig",
".",
"arguments",
":",
"raise",
"KeyError",
"(",
"\"option_hook functions must have an argument called\"",
"\" 'op... | Decorator for adding an option hook function.
An option hook is a function that is called right before a run
is created. It receives (and potentially modifies) the options
dictionary. That is, the dictionary of commandline options used for
this run.
.. note::
The decorated function MUST have an argument called options.
The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,
but changing them has no effect. Only modification on
flags (entries starting with ``'--'``) are considered. | [
"Decorator",
"for",
"adding",
"an",
"option",
"hook",
"function",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L143-L164 | train | 219,322 |
IDSIA/sacred | sacred/experiment.py | Experiment.get_usage | def get_usage(self, program_name=None):
"""Get the commandline usage string for this experiment."""
program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy',
self.base_dir)
commands = OrderedDict(self.gather_commands())
options = gather_command_line_options()
long_usage = format_usage(program_name, self.doc, commands, options)
# internal usage is a workaround because docopt cannot handle spaces
# in program names. So for parsing we use 'dummy' as the program name.
# for printing help etc. we want to use the actual program name.
internal_usage = format_usage('dummy', self.doc, commands, options)
short_usage = printable_usage(long_usage)
return short_usage, long_usage, internal_usage | python | def get_usage(self, program_name=None):
"""Get the commandline usage string for this experiment."""
program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy',
self.base_dir)
commands = OrderedDict(self.gather_commands())
options = gather_command_line_options()
long_usage = format_usage(program_name, self.doc, commands, options)
# internal usage is a workaround because docopt cannot handle spaces
# in program names. So for parsing we use 'dummy' as the program name.
# for printing help etc. we want to use the actual program name.
internal_usage = format_usage('dummy', self.doc, commands, options)
short_usage = printable_usage(long_usage)
return short_usage, long_usage, internal_usage | [
"def",
"get_usage",
"(",
"self",
",",
"program_name",
"=",
"None",
")",
":",
"program_name",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"program_name",
"or",
"sys",
".",
"argv",
"[",
"0",
"]",
"or",
"'Dummy'",
",",
"self",
".",
"base_dir",
")",
"co... | Get the commandline usage string for this experiment. | [
"Get",
"the",
"commandline",
"usage",
"string",
"for",
"this",
"experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L168-L180 | train | 219,323 |
IDSIA/sacred | sacred/experiment.py | Experiment.run | def run(self, command_name=None, config_updates=None, named_configs=(),
meta_info=None, options=None):
"""
Run the main function of the experiment or a given command.
Parameters
----------
command_name : str, optional
Name of the command to be run. Defaults to main function.
config_updates : dict, optional
Changes to the configuration as a nested dictionary
named_configs : list[str], optional
list of names of named_configs to use
meta_info : dict, optional
Additional meta information for this run.
options : dict, optional
Dictionary of options to use
Returns
-------
sacred.run.Run
the Run object corresponding to the finished run
"""
run = self._create_run(command_name, config_updates, named_configs,
meta_info, options)
run()
return run | python | def run(self, command_name=None, config_updates=None, named_configs=(),
meta_info=None, options=None):
"""
Run the main function of the experiment or a given command.
Parameters
----------
command_name : str, optional
Name of the command to be run. Defaults to main function.
config_updates : dict, optional
Changes to the configuration as a nested dictionary
named_configs : list[str], optional
list of names of named_configs to use
meta_info : dict, optional
Additional meta information for this run.
options : dict, optional
Dictionary of options to use
Returns
-------
sacred.run.Run
the Run object corresponding to the finished run
"""
run = self._create_run(command_name, config_updates, named_configs,
meta_info, options)
run()
return run | [
"def",
"run",
"(",
"self",
",",
"command_name",
"=",
"None",
",",
"config_updates",
"=",
"None",
",",
"named_configs",
"=",
"(",
")",
",",
"meta_info",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"run",
"=",
"self",
".",
"_create_run",
"(",
"... | Run the main function of the experiment or a given command.
Parameters
----------
command_name : str, optional
Name of the command to be run. Defaults to main function.
config_updates : dict, optional
Changes to the configuration as a nested dictionary
named_configs : list[str], optional
list of names of named_configs to use
meta_info : dict, optional
Additional meta information for this run.
options : dict, optional
Dictionary of options to use
Returns
-------
sacred.run.Run
the Run object corresponding to the finished run | [
"Run",
"the",
"main",
"function",
"of",
"the",
"experiment",
"or",
"a",
"given",
"command",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L182-L213 | train | 219,324 |
IDSIA/sacred | sacred/experiment.py | Experiment.run_command | def run_command(self, command_name, config_updates=None,
named_configs=(), args=(), meta_info=None):
"""Run the command with the given name.
.. note:: Deprecated in Sacred 0.7
run_command() will be removed in Sacred 1.0.
It is replaced by run() which can now also handle command_names.
"""
import warnings
warnings.warn("run_command is deprecated. Use run instead",
DeprecationWarning)
return self.run(command_name, config_updates, named_configs, meta_info,
args) | python | def run_command(self, command_name, config_updates=None,
named_configs=(), args=(), meta_info=None):
"""Run the command with the given name.
.. note:: Deprecated in Sacred 0.7
run_command() will be removed in Sacred 1.0.
It is replaced by run() which can now also handle command_names.
"""
import warnings
warnings.warn("run_command is deprecated. Use run instead",
DeprecationWarning)
return self.run(command_name, config_updates, named_configs, meta_info,
args) | [
"def",
"run_command",
"(",
"self",
",",
"command_name",
",",
"config_updates",
"=",
"None",
",",
"named_configs",
"=",
"(",
")",
",",
"args",
"=",
"(",
")",
",",
"meta_info",
"=",
"None",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\... | Run the command with the given name.
.. note:: Deprecated in Sacred 0.7
run_command() will be removed in Sacred 1.0.
It is replaced by run() which can now also handle command_names. | [
"Run",
"the",
"command",
"with",
"the",
"given",
"name",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L215-L227 | train | 219,325 |
IDSIA/sacred | sacred/experiment.py | Experiment.run_commandline | def run_commandline(self, argv=None):
"""
Run the command-line interface of this experiment.
If ``argv`` is omitted it defaults to ``sys.argv``.
Parameters
----------
argv : list[str] or str, optional
Command-line as string or list of strings like ``sys.argv``.
Returns
-------
sacred.run.Run
The Run object corresponding to the finished run.
"""
argv = ensure_wellformed_argv(argv)
short_usage, usage, internal_usage = self.get_usage()
args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False)
cmd_name = args.get('COMMAND') or self.default_command
config_updates, named_configs = get_config_updates(args['UPDATE'])
err = self._check_command(cmd_name)
if not args['help'] and err:
print(short_usage)
print(err)
exit(1)
if self._handle_help(args, usage):
exit()
try:
return self.run(cmd_name, config_updates, named_configs, {}, args)
except Exception as e:
if self.current_run:
debug = self.current_run.debug
else:
# The usual command line options are applied after the run
# object is built completely. Some exceptions (e.g.
# ConfigAddedError) are raised before this. In these cases,
# the debug flag must be checked manually.
debug = args.get('--debug', False)
if debug:
# Debug: Don't change behaviour, just re-raise exception
raise
elif self.current_run and self.current_run.pdb:
# Print exception and attach pdb debugger
import traceback
import pdb
traceback.print_exception(*sys.exc_info())
pdb.post_mortem()
else:
# Handle pretty printing of exceptions. This includes
# filtering the stacktrace and printing the usage, as
# specified by the exceptions attributes
if isinstance(e, SacredError):
print(format_sacred_error(e, short_usage), file=sys.stderr)
else:
print_filtered_stacktrace()
exit(1) | python | def run_commandline(self, argv=None):
"""
Run the command-line interface of this experiment.
If ``argv`` is omitted it defaults to ``sys.argv``.
Parameters
----------
argv : list[str] or str, optional
Command-line as string or list of strings like ``sys.argv``.
Returns
-------
sacred.run.Run
The Run object corresponding to the finished run.
"""
argv = ensure_wellformed_argv(argv)
short_usage, usage, internal_usage = self.get_usage()
args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False)
cmd_name = args.get('COMMAND') or self.default_command
config_updates, named_configs = get_config_updates(args['UPDATE'])
err = self._check_command(cmd_name)
if not args['help'] and err:
print(short_usage)
print(err)
exit(1)
if self._handle_help(args, usage):
exit()
try:
return self.run(cmd_name, config_updates, named_configs, {}, args)
except Exception as e:
if self.current_run:
debug = self.current_run.debug
else:
# The usual command line options are applied after the run
# object is built completely. Some exceptions (e.g.
# ConfigAddedError) are raised before this. In these cases,
# the debug flag must be checked manually.
debug = args.get('--debug', False)
if debug:
# Debug: Don't change behaviour, just re-raise exception
raise
elif self.current_run and self.current_run.pdb:
# Print exception and attach pdb debugger
import traceback
import pdb
traceback.print_exception(*sys.exc_info())
pdb.post_mortem()
else:
# Handle pretty printing of exceptions. This includes
# filtering the stacktrace and printing the usage, as
# specified by the exceptions attributes
if isinstance(e, SacredError):
print(format_sacred_error(e, short_usage), file=sys.stderr)
else:
print_filtered_stacktrace()
exit(1) | [
"def",
"run_commandline",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"ensure_wellformed_argv",
"(",
"argv",
")",
"short_usage",
",",
"usage",
",",
"internal_usage",
"=",
"self",
".",
"get_usage",
"(",
")",
"args",
"=",
"docopt",
"(",
"... | Run the command-line interface of this experiment.
If ``argv`` is omitted it defaults to ``sys.argv``.
Parameters
----------
argv : list[str] or str, optional
Command-line as string or list of strings like ``sys.argv``.
Returns
-------
sacred.run.Run
The Run object corresponding to the finished run. | [
"Run",
"the",
"command",
"-",
"line",
"interface",
"of",
"this",
"experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L229-L291 | train | 219,326 |
IDSIA/sacred | sacred/experiment.py | Experiment.get_default_options | def get_default_options(self):
"""Get a dictionary of default options as used with run.
Returns
-------
dict
A dictionary containing option keys of the form '--beat_interval'.
Their values are boolean if the option is a flag, otherwise None or
its default value.
"""
_, _, internal_usage = self.get_usage()
args = docopt(internal_usage, [])
return {k: v for k, v in args.items() if k.startswith('--')} | python | def get_default_options(self):
"""Get a dictionary of default options as used with run.
Returns
-------
dict
A dictionary containing option keys of the form '--beat_interval'.
Their values are boolean if the option is a flag, otherwise None or
its default value.
"""
_, _, internal_usage = self.get_usage()
args = docopt(internal_usage, [])
return {k: v for k, v in args.items() if k.startswith('--')} | [
"def",
"get_default_options",
"(",
"self",
")",
":",
"_",
",",
"_",
",",
"internal_usage",
"=",
"self",
".",
"get_usage",
"(",
")",
"args",
"=",
"docopt",
"(",
"internal_usage",
",",
"[",
"]",
")",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v"... | Get a dictionary of default options as used with run.
Returns
-------
dict
A dictionary containing option keys of the form '--beat_interval'.
Their values are boolean if the option is a flag, otherwise None or
its default value. | [
"Get",
"a",
"dictionary",
"of",
"default",
"options",
"as",
"used",
"with",
"run",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L420-L433 | train | 219,327 |
IDSIA/sacred | sacred/config/signature.py | Signature.construct_arguments | def construct_arguments(self, args, kwargs, options, bound=False):
"""
Construct args list and kwargs dictionary for this signature.
They are created such that:
- the original explicit call arguments (args, kwargs) are preserved
- missing arguments are filled in by name using options (if possible)
- default arguments are overridden by options
- TypeError is thrown if:
* kwargs contains one or more unexpected keyword arguments
* conflicting values for a parameter in both args and kwargs
* there is an unfilled parameter at the end of this process
"""
expected_args = self._get_expected_args(bound)
self._assert_no_unexpected_args(expected_args, args)
self._assert_no_unexpected_kwargs(expected_args, kwargs)
self._assert_no_duplicate_args(expected_args, args, kwargs)
args, kwargs = self._fill_in_options(args, kwargs, options, bound)
self._assert_no_missing_args(args, kwargs, bound)
return args, kwargs | python | def construct_arguments(self, args, kwargs, options, bound=False):
"""
Construct args list and kwargs dictionary for this signature.
They are created such that:
- the original explicit call arguments (args, kwargs) are preserved
- missing arguments are filled in by name using options (if possible)
- default arguments are overridden by options
- TypeError is thrown if:
* kwargs contains one or more unexpected keyword arguments
* conflicting values for a parameter in both args and kwargs
* there is an unfilled parameter at the end of this process
"""
expected_args = self._get_expected_args(bound)
self._assert_no_unexpected_args(expected_args, args)
self._assert_no_unexpected_kwargs(expected_args, kwargs)
self._assert_no_duplicate_args(expected_args, args, kwargs)
args, kwargs = self._fill_in_options(args, kwargs, options, bound)
self._assert_no_missing_args(args, kwargs, bound)
return args, kwargs | [
"def",
"construct_arguments",
"(",
"self",
",",
"args",
",",
"kwargs",
",",
"options",
",",
"bound",
"=",
"False",
")",
":",
"expected_args",
"=",
"self",
".",
"_get_expected_args",
"(",
"bound",
")",
"self",
".",
"_assert_no_unexpected_args",
"(",
"expected_a... | Construct args list and kwargs dictionary for this signature.
They are created such that:
- the original explicit call arguments (args, kwargs) are preserved
- missing arguments are filled in by name using options (if possible)
- default arguments are overridden by options
- TypeError is thrown if:
* kwargs contains one or more unexpected keyword arguments
* conflicting values for a parameter in both args and kwargs
* there is an unfilled parameter at the end of this process | [
"Construct",
"args",
"list",
"and",
"kwargs",
"dictionary",
"for",
"this",
"signature",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/signature.py#L83-L104 | train | 219,328 |
IDSIA/sacred | sacred/stdout_capturing.py | flush | def flush():
"""Try to flush all stdio buffers, both from python and from C."""
try:
sys.stdout.flush()
sys.stderr.flush()
except (AttributeError, ValueError, IOError):
pass # unsupported
try:
libc.fflush(None)
except (AttributeError, ValueError, IOError):
pass | python | def flush():
"""Try to flush all stdio buffers, both from python and from C."""
try:
sys.stdout.flush()
sys.stderr.flush()
except (AttributeError, ValueError, IOError):
pass # unsupported
try:
libc.fflush(None)
except (AttributeError, ValueError, IOError):
pass | [
"def",
"flush",
"(",
")",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"except",
"(",
"AttributeError",
",",
"ValueError",
",",
"IOError",
")",
":",
"pass",
"# unsupported",
"try",
":",
... | Try to flush all stdio buffers, both from python and from C. | [
"Try",
"to",
"flush",
"all",
"stdio",
"buffers",
"both",
"from",
"python",
"and",
"from",
"C",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L16-L26 | train | 219,329 |
IDSIA/sacred | sacred/stdout_capturing.py | tee_output_python | def tee_output_python():
"""Duplicate sys.stdout and sys.stderr to new StringIO."""
buffer = StringIO()
out = CapturedStdout(buffer)
orig_stdout, orig_stderr = sys.stdout, sys.stderr
flush()
sys.stdout = TeeingStreamProxy(sys.stdout, buffer)
sys.stderr = TeeingStreamProxy(sys.stderr, buffer)
try:
yield out
finally:
flush()
out.finalize()
sys.stdout, sys.stderr = orig_stdout, orig_stderr | python | def tee_output_python():
"""Duplicate sys.stdout and sys.stderr to new StringIO."""
buffer = StringIO()
out = CapturedStdout(buffer)
orig_stdout, orig_stderr = sys.stdout, sys.stderr
flush()
sys.stdout = TeeingStreamProxy(sys.stdout, buffer)
sys.stderr = TeeingStreamProxy(sys.stderr, buffer)
try:
yield out
finally:
flush()
out.finalize()
sys.stdout, sys.stderr = orig_stdout, orig_stderr | [
"def",
"tee_output_python",
"(",
")",
":",
"buffer",
"=",
"StringIO",
"(",
")",
"out",
"=",
"CapturedStdout",
"(",
"buffer",
")",
"orig_stdout",
",",
"orig_stderr",
"=",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"flush",
"(",
")",
"sys",
".",
"s... | Duplicate sys.stdout and sys.stderr to new StringIO. | [
"Duplicate",
"sys",
".",
"stdout",
"and",
"sys",
".",
"stderr",
"to",
"new",
"StringIO",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L97-L110 | train | 219,330 |
IDSIA/sacred | sacred/stdout_capturing.py | tee_output_fd | def tee_output_fd():
"""Duplicate stdout and stderr to a file on the file descriptor level."""
with NamedTemporaryFile(mode='w+') as target:
original_stdout_fd = 1
original_stderr_fd = 2
target_fd = target.fileno()
# Save a copy of the original stdout and stderr file descriptors
saved_stdout_fd = os.dup(original_stdout_fd)
saved_stderr_fd = os.dup(original_stderr_fd)
try:
# we call os.setsid to move process to a new process group
# this is done to avoid receiving KeyboardInterrupts (see #149)
# in Python 3 we could just pass start_new_session=True
tee_stdout = subprocess.Popen(
['tee', '-a', target.name], preexec_fn=os.setsid,
stdin=subprocess.PIPE, stdout=1)
tee_stderr = subprocess.Popen(
['tee', '-a', target.name], preexec_fn=os.setsid,
stdin=subprocess.PIPE, stdout=2)
except (FileNotFoundError, OSError, AttributeError):
# No tee found in this operating system. Trying to use a python
# implementation of tee. However this is slow and error-prone.
tee_stdout = subprocess.Popen(
[sys.executable, "-m", "sacred.pytee"],
stdin=subprocess.PIPE, stderr=target_fd)
tee_stderr = subprocess.Popen(
[sys.executable, "-m", "sacred.pytee"],
stdin=subprocess.PIPE, stdout=target_fd)
flush()
os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd)
os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd)
out = CapturedStdout(target)
try:
yield out # let the caller do their printing
finally:
flush()
# then redirect stdout back to the saved fd
tee_stdout.stdin.close()
tee_stderr.stdin.close()
# restore original fds
os.dup2(saved_stdout_fd, original_stdout_fd)
os.dup2(saved_stderr_fd, original_stderr_fd)
# wait for completion of the tee processes with timeout
# implemented using a timer because timeout support is py3 only
def kill_tees():
tee_stdout.kill()
tee_stderr.kill()
tee_timer = Timer(1, kill_tees)
try:
tee_timer.start()
tee_stdout.wait()
tee_stderr.wait()
finally:
tee_timer.cancel()
os.close(saved_stdout_fd)
os.close(saved_stderr_fd)
out.finalize() | python | def tee_output_fd():
"""Duplicate stdout and stderr to a file on the file descriptor level."""
with NamedTemporaryFile(mode='w+') as target:
original_stdout_fd = 1
original_stderr_fd = 2
target_fd = target.fileno()
# Save a copy of the original stdout and stderr file descriptors
saved_stdout_fd = os.dup(original_stdout_fd)
saved_stderr_fd = os.dup(original_stderr_fd)
try:
# we call os.setsid to move process to a new process group
# this is done to avoid receiving KeyboardInterrupts (see #149)
# in Python 3 we could just pass start_new_session=True
tee_stdout = subprocess.Popen(
['tee', '-a', target.name], preexec_fn=os.setsid,
stdin=subprocess.PIPE, stdout=1)
tee_stderr = subprocess.Popen(
['tee', '-a', target.name], preexec_fn=os.setsid,
stdin=subprocess.PIPE, stdout=2)
except (FileNotFoundError, OSError, AttributeError):
# No tee found in this operating system. Trying to use a python
# implementation of tee. However this is slow and error-prone.
tee_stdout = subprocess.Popen(
[sys.executable, "-m", "sacred.pytee"],
stdin=subprocess.PIPE, stderr=target_fd)
tee_stderr = subprocess.Popen(
[sys.executable, "-m", "sacred.pytee"],
stdin=subprocess.PIPE, stdout=target_fd)
flush()
os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd)
os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd)
out = CapturedStdout(target)
try:
yield out # let the caller do their printing
finally:
flush()
# then redirect stdout back to the saved fd
tee_stdout.stdin.close()
tee_stderr.stdin.close()
# restore original fds
os.dup2(saved_stdout_fd, original_stdout_fd)
os.dup2(saved_stderr_fd, original_stderr_fd)
# wait for completion of the tee processes with timeout
# implemented using a timer because timeout support is py3 only
def kill_tees():
tee_stdout.kill()
tee_stderr.kill()
tee_timer = Timer(1, kill_tees)
try:
tee_timer.start()
tee_stdout.wait()
tee_stderr.wait()
finally:
tee_timer.cancel()
os.close(saved_stdout_fd)
os.close(saved_stderr_fd)
out.finalize() | [
"def",
"tee_output_fd",
"(",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+'",
")",
"as",
"target",
":",
"original_stdout_fd",
"=",
"1",
"original_stderr_fd",
"=",
"2",
"target_fd",
"=",
"target",
".",
"fileno",
"(",
")",
"# Save a copy of the ... | Duplicate stdout and stderr to a file on the file descriptor level. | [
"Duplicate",
"stdout",
"and",
"stderr",
"to",
"a",
"file",
"on",
"the",
"file",
"descriptor",
"level",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L118-L183 | train | 219,331 |
IDSIA/sacred | sacred/arg_parser.py | get_config_updates | def get_config_updates(updates):
"""
Parse the UPDATES given on the commandline.
Parameters
----------
updates (list[str]):
list of update-strings of the form NAME=LITERAL or just NAME.
Returns
-------
(dict, list):
Config updates and named configs to use
"""
config_updates = {}
named_configs = []
if not updates:
return config_updates, named_configs
for upd in updates:
if upd == '':
continue
path, sep, value = upd.partition('=')
if sep == '=':
path = path.strip() # get rid of surrounding whitespace
value = value.strip() # get rid of surrounding whitespace
set_by_dotted_path(config_updates, path, _convert_value(value))
else:
named_configs.append(path)
return config_updates, named_configs | python | def get_config_updates(updates):
"""
Parse the UPDATES given on the commandline.
Parameters
----------
updates (list[str]):
list of update-strings of the form NAME=LITERAL or just NAME.
Returns
-------
(dict, list):
Config updates and named configs to use
"""
config_updates = {}
named_configs = []
if not updates:
return config_updates, named_configs
for upd in updates:
if upd == '':
continue
path, sep, value = upd.partition('=')
if sep == '=':
path = path.strip() # get rid of surrounding whitespace
value = value.strip() # get rid of surrounding whitespace
set_by_dotted_path(config_updates, path, _convert_value(value))
else:
named_configs.append(path)
return config_updates, named_configs | [
"def",
"get_config_updates",
"(",
"updates",
")",
":",
"config_updates",
"=",
"{",
"}",
"named_configs",
"=",
"[",
"]",
"if",
"not",
"updates",
":",
"return",
"config_updates",
",",
"named_configs",
"for",
"upd",
"in",
"updates",
":",
"if",
"upd",
"==",
"'... | Parse the UPDATES given on the commandline.
Parameters
----------
updates (list[str]):
list of update-strings of the form NAME=LITERAL or just NAME.
Returns
-------
(dict, list):
Config updates and named configs to use | [
"Parse",
"the",
"UPDATES",
"given",
"on",
"the",
"commandline",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L46-L75 | train | 219,332 |
IDSIA/sacred | sacred/arg_parser.py | _format_options_usage | def _format_options_usage(options):
"""
Format the Options-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description for the commandline options
"""
options_usage = ""
for op in options:
short, long = op.get_flags()
if op.arg:
flag = "{short} {arg} {long}={arg}".format(
short=short, long=long, arg=op.arg)
else:
flag = "{short} {long}".format(short=short, long=long)
wrapped_description = textwrap.wrap(inspect.cleandoc(op.__doc__),
width=79,
initial_indent=' ' * 32,
subsequent_indent=' ' * 32)
wrapped_description = "\n".join(wrapped_description).strip()
options_usage += " {0:28} {1}\n".format(flag, wrapped_description)
return options_usage | python | def _format_options_usage(options):
"""
Format the Options-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description for the commandline options
"""
options_usage = ""
for op in options:
short, long = op.get_flags()
if op.arg:
flag = "{short} {arg} {long}={arg}".format(
short=short, long=long, arg=op.arg)
else:
flag = "{short} {long}".format(short=short, long=long)
wrapped_description = textwrap.wrap(inspect.cleandoc(op.__doc__),
width=79,
initial_indent=' ' * 32,
subsequent_indent=' ' * 32)
wrapped_description = "\n".join(wrapped_description).strip()
options_usage += " {0:28} {1}\n".format(flag, wrapped_description)
return options_usage | [
"def",
"_format_options_usage",
"(",
"options",
")",
":",
"options_usage",
"=",
"\"\"",
"for",
"op",
"in",
"options",
":",
"short",
",",
"long",
"=",
"op",
".",
"get_flags",
"(",
")",
"if",
"op",
".",
"arg",
":",
"flag",
"=",
"\"{short} {arg} {long}={arg}\... | Format the Options-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description for the commandline options | [
"Format",
"the",
"Options",
"-",
"part",
"of",
"the",
"usage",
"text",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L78-L109 | train | 219,333 |
IDSIA/sacred | sacred/arg_parser.py | _format_arguments_usage | def _format_arguments_usage(options):
"""
Construct the Arguments-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description of the arguments supported by the
commandline options.
"""
argument_usage = ""
for op in options:
if op.arg and op.arg_description:
wrapped_description = textwrap.wrap(op.arg_description,
width=79,
initial_indent=' ' * 12,
subsequent_indent=' ' * 12)
wrapped_description = "\n".join(wrapped_description).strip()
argument_usage += " {0:8} {1}\n".format(op.arg,
wrapped_description)
return argument_usage | python | def _format_arguments_usage(options):
"""
Construct the Arguments-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description of the arguments supported by the
commandline options.
"""
argument_usage = ""
for op in options:
if op.arg and op.arg_description:
wrapped_description = textwrap.wrap(op.arg_description,
width=79,
initial_indent=' ' * 12,
subsequent_indent=' ' * 12)
wrapped_description = "\n".join(wrapped_description).strip()
argument_usage += " {0:8} {1}\n".format(op.arg,
wrapped_description)
return argument_usage | [
"def",
"_format_arguments_usage",
"(",
"options",
")",
":",
"argument_usage",
"=",
"\"\"",
"for",
"op",
"in",
"options",
":",
"if",
"op",
".",
"arg",
"and",
"op",
".",
"arg_description",
":",
"wrapped_description",
"=",
"textwrap",
".",
"wrap",
"(",
"op",
... | Construct the Arguments-part of the usage text.
Parameters
----------
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
Text formatted as a description of the arguments supported by the
commandline options. | [
"Construct",
"the",
"Arguments",
"-",
"part",
"of",
"the",
"usage",
"text",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L112-L138 | train | 219,334 |
IDSIA/sacred | sacred/arg_parser.py | _format_command_usage | def _format_command_usage(commands):
"""
Construct the Commands-part of the usage text.
Parameters
----------
commands : dict[str, func]
dictionary of supported commands.
Each entry should be a tuple of (name, function).
Returns
-------
str
Text formatted as a description of the commands.
"""
if not commands:
return ""
command_usage = "\nCommands:\n"
cmd_len = max([len(c) for c in commands] + [8])
command_doc = OrderedDict(
[(cmd_name, _get_first_line_of_docstring(cmd_doc))
for cmd_name, cmd_doc in commands.items()])
for cmd_name, cmd_doc in command_doc.items():
command_usage += (" {:%d} {}\n" % cmd_len).format(cmd_name, cmd_doc)
return command_usage | python | def _format_command_usage(commands):
"""
Construct the Commands-part of the usage text.
Parameters
----------
commands : dict[str, func]
dictionary of supported commands.
Each entry should be a tuple of (name, function).
Returns
-------
str
Text formatted as a description of the commands.
"""
if not commands:
return ""
command_usage = "\nCommands:\n"
cmd_len = max([len(c) for c in commands] + [8])
command_doc = OrderedDict(
[(cmd_name, _get_first_line_of_docstring(cmd_doc))
for cmd_name, cmd_doc in commands.items()])
for cmd_name, cmd_doc in command_doc.items():
command_usage += (" {:%d} {}\n" % cmd_len).format(cmd_name, cmd_doc)
return command_usage | [
"def",
"_format_command_usage",
"(",
"commands",
")",
":",
"if",
"not",
"commands",
":",
"return",
"\"\"",
"command_usage",
"=",
"\"\\nCommands:\\n\"",
"cmd_len",
"=",
"max",
"(",
"[",
"len",
"(",
"c",
")",
"for",
"c",
"in",
"commands",
"]",
"+",
"[",
"8... | Construct the Commands-part of the usage text.
Parameters
----------
commands : dict[str, func]
dictionary of supported commands.
Each entry should be a tuple of (name, function).
Returns
-------
str
Text formatted as a description of the commands. | [
"Construct",
"the",
"Commands",
"-",
"part",
"of",
"the",
"usage",
"text",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L141-L166 | train | 219,335 |
IDSIA/sacred | sacred/arg_parser.py | format_usage | def format_usage(program_name, description, commands=None, options=()):
"""
Construct the usage text.
Parameters
----------
program_name : str
Usually the name of the python file that contains the experiment.
description : str
description of this experiment (usually the docstring).
commands : dict[str, func]
Dictionary of supported commands.
Each entry should be a tuple of (name, function).
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
The complete formatted usage text for this experiment.
It adheres to the structure required by ``docopt``.
"""
usage = USAGE_TEMPLATE.format(
program_name=cmd_quote(program_name),
description=description.strip() if description else '',
options=_format_options_usage(options),
arguments=_format_arguments_usage(options),
commands=_format_command_usage(commands)
)
return usage | python | def format_usage(program_name, description, commands=None, options=()):
"""
Construct the usage text.
Parameters
----------
program_name : str
Usually the name of the python file that contains the experiment.
description : str
description of this experiment (usually the docstring).
commands : dict[str, func]
Dictionary of supported commands.
Each entry should be a tuple of (name, function).
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
The complete formatted usage text for this experiment.
It adheres to the structure required by ``docopt``.
"""
usage = USAGE_TEMPLATE.format(
program_name=cmd_quote(program_name),
description=description.strip() if description else '',
options=_format_options_usage(options),
arguments=_format_arguments_usage(options),
commands=_format_command_usage(commands)
)
return usage | [
"def",
"format_usage",
"(",
"program_name",
",",
"description",
",",
"commands",
"=",
"None",
",",
"options",
"=",
"(",
")",
")",
":",
"usage",
"=",
"USAGE_TEMPLATE",
".",
"format",
"(",
"program_name",
"=",
"cmd_quote",
"(",
"program_name",
")",
",",
"des... | Construct the usage text.
Parameters
----------
program_name : str
Usually the name of the python file that contains the experiment.
description : str
description of this experiment (usually the docstring).
commands : dict[str, func]
Dictionary of supported commands.
Each entry should be a tuple of (name, function).
options : list[sacred.commandline_options.CommandLineOption]
A list of all supported commandline options.
Returns
-------
str
The complete formatted usage text for this experiment.
It adheres to the structure required by ``docopt``. | [
"Construct",
"the",
"usage",
"text",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L169-L199 | train | 219,336 |
IDSIA/sacred | sacred/arg_parser.py | _convert_value | def _convert_value(value):
"""Parse string as python literal if possible and fallback to string."""
try:
return restore(ast.literal_eval(value))
except (ValueError, SyntaxError):
if SETTINGS.COMMAND_LINE.STRICT_PARSING:
raise
# use as string if nothing else worked
return value | python | def _convert_value(value):
"""Parse string as python literal if possible and fallback to string."""
try:
return restore(ast.literal_eval(value))
except (ValueError, SyntaxError):
if SETTINGS.COMMAND_LINE.STRICT_PARSING:
raise
# use as string if nothing else worked
return value | [
"def",
"_convert_value",
"(",
"value",
")",
":",
"try",
":",
"return",
"restore",
"(",
"ast",
".",
"literal_eval",
"(",
"value",
")",
")",
"except",
"(",
"ValueError",
",",
"SyntaxError",
")",
":",
"if",
"SETTINGS",
".",
"COMMAND_LINE",
".",
"STRICT_PARSIN... | Parse string as python literal if possible and fallback to string. | [
"Parse",
"string",
"as",
"python",
"literal",
"if",
"possible",
"and",
"fallback",
"to",
"string",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L206-L214 | train | 219,337 |
IDSIA/sacred | sacred/utils.py | iterate_flattened_separately | def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""
if manually_sorted_keys is None:
manually_sorted_keys = []
for key in manually_sorted_keys:
if key in dictionary:
yield key, dictionary[key]
single_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(not dictionary[key] or
not isinstance(dictionary[key], dict))]
for key in sorted(single_line_keys):
yield key, dictionary[key]
multi_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(dictionary[key] and
isinstance(dictionary[key], dict))]
for key in sorted(multi_line_keys):
yield key, PATHCHANGE
for k, val in iterate_flattened_separately(dictionary[key],
manually_sorted_keys):
yield join_paths(key, k), val | python | def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""
if manually_sorted_keys is None:
manually_sorted_keys = []
for key in manually_sorted_keys:
if key in dictionary:
yield key, dictionary[key]
single_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(not dictionary[key] or
not isinstance(dictionary[key], dict))]
for key in sorted(single_line_keys):
yield key, dictionary[key]
multi_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(dictionary[key] and
isinstance(dictionary[key], dict))]
for key in sorted(multi_line_keys):
yield key, PATHCHANGE
for k, val in iterate_flattened_separately(dictionary[key],
manually_sorted_keys):
yield join_paths(key, k), val | [
"def",
"iterate_flattened_separately",
"(",
"dictionary",
",",
"manually_sorted_keys",
"=",
"None",
")",
":",
"if",
"manually_sorted_keys",
"is",
"None",
":",
"manually_sorted_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"manually_sorted_keys",
":",
"if",
"key",
"in"... | Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf. | [
"Recursively",
"iterate",
"over",
"the",
"items",
"of",
"a",
"dictionary",
"in",
"a",
"special",
"order",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L325-L354 | train | 219,338 |
IDSIA/sacred | sacred/utils.py | iterate_flattened | def iterate_flattened(d):
"""
Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf.
"""
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict) and value:
for k, v in iterate_flattened(d[key]):
yield join_paths(key, k), v
else:
yield key, value | python | def iterate_flattened(d):
"""
Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf.
"""
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict) and value:
for k, v in iterate_flattened(d[key]):
yield join_paths(key, k), v
else:
yield key, value | [
"def",
"iterate_flattened",
"(",
"d",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"d",
".",
"keys",
"(",
")",
")",
":",
"value",
"=",
"d",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"value",
":",
"for",
"k",
",... | Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf. | [
"Recursively",
"iterate",
"over",
"the",
"items",
"of",
"a",
"dictionary",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L357-L369 | train | 219,339 |
IDSIA/sacred | sacred/utils.py | set_by_dotted_path | def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}}
"""
split_path = path.split('.')
current_option = d
for p in split_path[:-1]:
if p not in current_option:
current_option[p] = dict()
current_option = current_option[p]
current_option[split_path[-1]] = value | python | def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}}
"""
split_path = path.split('.')
current_option = d
for p in split_path[:-1]:
if p not in current_option:
current_option[p] = dict()
current_option = current_option[p]
current_option[split_path[-1]] = value | [
"def",
"set_by_dotted_path",
"(",
"d",
",",
"path",
",",
"value",
")",
":",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
"[",
":",
"-",
"1",
"]",
":",
"if",
"p",
"not",
"in",
... | Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}} | [
"Set",
"an",
"entry",
"in",
"a",
"nested",
"dict",
"using",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L372-L395 | train | 219,340 |
IDSIA/sacred | sacred/utils.py | get_by_dotted_path | def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
if p not in current_option:
return default
current_option = current_option[p]
return current_option | python | def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
if p not in current_option:
return default
current_option = current_option[p]
return current_option | [
"def",
"get_by_dotted_path",
"(",
"d",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"d",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
... | Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12 | [
"Get",
"an",
"entry",
"from",
"nested",
"dictionaries",
"using",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L398-L414 | train | 219,341 |
IDSIA/sacred | sacred/utils.py | iter_path_splits | def iter_path_splits(path):
"""
Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')]
"""
split_path = path.split('.')
for i in range(len(split_path)):
p1 = join_paths(*split_path[:i])
p2 = join_paths(*split_path[i:])
yield p1, p2 | python | def iter_path_splits(path):
"""
Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')]
"""
split_path = path.split('.')
for i in range(len(split_path)):
p1 = join_paths(*split_path[:i])
p2 = join_paths(*split_path[i:])
yield p1, p2 | [
"def",
"iter_path_splits",
"(",
"path",
")",
":",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"split_path",
")",
")",
":",
"p1",
"=",
"join_paths",
"(",
"*",
"split_path",
"[",
":",
"i",
"]"... | Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')] | [
"Iterate",
"over",
"possible",
"splits",
"of",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L417-L433 | train | 219,342 |
IDSIA/sacred | sacred/utils.py | is_prefix | def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | python | def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | [
"def",
"is_prefix",
"(",
"pre_path",
",",
"path",
")",
":",
"pre_path",
"=",
"pre_path",
".",
"strip",
"(",
"'.'",
")",
"path",
"=",
"path",
".",
"strip",
"(",
"'.'",
")",
"return",
"not",
"pre_path",
"or",
"path",
".",
"startswith",
"(",
"pre_path",
... | Return True if pre_path is a path-prefix of path. | [
"Return",
"True",
"if",
"pre_path",
"is",
"a",
"path",
"-",
"prefix",
"of",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L454-L458 | train | 219,343 |
IDSIA/sacred | sacred/utils.py | rel_path | def rel_path(base, path):
"""Return path relative to base."""
if base == path:
return ''
assert is_prefix(base, path), "{} not a prefix of {}".format(base, path)
return path[len(base):].strip('.') | python | def rel_path(base, path):
"""Return path relative to base."""
if base == path:
return ''
assert is_prefix(base, path), "{} not a prefix of {}".format(base, path)
return path[len(base):].strip('.') | [
"def",
"rel_path",
"(",
"base",
",",
"path",
")",
":",
"if",
"base",
"==",
"path",
":",
"return",
"''",
"assert",
"is_prefix",
"(",
"base",
",",
"path",
")",
",",
"\"{} not a prefix of {}\"",
".",
"format",
"(",
"base",
",",
"path",
")",
"return",
"pat... | Return path relative to base. | [
"Return",
"path",
"relative",
"to",
"base",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L461-L466 | train | 219,344 |
IDSIA/sacred | sacred/utils.py | convert_to_nested_dict | def convert_to_nested_dict(dotted_dict):
"""Convert a dict with dotted path keys to corresponding nested dict."""
nested_dict = {}
for k, v in iterate_flattened(dotted_dict):
set_by_dotted_path(nested_dict, k, v)
return nested_dict | python | def convert_to_nested_dict(dotted_dict):
"""Convert a dict with dotted path keys to corresponding nested dict."""
nested_dict = {}
for k, v in iterate_flattened(dotted_dict):
set_by_dotted_path(nested_dict, k, v)
return nested_dict | [
"def",
"convert_to_nested_dict",
"(",
"dotted_dict",
")",
":",
"nested_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iterate_flattened",
"(",
"dotted_dict",
")",
":",
"set_by_dotted_path",
"(",
"nested_dict",
",",
"k",
",",
"v",
")",
"return",
"nested_d... | Convert a dict with dotted path keys to corresponding nested dict. | [
"Convert",
"a",
"dict",
"with",
"dotted",
"path",
"keys",
"to",
"corresponding",
"nested",
"dict",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L469-L474 | train | 219,345 |
IDSIA/sacred | sacred/utils.py | format_filtered_stacktrace | def format_filtered_stacktrace(filter_traceback='default'):
"""
Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
# determine if last exception is from sacred
current_tb = exc_traceback
while current_tb.tb_next is not None:
current_tb = current_tb.tb_next
if filter_traceback == 'default' \
and _is_sacred_frame(current_tb.tb_frame):
# just print sacred internal trace
header = ["Exception originated from within Sacred.\n"
"Traceback (most recent calls):\n"]
texts = tb.format_exception(exc_type, exc_value, current_tb)
return ''.join(header + texts[1:]).strip()
elif filter_traceback in ('default', 'always'):
# print filtered stacktrace
if sys.version_info >= (3, 5):
tb_exception = \
tb.TracebackException(exc_type, exc_value, exc_traceback,
limit=None)
return ''.join(filtered_traceback_format(tb_exception))
else:
s = "Traceback (most recent calls WITHOUT Sacred internals):"
current_tb = exc_traceback
while current_tb is not None:
if not _is_sacred_frame(current_tb.tb_frame):
tb.print_tb(current_tb, 1)
current_tb = current_tb.tb_next
s += "\n".join(tb.format_exception_only(exc_type,
exc_value)).strip()
return s
elif filter_traceback == 'never':
# print full stacktrace
return '\n'.join(
tb.format_exception(exc_type, exc_value, exc_traceback))
else:
raise ValueError('Unknown value for filter_traceback: ' +
filter_traceback) | python | def format_filtered_stacktrace(filter_traceback='default'):
"""
Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
# determine if last exception is from sacred
current_tb = exc_traceback
while current_tb.tb_next is not None:
current_tb = current_tb.tb_next
if filter_traceback == 'default' \
and _is_sacred_frame(current_tb.tb_frame):
# just print sacred internal trace
header = ["Exception originated from within Sacred.\n"
"Traceback (most recent calls):\n"]
texts = tb.format_exception(exc_type, exc_value, current_tb)
return ''.join(header + texts[1:]).strip()
elif filter_traceback in ('default', 'always'):
# print filtered stacktrace
if sys.version_info >= (3, 5):
tb_exception = \
tb.TracebackException(exc_type, exc_value, exc_traceback,
limit=None)
return ''.join(filtered_traceback_format(tb_exception))
else:
s = "Traceback (most recent calls WITHOUT Sacred internals):"
current_tb = exc_traceback
while current_tb is not None:
if not _is_sacred_frame(current_tb.tb_frame):
tb.print_tb(current_tb, 1)
current_tb = current_tb.tb_next
s += "\n".join(tb.format_exception_only(exc_type,
exc_value)).strip()
return s
elif filter_traceback == 'never':
# print full stacktrace
return '\n'.join(
tb.format_exception(exc_type, exc_value, exc_traceback))
else:
raise ValueError('Unknown value for filter_traceback: ' +
filter_traceback) | [
"def",
"format_filtered_stacktrace",
"(",
"filter_traceback",
"=",
"'default'",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# determine if last exception is from sacred",
"current_tb",
"=",
"exc_traceback",
"whil... | Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'. | [
"Returns",
"the",
"traceback",
"as",
"string",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L485-L533 | train | 219,346 |
IDSIA/sacred | sacred/utils.py | get_inheritors | def get_inheritors(cls):
"""Get a set of all classes that inherit from the given class."""
subclasses = set()
work = [cls]
while work:
parent = work.pop()
for child in parent.__subclasses__():
if child not in subclasses:
subclasses.add(child)
work.append(child)
return subclasses | python | def get_inheritors(cls):
"""Get a set of all classes that inherit from the given class."""
subclasses = set()
work = [cls]
while work:
parent = work.pop()
for child in parent.__subclasses__():
if child not in subclasses:
subclasses.add(child)
work.append(child)
return subclasses | [
"def",
"get_inheritors",
"(",
"cls",
")",
":",
"subclasses",
"=",
"set",
"(",
")",
"work",
"=",
"[",
"cls",
"]",
"while",
"work",
":",
"parent",
"=",
"work",
".",
"pop",
"(",
")",
"for",
"child",
"in",
"parent",
".",
"__subclasses__",
"(",
")",
":"... | Get a set of all classes that inherit from the given class. | [
"Get",
"a",
"set",
"of",
"all",
"classes",
"that",
"inherit",
"from",
"the",
"given",
"class",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L593-L603 | train | 219,347 |
IDSIA/sacred | sacred/utils.py | apply_backspaces_and_linefeeds | def apply_backspaces_and_linefeeds(text):
"""
Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk.
"""
orig_lines = text.split('\n')
orig_lines_len = len(orig_lines)
new_lines = []
for orig_line_idx, orig_line in enumerate(orig_lines):
chars, cursor = [], 0
orig_line_len = len(orig_line)
for orig_char_idx, orig_char in enumerate(orig_line):
if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
orig_line_idx != orig_lines_len - 1):
cursor = 0
elif orig_char == '\b':
cursor = max(0, cursor - 1)
else:
if (orig_char == '\r' and
orig_char_idx == orig_line_len - 1 and
orig_line_idx == orig_lines_len - 1):
cursor = len(chars)
if cursor == len(chars):
chars.append(orig_char)
else:
chars[cursor] = orig_char
cursor += 1
new_lines.append(''.join(chars))
return '\n'.join(new_lines) | python | def apply_backspaces_and_linefeeds(text):
"""
Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk.
"""
orig_lines = text.split('\n')
orig_lines_len = len(orig_lines)
new_lines = []
for orig_line_idx, orig_line in enumerate(orig_lines):
chars, cursor = [], 0
orig_line_len = len(orig_line)
for orig_char_idx, orig_char in enumerate(orig_line):
if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
orig_line_idx != orig_lines_len - 1):
cursor = 0
elif orig_char == '\b':
cursor = max(0, cursor - 1)
else:
if (orig_char == '\r' and
orig_char_idx == orig_line_len - 1 and
orig_line_idx == orig_lines_len - 1):
cursor = len(chars)
if cursor == len(chars):
chars.append(orig_char)
else:
chars[cursor] = orig_char
cursor += 1
new_lines.append(''.join(chars))
return '\n'.join(new_lines) | [
"def",
"apply_backspaces_and_linefeeds",
"(",
"text",
")",
":",
"orig_lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"orig_lines_len",
"=",
"len",
"(",
"orig_lines",
")",
"new_lines",
"=",
"[",
"]",
"for",
"orig_line_idx",
",",
"orig_line",
"in",
"enu... | Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk. | [
"Interpret",
"backspaces",
"and",
"linefeeds",
"in",
"text",
"like",
"a",
"terminal",
"would",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L614-L647 | train | 219,348 |
IDSIA/sacred | sacred/utils.py | module_is_imported | def module_is_imported(modname, scope=None):
"""Checks if a module is imported within the current namespace."""
# return early if modname is not even cached
if not module_is_in_cache(modname):
return False
if scope is None: # use globals() of the caller by default
scope = inspect.stack()[1][0].f_globals
for m in scope.values():
if isinstance(m, type(sys)) and m.__name__ == modname:
return True
return False | python | def module_is_imported(modname, scope=None):
"""Checks if a module is imported within the current namespace."""
# return early if modname is not even cached
if not module_is_in_cache(modname):
return False
if scope is None: # use globals() of the caller by default
scope = inspect.stack()[1][0].f_globals
for m in scope.values():
if isinstance(m, type(sys)) and m.__name__ == modname:
return True
return False | [
"def",
"module_is_imported",
"(",
"modname",
",",
"scope",
"=",
"None",
")",
":",
"# return early if modname is not even cached",
"if",
"not",
"module_is_in_cache",
"(",
"modname",
")",
":",
"return",
"False",
"if",
"scope",
"is",
"None",
":",
"# use globals() of th... | Checks if a module is imported within the current namespace. | [
"Checks",
"if",
"a",
"module",
"is",
"imported",
"within",
"the",
"current",
"namespace",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L664-L677 | train | 219,349 |
IDSIA/sacred | sacred/observers/telegram_obs.py | TelegramObserver.from_config | def from_config(cls, filename):
"""
Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
import telegram
d = load_config_file(filename)
request = cls.get_proxy_request(d) if 'proxy_url' in d else None
if 'token' in d and 'chat_id' in d:
bot = telegram.Bot(d['token'], request=request)
obs = cls(bot, **d)
else:
raise ValueError("Telegram configuration file must contain "
"entries for 'token' and 'chat_id'!")
for k in ['completed_text', 'interrupted_text', 'failed_text']:
if k in d:
setattr(obs, k, d[k])
return obs | python | def from_config(cls, filename):
"""
Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
import telegram
d = load_config_file(filename)
request = cls.get_proxy_request(d) if 'proxy_url' in d else None
if 'token' in d and 'chat_id' in d:
bot = telegram.Bot(d['token'], request=request)
obs = cls(bot, **d)
else:
raise ValueError("Telegram configuration file must contain "
"entries for 'token' and 'chat_id'!")
for k in ['completed_text', 'interrupted_text', 'failed_text']:
if k in d:
setattr(obs, k, d[k])
return obs | [
"def",
"from_config",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"telegram",
"d",
"=",
"load_config_file",
"(",
"filename",
")",
"request",
"=",
"cls",
".",
"get_proxy_request",
"(",
"d",
")",
"if",
"'proxy_url'",
"in",
"d",
"else",
"None",
"if",
"... | Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``. | [
"Create",
"a",
"TelegramObserver",
"from",
"a",
"given",
"configuration",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/telegram_obs.py#L73-L96 | train | 219,350 |
IDSIA/sacred | sacred/observers/mongo.py | MongoObserver.log_metrics | def log_metrics(self, metrics_by_name, info):
"""Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary.
"""
if self.metrics is None:
# If, for whatever reason, the metrics collection has not been set
# do not try to save anything there.
return
for key in metrics_by_name:
query = {"run_id": self.run_entry['_id'],
"name": key}
push = {"steps": {"$each": metrics_by_name[key]["steps"]},
"values": {"$each": metrics_by_name[key]["values"]},
"timestamps": {"$each": metrics_by_name[key]["timestamps"]}
}
update = {"$push": push}
result = self.metrics.update_one(query, update, upsert=True)
if result.upserted_id is not None:
# This is the first time we are storing this metric
info.setdefault("metrics", []) \
.append({"name": key, "id": str(result.upserted_id)}) | python | def log_metrics(self, metrics_by_name, info):
"""Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary.
"""
if self.metrics is None:
# If, for whatever reason, the metrics collection has not been set
# do not try to save anything there.
return
for key in metrics_by_name:
query = {"run_id": self.run_entry['_id'],
"name": key}
push = {"steps": {"$each": metrics_by_name[key]["steps"]},
"values": {"$each": metrics_by_name[key]["values"]},
"timestamps": {"$each": metrics_by_name[key]["timestamps"]}
}
update = {"$push": push}
result = self.metrics.update_one(query, update, upsert=True)
if result.upserted_id is not None:
# This is the first time we are storing this metric
info.setdefault("metrics", []) \
.append({"name": key, "id": str(result.upserted_id)}) | [
"def",
"log_metrics",
"(",
"self",
",",
"metrics_by_name",
",",
"info",
")",
":",
"if",
"self",
".",
"metrics",
"is",
"None",
":",
"# If, for whatever reason, the metrics collection has not been set",
"# do not try to save anything there.",
"return",
"for",
"key",
"in",
... | Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary. | [
"Store",
"new",
"measurements",
"to",
"the",
"database",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/mongo.py#L220-L244 | train | 219,351 |
IDSIA/sacred | sacred/dependencies.py | get_digest | def get_digest(filename):
"""Compute the MD5 hash for a given file."""
h = hashlib.md5()
with open(filename, 'rb') as f:
data = f.read(1 * MB)
while data:
h.update(data)
data = f.read(1 * MB)
return h.hexdigest() | python | def get_digest(filename):
"""Compute the MD5 hash for a given file."""
h = hashlib.md5()
with open(filename, 'rb') as f:
data = f.read(1 * MB)
while data:
h.update(data)
data = f.read(1 * MB)
return h.hexdigest() | [
"def",
"get_digest",
"(",
"filename",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1",
"*",
"MB",
")",
"while",
"data",
":",
"h",
... | Compute the MD5 hash for a given file. | [
"Compute",
"the",
"MD5",
"hash",
"for",
"a",
"given",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L102-L110 | train | 219,352 |
IDSIA/sacred | sacred/dependencies.py | get_commit_if_possible | def get_commit_if_possible(filename):
"""Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository
"""
# git
if opt.has_gitpython:
from git import Repo, InvalidGitRepositoryError
try:
directory = os.path.dirname(filename)
repo = Repo(directory, search_parent_directories=True)
try:
path = repo.remote().url
except ValueError:
path = 'git:/' + repo.working_dir
is_dirty = repo.is_dirty()
commit = repo.head.commit.hexsha
return path, commit, is_dirty
except (InvalidGitRepositoryError, ValueError):
pass
return None, None, None | python | def get_commit_if_possible(filename):
"""Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository
"""
# git
if opt.has_gitpython:
from git import Repo, InvalidGitRepositoryError
try:
directory = os.path.dirname(filename)
repo = Repo(directory, search_parent_directories=True)
try:
path = repo.remote().url
except ValueError:
path = 'git:/' + repo.working_dir
is_dirty = repo.is_dirty()
commit = repo.head.commit.hexsha
return path, commit, is_dirty
except (InvalidGitRepositoryError, ValueError):
pass
return None, None, None | [
"def",
"get_commit_if_possible",
"(",
"filename",
")",
":",
"# git",
"if",
"opt",
".",
"has_gitpython",
":",
"from",
"git",
"import",
"Repo",
",",
"InvalidGitRepositoryError",
"try",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
... | Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository | [
"Try",
"to",
"retrieve",
"VCS",
"information",
"for",
"a",
"given",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L113-L146 | train | 219,353 |
IDSIA/sacred | sacred/dependencies.py | convert_path_to_module_parts | def convert_path_to_module_parts(path):
"""Convert path to a python file into list of module names."""
module_parts = splitall(path)
if module_parts[-1] in ['__init__.py', '__init__.pyc']:
# remove trailing __init__.py
module_parts = module_parts[:-1]
else:
# remove file extension
module_parts[-1], _ = os.path.splitext(module_parts[-1])
return module_parts | python | def convert_path_to_module_parts(path):
"""Convert path to a python file into list of module names."""
module_parts = splitall(path)
if module_parts[-1] in ['__init__.py', '__init__.pyc']:
# remove trailing __init__.py
module_parts = module_parts[:-1]
else:
# remove file extension
module_parts[-1], _ = os.path.splitext(module_parts[-1])
return module_parts | [
"def",
"convert_path_to_module_parts",
"(",
"path",
")",
":",
"module_parts",
"=",
"splitall",
"(",
"path",
")",
"if",
"module_parts",
"[",
"-",
"1",
"]",
"in",
"[",
"'__init__.py'",
",",
"'__init__.pyc'",
"]",
":",
"# remove trailing __init__.py",
"module_parts",... | Convert path to a python file into list of module names. | [
"Convert",
"path",
"to",
"a",
"python",
"file",
"into",
"list",
"of",
"module",
"names",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L299-L308 | train | 219,354 |
IDSIA/sacred | sacred/dependencies.py | is_local_source | def is_local_source(filename, modname, experiment_path):
"""Check if a module comes from the given experiment path.
Check if a module, given by name and filename, is from (a subdirectory of )
the given experiment path.
This is used to determine if the module is a local source file, or rather
a package dependency.
Parameters
----------
filename: str
The absolute filename of the module in question.
(Usually module.__file__)
modname: str
The full name of the module including parent namespaces.
experiment_path: str
The base path of the experiment.
Returns
-------
bool:
True if the module was imported locally from (a subdir of) the
experiment_path, and False otherwise.
"""
if not is_subdir(filename, experiment_path):
return False
rel_path = os.path.relpath(filename, experiment_path)
path_parts = convert_path_to_module_parts(rel_path)
mod_parts = modname.split('.')
if path_parts == mod_parts:
return True
if len(path_parts) > len(mod_parts):
return False
abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename))
return all([p == m for p, m in zip(reversed(abs_path_parts),
reversed(mod_parts))]) | python | def is_local_source(filename, modname, experiment_path):
"""Check if a module comes from the given experiment path.
Check if a module, given by name and filename, is from (a subdirectory of )
the given experiment path.
This is used to determine if the module is a local source file, or rather
a package dependency.
Parameters
----------
filename: str
The absolute filename of the module in question.
(Usually module.__file__)
modname: str
The full name of the module including parent namespaces.
experiment_path: str
The base path of the experiment.
Returns
-------
bool:
True if the module was imported locally from (a subdir of) the
experiment_path, and False otherwise.
"""
if not is_subdir(filename, experiment_path):
return False
rel_path = os.path.relpath(filename, experiment_path)
path_parts = convert_path_to_module_parts(rel_path)
mod_parts = modname.split('.')
if path_parts == mod_parts:
return True
if len(path_parts) > len(mod_parts):
return False
abs_path_parts = convert_path_to_module_parts(os.path.abspath(filename))
return all([p == m for p, m in zip(reversed(abs_path_parts),
reversed(mod_parts))]) | [
"def",
"is_local_source",
"(",
"filename",
",",
"modname",
",",
"experiment_path",
")",
":",
"if",
"not",
"is_subdir",
"(",
"filename",
",",
"experiment_path",
")",
":",
"return",
"False",
"rel_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"filename",
... | Check if a module comes from the given experiment path.
Check if a module, given by name and filename, is from (a subdirectory of )
the given experiment path.
This is used to determine if the module is a local source file, or rather
a package dependency.
Parameters
----------
filename: str
The absolute filename of the module in question.
(Usually module.__file__)
modname: str
The full name of the module including parent namespaces.
experiment_path: str
The base path of the experiment.
Returns
-------
bool:
True if the module was imported locally from (a subdir of) the
experiment_path, and False otherwise. | [
"Check",
"if",
"a",
"module",
"comes",
"from",
"the",
"given",
"experiment",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L311-L347 | train | 219,355 |
IDSIA/sacred | sacred/dependencies.py | gather_sources_and_dependencies | def gather_sources_and_dependencies(globs, base_dir=None):
"""Scan the given globals for modules and return them as dependencies."""
experiment_path, main = get_main_file(globs)
base_dir = base_dir or experiment_path
gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']]
sources = gather_sources(globs, base_dir)
if main is not None:
sources.add(main)
gather_dependencies = dependency_discovery_strategies[
SETTINGS['DISCOVER_DEPENDENCIES']]
dependencies = gather_dependencies(globs, base_dir)
if opt.has_numpy:
# Add numpy as a dependency because it might be used for randomness
dependencies.add(PackageDependency.create(opt.np))
return main, sources, dependencies | python | def gather_sources_and_dependencies(globs, base_dir=None):
"""Scan the given globals for modules and return them as dependencies."""
experiment_path, main = get_main_file(globs)
base_dir = base_dir or experiment_path
gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']]
sources = gather_sources(globs, base_dir)
if main is not None:
sources.add(main)
gather_dependencies = dependency_discovery_strategies[
SETTINGS['DISCOVER_DEPENDENCIES']]
dependencies = gather_dependencies(globs, base_dir)
if opt.has_numpy:
# Add numpy as a dependency because it might be used for randomness
dependencies.add(PackageDependency.create(opt.np))
return main, sources, dependencies | [
"def",
"gather_sources_and_dependencies",
"(",
"globs",
",",
"base_dir",
"=",
"None",
")",
":",
"experiment_path",
",",
"main",
"=",
"get_main_file",
"(",
"globs",
")",
"base_dir",
"=",
"base_dir",
"or",
"experiment_path",
"gather_sources",
"=",
"source_discovery_st... | Scan the given globals for modules and return them as dependencies. | [
"Scan",
"the",
"given",
"globals",
"for",
"modules",
"and",
"return",
"them",
"as",
"dependencies",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L481-L501 | train | 219,356 |
IDSIA/sacred | sacred/config/utils.py | assert_is_valid_key | def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' or start with a '$'
* ENFORCE_JSONPICKLE_COMPATIBLE (default: True):
make sure the keys do not contain any reserved jsonpickle tags
This is very important. Only deactivate if you know what you are doing.
* ENFORCE_STRING (default: False):
make sure all keys are string.
* ENFORCE_VALID_PYTHON_IDENTIFIER (default: False):
make sure all keys are valid python identifiers.
Parameters
----------
key:
The key that should be checked
Raises
------
KeyError:
if the key violates any requirements
"""
if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and (
isinstance(key, basestring) and ('.' in key or key[0] == '$')):
raise KeyError('Invalid key "{}". Config-keys cannot '
'contain "." or start with "$"'.format(key))
if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \
isinstance(key, basestring) and (
key in jsonpickle.tags.RESERVED or key.startswith('json://')):
raise KeyError('Invalid key "{}". Config-keys cannot be one of the'
'reserved jsonpickle tags: {}'
.format(key, jsonpickle.tags.RESERVED))
if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and (
not isinstance(key, basestring)):
raise KeyError('Invalid key "{}". Config-keys have to be strings, '
'but was {}'.format(key, type(key)))
if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and (
isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)):
raise KeyError('Key "{}" is not a valid python identifier'
.format(key))
if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and (
isinstance(key, basestring) and '=' in key):
raise KeyError('Invalid key "{}". Config keys may not contain an'
'equals sign ("=").'.format('=')) | python | def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' or start with a '$'
* ENFORCE_JSONPICKLE_COMPATIBLE (default: True):
make sure the keys do not contain any reserved jsonpickle tags
This is very important. Only deactivate if you know what you are doing.
* ENFORCE_STRING (default: False):
make sure all keys are string.
* ENFORCE_VALID_PYTHON_IDENTIFIER (default: False):
make sure all keys are valid python identifiers.
Parameters
----------
key:
The key that should be checked
Raises
------
KeyError:
if the key violates any requirements
"""
if SETTINGS.CONFIG.ENFORCE_KEYS_MONGO_COMPATIBLE and (
isinstance(key, basestring) and ('.' in key or key[0] == '$')):
raise KeyError('Invalid key "{}". Config-keys cannot '
'contain "." or start with "$"'.format(key))
if SETTINGS.CONFIG.ENFORCE_KEYS_JSONPICKLE_COMPATIBLE and \
isinstance(key, basestring) and (
key in jsonpickle.tags.RESERVED or key.startswith('json://')):
raise KeyError('Invalid key "{}". Config-keys cannot be one of the'
'reserved jsonpickle tags: {}'
.format(key, jsonpickle.tags.RESERVED))
if SETTINGS.CONFIG.ENFORCE_STRING_KEYS and (
not isinstance(key, basestring)):
raise KeyError('Invalid key "{}". Config-keys have to be strings, '
'but was {}'.format(key, type(key)))
if SETTINGS.CONFIG.ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS and (
isinstance(key, basestring) and not PYTHON_IDENTIFIER.match(key)):
raise KeyError('Key "{}" is not a valid python identifier'
.format(key))
if SETTINGS.CONFIG.ENFORCE_KEYS_NO_EQUALS and (
isinstance(key, basestring) and '=' in key):
raise KeyError('Invalid key "{}". Config keys may not contain an'
'equals sign ("=").'.format('=')) | [
"def",
"assert_is_valid_key",
"(",
"key",
")",
":",
"if",
"SETTINGS",
".",
"CONFIG",
".",
"ENFORCE_KEYS_MONGO_COMPATIBLE",
"and",
"(",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"and",
"(",
"'.'",
"in",
"key",
"or",
"key",
"[",
"0",
"]",
"==",
"'$... | Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' or start with a '$'
* ENFORCE_JSONPICKLE_COMPATIBLE (default: True):
make sure the keys do not contain any reserved jsonpickle tags
This is very important. Only deactivate if you know what you are doing.
* ENFORCE_STRING (default: False):
make sure all keys are string.
* ENFORCE_VALID_PYTHON_IDENTIFIER (default: False):
make sure all keys are valid python identifiers.
Parameters
----------
key:
The key that should be checked
Raises
------
KeyError:
if the key violates any requirements | [
"Raise",
"KeyError",
"if",
"a",
"given",
"config",
"key",
"violates",
"any",
"requirements",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/utils.py#L13-L65 | train | 219,357 |
IDSIA/sacred | sacred/observers/slack.py | SlackObserver.from_config | def from_config(cls, filename):
"""
Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
d = load_config_file(filename)
obs = None
if 'webhook_url' in d:
obs = cls(d['webhook_url'])
else:
raise ValueError("Slack configuration file must contain "
"an entry for 'webhook_url'!")
for k in ['completed_text', 'interrupted_text', 'failed_text',
'bot_name', 'icon']:
if k in d:
setattr(obs, k, d[k])
return obs | python | def from_config(cls, filename):
"""
Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
d = load_config_file(filename)
obs = None
if 'webhook_url' in d:
obs = cls(d['webhook_url'])
else:
raise ValueError("Slack configuration file must contain "
"an entry for 'webhook_url'!")
for k in ['completed_text', 'interrupted_text', 'failed_text',
'bot_name', 'icon']:
if k in d:
setattr(obs, k, d[k])
return obs | [
"def",
"from_config",
"(",
"cls",
",",
"filename",
")",
":",
"d",
"=",
"load_config_file",
"(",
"filename",
")",
"obs",
"=",
"None",
"if",
"'webhook_url'",
"in",
"d",
":",
"obs",
"=",
"cls",
"(",
"d",
"[",
"'webhook_url'",
"]",
")",
"else",
":",
"rai... | Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and
``failed_text``. | [
"Create",
"a",
"SlackObserver",
"from",
"a",
"given",
"configuration",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/slack.py#L44-L65 | train | 219,358 |
IDSIA/sacred | sacred/host_info.py | get_host_info | def get_host_info():
"""Collect some information about the machine this experiment runs on.
Returns
-------
dict
A dictionary with information about the CPU, the OS and the
Python version of this machine.
"""
host_info = {}
for k, v in host_info_gatherers.items():
try:
host_info[k] = v()
except IgnoreHostInfo:
pass
return host_info | python | def get_host_info():
"""Collect some information about the machine this experiment runs on.
Returns
-------
dict
A dictionary with information about the CPU, the OS and the
Python version of this machine.
"""
host_info = {}
for k, v in host_info_gatherers.items():
try:
host_info[k] = v()
except IgnoreHostInfo:
pass
return host_info | [
"def",
"get_host_info",
"(",
")",
":",
"host_info",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"host_info_gatherers",
".",
"items",
"(",
")",
":",
"try",
":",
"host_info",
"[",
"k",
"]",
"=",
"v",
"(",
")",
"except",
"IgnoreHostInfo",
":",
"pass",
... | Collect some information about the machine this experiment runs on.
Returns
-------
dict
A dictionary with information about the CPU, the OS and the
Python version of this machine. | [
"Collect",
"some",
"information",
"about",
"the",
"machine",
"this",
"experiment",
"runs",
"on",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L27-L43 | train | 219,359 |
IDSIA/sacred | sacred/host_info.py | host_info_getter | def host_info_getter(func, name=None):
"""
The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when collecting the host info
using :py:func:`~sacred.host_info.get_host_info`.
Parameters
----------
func : callable
A function that can be called without arguments and returns some
json-serializable information.
name : str, optional
The name of the corresponding entry in host_info.
Defaults to the name of the function.
Returns
-------
The function itself.
"""
name = name or func.__name__
host_info_gatherers[name] = func
return func | python | def host_info_getter(func, name=None):
"""
The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when collecting the host info
using :py:func:`~sacred.host_info.get_host_info`.
Parameters
----------
func : callable
A function that can be called without arguments and returns some
json-serializable information.
name : str, optional
The name of the corresponding entry in host_info.
Defaults to the name of the function.
Returns
-------
The function itself.
"""
name = name or func.__name__
host_info_gatherers[name] = func
return func | [
"def",
"host_info_getter",
"(",
"func",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"func",
".",
"__name__",
"host_info_gatherers",
"[",
"name",
"]",
"=",
"func",
"return",
"func"
] | The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when collecting the host info
using :py:func:`~sacred.host_info.get_host_info`.
Parameters
----------
func : callable
A function that can be called without arguments and returns some
json-serializable information.
name : str, optional
The name of the corresponding entry in host_info.
Defaults to the name of the function.
Returns
-------
The function itself. | [
"The",
"decorated",
"function",
"is",
"added",
"to",
"the",
"process",
"of",
"collecting",
"the",
"host_info",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L47-L72 | train | 219,360 |
IDSIA/sacred | sacred/metrics_logger.py | linearize_metrics | def linearize_metrics(logged_metrics):
"""
Group metrics by name.
Takes a list of individual measurements, possibly belonging
to different metrics and groups them by name.
:param logged_metrics: A list of ScalarMetricLogEntries
:return: Measured values grouped by the metric name:
{"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6],
"timestamps": [datetime, datetime, datetime]},
"metric_name2": {...}}
"""
metrics_by_name = {}
for metric_entry in logged_metrics:
if metric_entry.name not in metrics_by_name:
metrics_by_name[metric_entry.name] = {
"steps": [],
"values": [],
"timestamps": [],
"name": metric_entry.name
}
metrics_by_name[metric_entry.name]["steps"] \
.append(metric_entry.step)
metrics_by_name[metric_entry.name]["values"] \
.append(metric_entry.value)
metrics_by_name[metric_entry.name]["timestamps"] \
.append(metric_entry.timestamp)
return metrics_by_name | python | def linearize_metrics(logged_metrics):
"""
Group metrics by name.
Takes a list of individual measurements, possibly belonging
to different metrics and groups them by name.
:param logged_metrics: A list of ScalarMetricLogEntries
:return: Measured values grouped by the metric name:
{"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6],
"timestamps": [datetime, datetime, datetime]},
"metric_name2": {...}}
"""
metrics_by_name = {}
for metric_entry in logged_metrics:
if metric_entry.name not in metrics_by_name:
metrics_by_name[metric_entry.name] = {
"steps": [],
"values": [],
"timestamps": [],
"name": metric_entry.name
}
metrics_by_name[metric_entry.name]["steps"] \
.append(metric_entry.step)
metrics_by_name[metric_entry.name]["values"] \
.append(metric_entry.value)
metrics_by_name[metric_entry.name]["timestamps"] \
.append(metric_entry.timestamp)
return metrics_by_name | [
"def",
"linearize_metrics",
"(",
"logged_metrics",
")",
":",
"metrics_by_name",
"=",
"{",
"}",
"for",
"metric_entry",
"in",
"logged_metrics",
":",
"if",
"metric_entry",
".",
"name",
"not",
"in",
"metrics_by_name",
":",
"metrics_by_name",
"[",
"metric_entry",
".",
... | Group metrics by name.
Takes a list of individual measurements, possibly belonging
to different metrics and groups them by name.
:param logged_metrics: A list of ScalarMetricLogEntries
:return: Measured values grouped by the metric name:
{"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6],
"timestamps": [datetime, datetime, datetime]},
"metric_name2": {...}} | [
"Group",
"metrics",
"by",
"name",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L85-L113 | train | 219,361 |
IDSIA/sacred | sacred/metrics_logger.py | MetricsLogger.get_last_metrics | def get_last_metrics(self):
"""Read all measurement events since last call of the method.
:return List[ScalarMetricLogEntry]
"""
read_up_to = self._logged_metrics.qsize()
messages = []
for i in range(read_up_to):
try:
messages.append(self._logged_metrics.get_nowait())
except Empty:
pass
return messages | python | def get_last_metrics(self):
"""Read all measurement events since last call of the method.
:return List[ScalarMetricLogEntry]
"""
read_up_to = self._logged_metrics.qsize()
messages = []
for i in range(read_up_to):
try:
messages.append(self._logged_metrics.get_nowait())
except Empty:
pass
return messages | [
"def",
"get_last_metrics",
"(",
"self",
")",
":",
"read_up_to",
"=",
"self",
".",
"_logged_metrics",
".",
"qsize",
"(",
")",
"messages",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"read_up_to",
")",
":",
"try",
":",
"messages",
".",
"append",
"(",
... | Read all measurement events since last call of the method.
:return List[ScalarMetricLogEntry] | [
"Read",
"all",
"measurement",
"events",
"since",
"last",
"call",
"of",
"the",
"method",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L57-L69 | train | 219,362 |
IDSIA/sacred | sacred/commandline_options.py | gather_command_line_options | def gather_command_line_options(filter_disabled=None):
"""Get a sorted list of all CommandLineOption subclasses."""
if filter_disabled is None:
filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS
options = [opt for opt in get_inheritors(CommandLineOption)
if not filter_disabled or opt._enabled]
return sorted(options, key=lambda opt: opt.__name__) | python | def gather_command_line_options(filter_disabled=None):
"""Get a sorted list of all CommandLineOption subclasses."""
if filter_disabled is None:
filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS
options = [opt for opt in get_inheritors(CommandLineOption)
if not filter_disabled or opt._enabled]
return sorted(options, key=lambda opt: opt.__name__) | [
"def",
"gather_command_line_options",
"(",
"filter_disabled",
"=",
"None",
")",
":",
"if",
"filter_disabled",
"is",
"None",
":",
"filter_disabled",
"=",
"not",
"SETTINGS",
".",
"COMMAND_LINE",
".",
"SHOW_DISABLED_OPTIONS",
"options",
"=",
"[",
"opt",
"for",
"opt",... | Get a sorted list of all CommandLineOption subclasses. | [
"Get",
"a",
"sorted",
"list",
"of",
"all",
"CommandLineOption",
"subclasses",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L159-L165 | train | 219,363 |
IDSIA/sacred | sacred/commandline_options.py | LoglevelOption.apply | def apply(cls, args, run):
"""Adjust the loglevel of the root-logger of this run."""
# TODO: sacred.initialize.create_run already takes care of this
try:
lvl = int(args)
except ValueError:
lvl = args
run.root_logger.setLevel(lvl) | python | def apply(cls, args, run):
"""Adjust the loglevel of the root-logger of this run."""
# TODO: sacred.initialize.create_run already takes care of this
try:
lvl = int(args)
except ValueError:
lvl = args
run.root_logger.setLevel(lvl) | [
"def",
"apply",
"(",
"cls",
",",
"args",
",",
"run",
")",
":",
"# TODO: sacred.initialize.create_run already takes care of this",
"try",
":",
"lvl",
"=",
"int",
"(",
"args",
")",
"except",
"ValueError",
":",
"lvl",
"=",
"args",
"run",
".",
"root_logger",
".",
... | Adjust the loglevel of the root-logger of this run. | [
"Adjust",
"the",
"loglevel",
"of",
"the",
"root",
"-",
"logger",
"of",
"this",
"run",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L203-L211 | train | 219,364 |
IDSIA/sacred | sacred/commandline_options.py | PriorityOption.apply | def apply(cls, args, run):
"""Add priority info for this run."""
try:
priority = float(args)
except ValueError:
raise ValueError("The PRIORITY argument must be a number! "
"(but was '{}')".format(args))
run.meta_info['priority'] = priority | python | def apply(cls, args, run):
"""Add priority info for this run."""
try:
priority = float(args)
except ValueError:
raise ValueError("The PRIORITY argument must be a number! "
"(but was '{}')".format(args))
run.meta_info['priority'] = priority | [
"def",
"apply",
"(",
"cls",
",",
"args",
",",
"run",
")",
":",
"try",
":",
"priority",
"=",
"float",
"(",
"args",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"The PRIORITY argument must be a number! \"",
"\"(but was '{}')\"",
".",
"format",
... | Add priority info for this run. | [
"Add",
"priority",
"info",
"for",
"this",
"run",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L273-L280 | train | 219,365 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.capture | def capture(self, function=None, prefix=None):
"""
Decorator to turn a function into a captured function.
The missing arguments of captured functions are automatically filled
from the configuration if possible.
See :ref:`captured_functions` for more information.
If a ``prefix`` is specified, the search for suitable
entries is performed in the corresponding subtree of the configuration.
"""
if function in self.captured_functions:
return function
captured_function = create_captured_function(function, prefix=prefix)
self.captured_functions.append(captured_function)
return captured_function | python | def capture(self, function=None, prefix=None):
"""
Decorator to turn a function into a captured function.
The missing arguments of captured functions are automatically filled
from the configuration if possible.
See :ref:`captured_functions` for more information.
If a ``prefix`` is specified, the search for suitable
entries is performed in the corresponding subtree of the configuration.
"""
if function in self.captured_functions:
return function
captured_function = create_captured_function(function, prefix=prefix)
self.captured_functions.append(captured_function)
return captured_function | [
"def",
"capture",
"(",
"self",
",",
"function",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"function",
"in",
"self",
".",
"captured_functions",
":",
"return",
"function",
"captured_function",
"=",
"create_captured_function",
"(",
"function",
",",... | Decorator to turn a function into a captured function.
The missing arguments of captured functions are automatically filled
from the configuration if possible.
See :ref:`captured_functions` for more information.
If a ``prefix`` is specified, the search for suitable
entries is performed in the corresponding subtree of the configuration. | [
"Decorator",
"to",
"turn",
"a",
"function",
"into",
"a",
"captured",
"function",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L80-L95 | train | 219,366 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.pre_run_hook | def pre_run_hook(self, func, prefix=None):
"""
Decorator to add a pre-run hook to this ingredient.
Pre-run hooks are captured functions that are run, just before the
main function is executed.
"""
cf = self.capture(func, prefix=prefix)
self.pre_run_hooks.append(cf)
return cf | python | def pre_run_hook(self, func, prefix=None):
"""
Decorator to add a pre-run hook to this ingredient.
Pre-run hooks are captured functions that are run, just before the
main function is executed.
"""
cf = self.capture(func, prefix=prefix)
self.pre_run_hooks.append(cf)
return cf | [
"def",
"pre_run_hook",
"(",
"self",
",",
"func",
",",
"prefix",
"=",
"None",
")",
":",
"cf",
"=",
"self",
".",
"capture",
"(",
"func",
",",
"prefix",
"=",
"prefix",
")",
"self",
".",
"pre_run_hooks",
".",
"append",
"(",
"cf",
")",
"return",
"cf"
] | Decorator to add a pre-run hook to this ingredient.
Pre-run hooks are captured functions that are run, just before the
main function is executed. | [
"Decorator",
"to",
"add",
"a",
"pre",
"-",
"run",
"hook",
"to",
"this",
"ingredient",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L98-L107 | train | 219,367 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.post_run_hook | def post_run_hook(self, func, prefix=None):
"""
Decorator to add a post-run hook to this ingredient.
Post-run hooks are captured functions that are run, just after the
main function is executed.
"""
cf = self.capture(func, prefix=prefix)
self.post_run_hooks.append(cf)
return cf | python | def post_run_hook(self, func, prefix=None):
"""
Decorator to add a post-run hook to this ingredient.
Post-run hooks are captured functions that are run, just after the
main function is executed.
"""
cf = self.capture(func, prefix=prefix)
self.post_run_hooks.append(cf)
return cf | [
"def",
"post_run_hook",
"(",
"self",
",",
"func",
",",
"prefix",
"=",
"None",
")",
":",
"cf",
"=",
"self",
".",
"capture",
"(",
"func",
",",
"prefix",
"=",
"prefix",
")",
"self",
".",
"post_run_hooks",
".",
"append",
"(",
"cf",
")",
"return",
"cf"
] | Decorator to add a post-run hook to this ingredient.
Post-run hooks are captured functions that are run, just after the
main function is executed. | [
"Decorator",
"to",
"add",
"a",
"post",
"-",
"run",
"hook",
"to",
"this",
"ingredient",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L110-L119 | train | 219,368 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.command | def command(self, function=None, prefix=None, unobserved=False):
"""
Decorator to define a new command for this Ingredient or Experiment.
The name of the command will be the name of the function. It can be
called from the command-line or by using the run_command function.
Commands are automatically also captured functions.
The command can be given a prefix, to restrict its configuration space
to a subtree. (see ``capture`` for more information)
A command can be made unobserved (i.e. ignoring all observers) by
passing the unobserved=True keyword argument.
"""
captured_f = self.capture(function, prefix=prefix)
captured_f.unobserved = unobserved
self.commands[function.__name__] = captured_f
return captured_f | python | def command(self, function=None, prefix=None, unobserved=False):
"""
Decorator to define a new command for this Ingredient or Experiment.
The name of the command will be the name of the function. It can be
called from the command-line or by using the run_command function.
Commands are automatically also captured functions.
The command can be given a prefix, to restrict its configuration space
to a subtree. (see ``capture`` for more information)
A command can be made unobserved (i.e. ignoring all observers) by
passing the unobserved=True keyword argument.
"""
captured_f = self.capture(function, prefix=prefix)
captured_f.unobserved = unobserved
self.commands[function.__name__] = captured_f
return captured_f | [
"def",
"command",
"(",
"self",
",",
"function",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"unobserved",
"=",
"False",
")",
":",
"captured_f",
"=",
"self",
".",
"capture",
"(",
"function",
",",
"prefix",
"=",
"prefix",
")",
"captured_f",
".",
"unobs... | Decorator to define a new command for this Ingredient or Experiment.
The name of the command will be the name of the function. It can be
called from the command-line or by using the run_command function.
Commands are automatically also captured functions.
The command can be given a prefix, to restrict its configuration space
to a subtree. (see ``capture`` for more information)
A command can be made unobserved (i.e. ignoring all observers) by
passing the unobserved=True keyword argument. | [
"Decorator",
"to",
"define",
"a",
"new",
"command",
"for",
"this",
"Ingredient",
"or",
"Experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L122-L140 | train | 219,369 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.config | def config(self, function):
"""
Decorator to add a function to the configuration of the Experiment.
The decorated function is turned into a
:class:`~sacred.config_scope.ConfigScope` and added to the
Ingredient/Experiment.
When the experiment is run, this function will also be executed and
all json-serializable local variables inside it will end up as entries
in the configuration of the experiment.
"""
self.configurations.append(ConfigScope(function))
return self.configurations[-1] | python | def config(self, function):
"""
Decorator to add a function to the configuration of the Experiment.
The decorated function is turned into a
:class:`~sacred.config_scope.ConfigScope` and added to the
Ingredient/Experiment.
When the experiment is run, this function will also be executed and
all json-serializable local variables inside it will end up as entries
in the configuration of the experiment.
"""
self.configurations.append(ConfigScope(function))
return self.configurations[-1] | [
"def",
"config",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"configurations",
".",
"append",
"(",
"ConfigScope",
"(",
"function",
")",
")",
"return",
"self",
".",
"configurations",
"[",
"-",
"1",
"]"
] | Decorator to add a function to the configuration of the Experiment.
The decorated function is turned into a
:class:`~sacred.config_scope.ConfigScope` and added to the
Ingredient/Experiment.
When the experiment is run, this function will also be executed and
all json-serializable local variables inside it will end up as entries
in the configuration of the experiment. | [
"Decorator",
"to",
"add",
"a",
"function",
"to",
"the",
"configuration",
"of",
"the",
"Experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L142-L155 | train | 219,370 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.named_config | def named_config(self, func):
"""
Decorator to turn a function into a named configuration.
See :ref:`named_configurations`.
"""
config_scope = ConfigScope(func)
self._add_named_config(func.__name__, config_scope)
return config_scope | python | def named_config(self, func):
"""
Decorator to turn a function into a named configuration.
See :ref:`named_configurations`.
"""
config_scope = ConfigScope(func)
self._add_named_config(func.__name__, config_scope)
return config_scope | [
"def",
"named_config",
"(",
"self",
",",
"func",
")",
":",
"config_scope",
"=",
"ConfigScope",
"(",
"func",
")",
"self",
".",
"_add_named_config",
"(",
"func",
".",
"__name__",
",",
"config_scope",
")",
"return",
"config_scope"
] | Decorator to turn a function into a named configuration.
See :ref:`named_configurations`. | [
"Decorator",
"to",
"turn",
"a",
"function",
"into",
"a",
"named",
"configuration",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L157-L165 | train | 219,371 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.config_hook | def config_hook(self, func):
"""
Decorator to add a config hook to this ingredient.
Config hooks need to be a function that takes 3 parameters and returns
a dictionary:
(config, command_name, logger) --> dict
Config hooks are run after the configuration of this Ingredient, but
before any further ingredient-configurations are run.
The dictionary returned by a config hook is used to update the
config updates.
Note that they are not restricted to the local namespace of the
ingredient.
"""
argspec = inspect.getargspec(func)
args = ['config', 'command_name', 'logger']
if not (argspec.args == args and argspec.varargs is None and
argspec.keywords is None and argspec.defaults is None):
raise ValueError('Wrong signature for config_hook. Expected: '
'(config, command_name, logger)')
self.config_hooks.append(func)
return self.config_hooks[-1] | python | def config_hook(self, func):
"""
Decorator to add a config hook to this ingredient.
Config hooks need to be a function that takes 3 parameters and returns
a dictionary:
(config, command_name, logger) --> dict
Config hooks are run after the configuration of this Ingredient, but
before any further ingredient-configurations are run.
The dictionary returned by a config hook is used to update the
config updates.
Note that they are not restricted to the local namespace of the
ingredient.
"""
argspec = inspect.getargspec(func)
args = ['config', 'command_name', 'logger']
if not (argspec.args == args and argspec.varargs is None and
argspec.keywords is None and argspec.defaults is None):
raise ValueError('Wrong signature for config_hook. Expected: '
'(config, command_name, logger)')
self.config_hooks.append(func)
return self.config_hooks[-1] | [
"def",
"config_hook",
"(",
"self",
",",
"func",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"args",
"=",
"[",
"'config'",
",",
"'command_name'",
",",
"'logger'",
"]",
"if",
"not",
"(",
"argspec",
".",
"args",
"==",
"args",... | Decorator to add a config hook to this ingredient.
Config hooks need to be a function that takes 3 parameters and returns
a dictionary:
(config, command_name, logger) --> dict
Config hooks are run after the configuration of this Ingredient, but
before any further ingredient-configurations are run.
The dictionary returned by a config hook is used to update the
config updates.
Note that they are not restricted to the local namespace of the
ingredient. | [
"Decorator",
"to",
"add",
"a",
"config",
"hook",
"to",
"this",
"ingredient",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L167-L189 | train | 219,372 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.add_package_dependency | def add_package_dependency(self, package_name, version):
"""
Add a package to the list of dependencies.
:param package_name: The name of the package dependency
:type package_name: str
:param version: The (minimum) version of the package
:type version: str
"""
if not PEP440_VERSION_PATTERN.match(version):
raise ValueError('Invalid Version: "{}"'.format(version))
self.dependencies.add(PackageDependency(package_name, version)) | python | def add_package_dependency(self, package_name, version):
"""
Add a package to the list of dependencies.
:param package_name: The name of the package dependency
:type package_name: str
:param version: The (minimum) version of the package
:type version: str
"""
if not PEP440_VERSION_PATTERN.match(version):
raise ValueError('Invalid Version: "{}"'.format(version))
self.dependencies.add(PackageDependency(package_name, version)) | [
"def",
"add_package_dependency",
"(",
"self",
",",
"package_name",
",",
"version",
")",
":",
"if",
"not",
"PEP440_VERSION_PATTERN",
".",
"match",
"(",
"version",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid Version: \"{}\"'",
".",
"format",
"(",
"version",
")... | Add a package to the list of dependencies.
:param package_name: The name of the package dependency
:type package_name: str
:param version: The (minimum) version of the package
:type version: str | [
"Add",
"a",
"package",
"to",
"the",
"list",
"of",
"dependencies",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L272-L283 | train | 219,373 |
IDSIA/sacred | sacred/ingredient.py | Ingredient._gather | def _gather(self, func):
"""
Function needed and used by gathering functions through the decorator
`gather_from_ingredients` in `Ingredient`. Don't use this function by
itself outside of the decorator!
By overwriting this function you can filter what is visible when
gathering something (e.g. commands). See `Experiment._gather` for an
example.
"""
for ingredient, _ in self.traverse_ingredients():
for item in func(ingredient):
yield item | python | def _gather(self, func):
"""
Function needed and used by gathering functions through the decorator
`gather_from_ingredients` in `Ingredient`. Don't use this function by
itself outside of the decorator!
By overwriting this function you can filter what is visible when
gathering something (e.g. commands). See `Experiment._gather` for an
example.
"""
for ingredient, _ in self.traverse_ingredients():
for item in func(ingredient):
yield item | [
"def",
"_gather",
"(",
"self",
",",
"func",
")",
":",
"for",
"ingredient",
",",
"_",
"in",
"self",
".",
"traverse_ingredients",
"(",
")",
":",
"for",
"item",
"in",
"func",
"(",
"ingredient",
")",
":",
"yield",
"item"
] | Function needed and used by gathering functions through the decorator
`gather_from_ingredients` in `Ingredient`. Don't use this function by
itself outside of the decorator!
By overwriting this function you can filter what is visible when
gathering something (e.g. commands). See `Experiment._gather` for an
example. | [
"Function",
"needed",
"and",
"used",
"by",
"gathering",
"functions",
"through",
"the",
"decorator",
"gather_from_ingredients",
"in",
"Ingredient",
".",
"Don",
"t",
"use",
"this",
"function",
"by",
"itself",
"outside",
"of",
"the",
"decorator!"
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L285-L297 | train | 219,374 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.gather_commands | def gather_commands(self, ingredient):
"""Collect all commands from this ingredient and its sub-ingredients.
Yields
------
cmd_name: str
The full (dotted) name of the command.
cmd: function
The corresponding captured function.
"""
for command_name, command in ingredient.commands.items():
yield join_paths(ingredient.path, command_name), command | python | def gather_commands(self, ingredient):
"""Collect all commands from this ingredient and its sub-ingredients.
Yields
------
cmd_name: str
The full (dotted) name of the command.
cmd: function
The corresponding captured function.
"""
for command_name, command in ingredient.commands.items():
yield join_paths(ingredient.path, command_name), command | [
"def",
"gather_commands",
"(",
"self",
",",
"ingredient",
")",
":",
"for",
"command_name",
",",
"command",
"in",
"ingredient",
".",
"commands",
".",
"items",
"(",
")",
":",
"yield",
"join_paths",
"(",
"ingredient",
".",
"path",
",",
"command_name",
")",
",... | Collect all commands from this ingredient and its sub-ingredients.
Yields
------
cmd_name: str
The full (dotted) name of the command.
cmd: function
The corresponding captured function. | [
"Collect",
"all",
"commands",
"from",
"this",
"ingredient",
"and",
"its",
"sub",
"-",
"ingredients",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L300-L311 | train | 219,375 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.gather_named_configs | def gather_named_configs(self, ingredient):
"""Collect all named configs from this ingredient and its
sub-ingredients.
Yields
------
config_name: str
The full (dotted) name of the named config.
config: ConfigScope or ConfigDict or basestring
The corresponding named config.
"""
for config_name, config in ingredient.named_configs.items():
yield join_paths(ingredient.path, config_name), config | python | def gather_named_configs(self, ingredient):
"""Collect all named configs from this ingredient and its
sub-ingredients.
Yields
------
config_name: str
The full (dotted) name of the named config.
config: ConfigScope or ConfigDict or basestring
The corresponding named config.
"""
for config_name, config in ingredient.named_configs.items():
yield join_paths(ingredient.path, config_name), config | [
"def",
"gather_named_configs",
"(",
"self",
",",
"ingredient",
")",
":",
"for",
"config_name",
",",
"config",
"in",
"ingredient",
".",
"named_configs",
".",
"items",
"(",
")",
":",
"yield",
"join_paths",
"(",
"ingredient",
".",
"path",
",",
"config_name",
")... | Collect all named configs from this ingredient and its
sub-ingredients.
Yields
------
config_name: str
The full (dotted) name of the named config.
config: ConfigScope or ConfigDict or basestring
The corresponding named config. | [
"Collect",
"all",
"named",
"configs",
"from",
"this",
"ingredient",
"and",
"its",
"sub",
"-",
"ingredients",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L314-L326 | train | 219,376 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.get_experiment_info | def get_experiment_info(self):
"""Get a dictionary with information about this experiment.
Contains:
* *name*: the name
* *sources*: a list of sources (filename, md5)
* *dependencies*: a list of package dependencies (name, version)
:return: experiment information
:rtype: dict
"""
dependencies = set()
sources = set()
for ing, _ in self.traverse_ingredients():
dependencies |= ing.dependencies
sources |= ing.sources
for dep in dependencies:
dep.fill_missing_version()
mainfile = (self.mainfile.to_json(self.base_dir)[0]
if self.mainfile else None)
def name_lower(d):
return d.name.lower()
return dict(
name=self.path,
base_dir=self.base_dir,
sources=[s.to_json(self.base_dir) for s in sorted(sources)],
dependencies=[d.to_json()
for d in sorted(dependencies, key=name_lower)],
repositories=collect_repositories(sources),
mainfile=mainfile
) | python | def get_experiment_info(self):
"""Get a dictionary with information about this experiment.
Contains:
* *name*: the name
* *sources*: a list of sources (filename, md5)
* *dependencies*: a list of package dependencies (name, version)
:return: experiment information
:rtype: dict
"""
dependencies = set()
sources = set()
for ing, _ in self.traverse_ingredients():
dependencies |= ing.dependencies
sources |= ing.sources
for dep in dependencies:
dep.fill_missing_version()
mainfile = (self.mainfile.to_json(self.base_dir)[0]
if self.mainfile else None)
def name_lower(d):
return d.name.lower()
return dict(
name=self.path,
base_dir=self.base_dir,
sources=[s.to_json(self.base_dir) for s in sorted(sources)],
dependencies=[d.to_json()
for d in sorted(dependencies, key=name_lower)],
repositories=collect_repositories(sources),
mainfile=mainfile
) | [
"def",
"get_experiment_info",
"(",
"self",
")",
":",
"dependencies",
"=",
"set",
"(",
")",
"sources",
"=",
"set",
"(",
")",
"for",
"ing",
",",
"_",
"in",
"self",
".",
"traverse_ingredients",
"(",
")",
":",
"dependencies",
"|=",
"ing",
".",
"dependencies"... | Get a dictionary with information about this experiment.
Contains:
* *name*: the name
* *sources*: a list of sources (filename, md5)
* *dependencies*: a list of package dependencies (name, version)
:return: experiment information
:rtype: dict | [
"Get",
"a",
"dictionary",
"with",
"information",
"about",
"this",
"experiment",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L328-L362 | train | 219,377 |
IDSIA/sacred | sacred/ingredient.py | Ingredient.traverse_ingredients | def traverse_ingredients(self):
"""Recursively traverse this ingredient and its sub-ingredients.
Yields
------
ingredient: sacred.Ingredient
The ingredient as traversed in preorder.
depth: int
The depth of the ingredient starting from 0.
Raises
------
CircularDependencyError:
If a circular structure among ingredients was detected.
"""
if self._is_traversing:
raise CircularDependencyError(ingredients=[self])
else:
self._is_traversing = True
yield self, 0
with CircularDependencyError.track(self):
for ingredient in self.ingredients:
for ingred, depth in ingredient.traverse_ingredients():
yield ingred, depth + 1
self._is_traversing = False | python | def traverse_ingredients(self):
"""Recursively traverse this ingredient and its sub-ingredients.
Yields
------
ingredient: sacred.Ingredient
The ingredient as traversed in preorder.
depth: int
The depth of the ingredient starting from 0.
Raises
------
CircularDependencyError:
If a circular structure among ingredients was detected.
"""
if self._is_traversing:
raise CircularDependencyError(ingredients=[self])
else:
self._is_traversing = True
yield self, 0
with CircularDependencyError.track(self):
for ingredient in self.ingredients:
for ingred, depth in ingredient.traverse_ingredients():
yield ingred, depth + 1
self._is_traversing = False | [
"def",
"traverse_ingredients",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_traversing",
":",
"raise",
"CircularDependencyError",
"(",
"ingredients",
"=",
"[",
"self",
"]",
")",
"else",
":",
"self",
".",
"_is_traversing",
"=",
"True",
"yield",
"self",
",",... | Recursively traverse this ingredient and its sub-ingredients.
Yields
------
ingredient: sacred.Ingredient
The ingredient as traversed in preorder.
depth: int
The depth of the ingredient starting from 0.
Raises
------
CircularDependencyError:
If a circular structure among ingredients was detected. | [
"Recursively",
"traverse",
"this",
"ingredient",
"and",
"its",
"sub",
"-",
"ingredients",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L364-L388 | train | 219,378 |
simonw/datasette | datasette/utils.py | path_from_row_pks | def path_from_row_pks(row, pks, use_rowid, quote=True):
""" Generate an optionally URL-quoted unique identifier
for a row from its primary keys."""
if use_rowid:
bits = [row['rowid']]
else:
bits = [
row[pk]["value"] if isinstance(row[pk], dict) else row[pk]
for pk in pks
]
if quote:
bits = [urllib.parse.quote_plus(str(bit)) for bit in bits]
else:
bits = [str(bit) for bit in bits]
return ','.join(bits) | python | def path_from_row_pks(row, pks, use_rowid, quote=True):
""" Generate an optionally URL-quoted unique identifier
for a row from its primary keys."""
if use_rowid:
bits = [row['rowid']]
else:
bits = [
row[pk]["value"] if isinstance(row[pk], dict) else row[pk]
for pk in pks
]
if quote:
bits = [urllib.parse.quote_plus(str(bit)) for bit in bits]
else:
bits = [str(bit) for bit in bits]
return ','.join(bits) | [
"def",
"path_from_row_pks",
"(",
"row",
",",
"pks",
",",
"use_rowid",
",",
"quote",
"=",
"True",
")",
":",
"if",
"use_rowid",
":",
"bits",
"=",
"[",
"row",
"[",
"'rowid'",
"]",
"]",
"else",
":",
"bits",
"=",
"[",
"row",
"[",
"pk",
"]",
"[",
"\"va... | Generate an optionally URL-quoted unique identifier
for a row from its primary keys. | [
"Generate",
"an",
"optionally",
"URL",
"-",
"quoted",
"unique",
"identifier",
"for",
"a",
"row",
"from",
"its",
"primary",
"keys",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L75-L90 | train | 219,379 |
simonw/datasette | datasette/utils.py | detect_primary_keys | def detect_primary_keys(conn, table):
" Figure out primary keys for a table. "
table_info_rows = [
row
for row in conn.execute(
'PRAGMA table_info("{}")'.format(table)
).fetchall()
if row[-1]
]
table_info_rows.sort(key=lambda row: row[-1])
return [str(r[1]) for r in table_info_rows] | python | def detect_primary_keys(conn, table):
" Figure out primary keys for a table. "
table_info_rows = [
row
for row in conn.execute(
'PRAGMA table_info("{}")'.format(table)
).fetchall()
if row[-1]
]
table_info_rows.sort(key=lambda row: row[-1])
return [str(r[1]) for r in table_info_rows] | [
"def",
"detect_primary_keys",
"(",
"conn",
",",
"table",
")",
":",
"table_info_rows",
"=",
"[",
"row",
"for",
"row",
"in",
"conn",
".",
"execute",
"(",
"'PRAGMA table_info(\"{}\")'",
".",
"format",
"(",
"table",
")",
")",
".",
"fetchall",
"(",
")",
"if",
... | Figure out primary keys for a table. | [
"Figure",
"out",
"primary",
"keys",
"for",
"a",
"table",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L478-L488 | train | 219,380 |
simonw/datasette | datasette/utils.py | detect_fts | def detect_fts(conn, table):
"Detect if table has a corresponding FTS virtual table and return it"
rows = conn.execute(detect_fts_sql(table)).fetchall()
if len(rows) == 0:
return None
else:
return rows[0][0] | python | def detect_fts(conn, table):
"Detect if table has a corresponding FTS virtual table and return it"
rows = conn.execute(detect_fts_sql(table)).fetchall()
if len(rows) == 0:
return None
else:
return rows[0][0] | [
"def",
"detect_fts",
"(",
"conn",
",",
"table",
")",
":",
"rows",
"=",
"conn",
".",
"execute",
"(",
"detect_fts_sql",
"(",
"table",
")",
")",
".",
"fetchall",
"(",
")",
"if",
"len",
"(",
"rows",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
... | Detect if table has a corresponding FTS virtual table and return it | [
"Detect",
"if",
"table",
"has",
"a",
"corresponding",
"FTS",
"virtual",
"table",
"and",
"return",
"it"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L545-L551 | train | 219,381 |
simonw/datasette | datasette/app.py | Datasette.metadata | def metadata(self, key=None, database=None, table=None, fallback=True):
"""
Looks up metadata, cascading backwards from specified level.
Returns None if metadata value is not found.
"""
assert not (database is None and table is not None), \
"Cannot call metadata() with table= specified but not database="
databases = self._metadata.get("databases") or {}
search_list = []
if database is not None:
search_list.append(databases.get(database) or {})
if table is not None:
table_metadata = (
(databases.get(database) or {}).get("tables") or {}
).get(table) or {}
search_list.insert(0, table_metadata)
search_list.append(self._metadata)
if not fallback:
# No fallback allowed, so just use the first one in the list
search_list = search_list[:1]
if key is not None:
for item in search_list:
if key in item:
return item[key]
return None
else:
# Return the merged list
m = {}
for item in search_list:
m.update(item)
return m | python | def metadata(self, key=None, database=None, table=None, fallback=True):
"""
Looks up metadata, cascading backwards from specified level.
Returns None if metadata value is not found.
"""
assert not (database is None and table is not None), \
"Cannot call metadata() with table= specified but not database="
databases = self._metadata.get("databases") or {}
search_list = []
if database is not None:
search_list.append(databases.get(database) or {})
if table is not None:
table_metadata = (
(databases.get(database) or {}).get("tables") or {}
).get(table) or {}
search_list.insert(0, table_metadata)
search_list.append(self._metadata)
if not fallback:
# No fallback allowed, so just use the first one in the list
search_list = search_list[:1]
if key is not None:
for item in search_list:
if key in item:
return item[key]
return None
else:
# Return the merged list
m = {}
for item in search_list:
m.update(item)
return m | [
"def",
"metadata",
"(",
"self",
",",
"key",
"=",
"None",
",",
"database",
"=",
"None",
",",
"table",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"database",
"is",
"None",
"and",
"table",
"is",
"not",
"None",
")",
",",... | Looks up metadata, cascading backwards from specified level.
Returns None if metadata value is not found. | [
"Looks",
"up",
"metadata",
"cascading",
"backwards",
"from",
"specified",
"level",
".",
"Returns",
"None",
"if",
"metadata",
"value",
"is",
"not",
"found",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L239-L269 | train | 219,382 |
simonw/datasette | datasette/app.py | Datasette.inspect | def inspect(self):
" Inspect the database and return a dictionary of table metadata "
if self._inspect:
return self._inspect
self._inspect = {}
for filename in self.files:
if filename is MEMORY:
self._inspect[":memory:"] = {
"hash": "000",
"file": ":memory:",
"size": 0,
"views": {},
"tables": {},
}
else:
path = Path(filename)
name = path.stem
if name in self._inspect:
raise Exception("Multiple files with same stem %s" % name)
try:
with sqlite3.connect(
"file:{}?mode=ro".format(path), uri=True
) as conn:
self.prepare_connection(conn)
self._inspect[name] = {
"hash": inspect_hash(path),
"file": str(path),
"size": path.stat().st_size,
"views": inspect_views(conn),
"tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {}))
}
except sqlite3.OperationalError as e:
if (e.args[0] == 'no such module: VirtualSpatialIndex'):
raise click.UsageError(
"It looks like you're trying to load a SpatiaLite"
" database without first loading the SpatiaLite module."
"\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html"
)
else:
raise
return self._inspect | python | def inspect(self):
" Inspect the database and return a dictionary of table metadata "
if self._inspect:
return self._inspect
self._inspect = {}
for filename in self.files:
if filename is MEMORY:
self._inspect[":memory:"] = {
"hash": "000",
"file": ":memory:",
"size": 0,
"views": {},
"tables": {},
}
else:
path = Path(filename)
name = path.stem
if name in self._inspect:
raise Exception("Multiple files with same stem %s" % name)
try:
with sqlite3.connect(
"file:{}?mode=ro".format(path), uri=True
) as conn:
self.prepare_connection(conn)
self._inspect[name] = {
"hash": inspect_hash(path),
"file": str(path),
"size": path.stat().st_size,
"views": inspect_views(conn),
"tables": inspect_tables(conn, (self.metadata("databases") or {}).get(name, {}))
}
except sqlite3.OperationalError as e:
if (e.args[0] == 'no such module: VirtualSpatialIndex'):
raise click.UsageError(
"It looks like you're trying to load a SpatiaLite"
" database without first loading the SpatiaLite module."
"\n\nRead more: https://datasette.readthedocs.io/en/latest/spatialite.html"
)
else:
raise
return self._inspect | [
"def",
"inspect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_inspect",
":",
"return",
"self",
".",
"_inspect",
"self",
".",
"_inspect",
"=",
"{",
"}",
"for",
"filename",
"in",
"self",
".",
"files",
":",
"if",
"filename",
"is",
"MEMORY",
":",
"self",... | Inspect the database and return a dictionary of table metadata | [
"Inspect",
"the",
"database",
"and",
"return",
"a",
"dictionary",
"of",
"table",
"metadata"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L414-L455 | train | 219,383 |
simonw/datasette | datasette/app.py | Datasette.table_metadata | def table_metadata(self, database, table):
"Fetch table-specific metadata."
return (self.metadata("databases") or {}).get(database, {}).get(
"tables", {}
).get(
table, {}
) | python | def table_metadata(self, database, table):
"Fetch table-specific metadata."
return (self.metadata("databases") or {}).get(database, {}).get(
"tables", {}
).get(
table, {}
) | [
"def",
"table_metadata",
"(",
"self",
",",
"database",
",",
"table",
")",
":",
"return",
"(",
"self",
".",
"metadata",
"(",
"\"databases\"",
")",
"or",
"{",
"}",
")",
".",
"get",
"(",
"database",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"tables\"",
"... | Fetch table-specific metadata. | [
"Fetch",
"table",
"-",
"specific",
"metadata",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L521-L527 | train | 219,384 |
simonw/datasette | datasette/app.py | Datasette.execute | async def execute(
self,
db_name,
sql,
params=None,
truncate=False,
custom_time_limit=None,
page_size=None,
):
"""Executes sql against db_name in a thread"""
page_size = page_size or self.page_size
def sql_operation_in_thread(conn):
time_limit_ms = self.sql_time_limit_ms
if custom_time_limit and custom_time_limit < time_limit_ms:
time_limit_ms = custom_time_limit
with sqlite_timelimit(conn, time_limit_ms):
try:
cursor = conn.cursor()
cursor.execute(sql, params or {})
max_returned_rows = self.max_returned_rows
if max_returned_rows == page_size:
max_returned_rows += 1
if max_returned_rows and truncate:
rows = cursor.fetchmany(max_returned_rows + 1)
truncated = len(rows) > max_returned_rows
rows = rows[:max_returned_rows]
else:
rows = cursor.fetchall()
truncated = False
except sqlite3.OperationalError as e:
if e.args == ('interrupted',):
raise InterruptedError(e)
print(
"ERROR: conn={}, sql = {}, params = {}: {}".format(
conn, repr(sql), params, e
)
)
raise
if truncate:
return Results(rows, truncated, cursor.description)
else:
return Results(rows, False, cursor.description)
with trace("sql", (db_name, sql.strip(), params)):
results = await self.execute_against_connection_in_thread(
db_name, sql_operation_in_thread
)
return results | python | async def execute(
self,
db_name,
sql,
params=None,
truncate=False,
custom_time_limit=None,
page_size=None,
):
"""Executes sql against db_name in a thread"""
page_size = page_size or self.page_size
def sql_operation_in_thread(conn):
time_limit_ms = self.sql_time_limit_ms
if custom_time_limit and custom_time_limit < time_limit_ms:
time_limit_ms = custom_time_limit
with sqlite_timelimit(conn, time_limit_ms):
try:
cursor = conn.cursor()
cursor.execute(sql, params or {})
max_returned_rows = self.max_returned_rows
if max_returned_rows == page_size:
max_returned_rows += 1
if max_returned_rows and truncate:
rows = cursor.fetchmany(max_returned_rows + 1)
truncated = len(rows) > max_returned_rows
rows = rows[:max_returned_rows]
else:
rows = cursor.fetchall()
truncated = False
except sqlite3.OperationalError as e:
if e.args == ('interrupted',):
raise InterruptedError(e)
print(
"ERROR: conn={}, sql = {}, params = {}: {}".format(
conn, repr(sql), params, e
)
)
raise
if truncate:
return Results(rows, truncated, cursor.description)
else:
return Results(rows, False, cursor.description)
with trace("sql", (db_name, sql.strip(), params)):
results = await self.execute_against_connection_in_thread(
db_name, sql_operation_in_thread
)
return results | [
"async",
"def",
"execute",
"(",
"self",
",",
"db_name",
",",
"sql",
",",
"params",
"=",
"None",
",",
"truncate",
"=",
"False",
",",
"custom_time_limit",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
")",
":",
"page_size",
"=",
"page_size",
"or",
"se... | Executes sql against db_name in a thread | [
"Executes",
"sql",
"against",
"db_name",
"in",
"a",
"thread"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L580-L631 | train | 219,385 |
simonw/datasette | datasette/inspect.py | inspect_hash | def inspect_hash(path):
" Calculate the hash of a database, efficiently. "
m = hashlib.sha256()
with path.open("rb") as fp:
while True:
data = fp.read(HASH_BLOCK_SIZE)
if not data:
break
m.update(data)
return m.hexdigest() | python | def inspect_hash(path):
" Calculate the hash of a database, efficiently. "
m = hashlib.sha256()
with path.open("rb") as fp:
while True:
data = fp.read(HASH_BLOCK_SIZE)
if not data:
break
m.update(data)
return m.hexdigest() | [
"def",
"inspect_hash",
"(",
"path",
")",
":",
"m",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"path",
".",
"open",
"(",
"\"rb\"",
")",
"as",
"fp",
":",
"while",
"True",
":",
"data",
"=",
"fp",
".",
"read",
"(",
"HASH_BLOCK_SIZE",
")",
"if",
... | Calculate the hash of a database, efficiently. | [
"Calculate",
"the",
"hash",
"of",
"a",
"database",
"efficiently",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L17-L27 | train | 219,386 |
simonw/datasette | datasette/inspect.py | inspect_tables | def inspect_tables(conn, database_metadata):
" List tables and their row counts, excluding uninteresting tables. "
tables = {}
table_names = [
r["name"]
for r in conn.execute(
'select * from sqlite_master where type="table"'
)
]
for table in table_names:
table_metadata = database_metadata.get("tables", {}).get(
table, {}
)
try:
count = conn.execute(
"select count(*) from {}".format(escape_sqlite(table))
).fetchone()[0]
except sqlite3.OperationalError:
# This can happen when running against a FTS virtual table
# e.g. "select count(*) from some_fts;"
count = 0
column_names = table_columns(conn, table)
tables[table] = {
"name": table,
"columns": column_names,
"primary_keys": detect_primary_keys(conn, table),
"count": count,
"hidden": table_metadata.get("hidden") or False,
"fts_table": detect_fts(conn, table),
}
foreign_keys = get_all_foreign_keys(conn)
for table, info in foreign_keys.items():
tables[table]["foreign_keys"] = info
# Mark tables 'hidden' if they relate to FTS virtual tables
hidden_tables = [
r["name"]
for r in conn.execute(
"""
select name from sqlite_master
where rootpage = 0
and sql like '%VIRTUAL TABLE%USING FTS%'
"""
)
]
if detect_spatialite(conn):
# Also hide Spatialite internal tables
hidden_tables += [
"ElementaryGeometries",
"SpatialIndex",
"geometry_columns",
"spatial_ref_sys",
"spatialite_history",
"sql_statements_log",
"sqlite_sequence",
"views_geometry_columns",
"virts_geometry_columns",
] + [
r["name"]
for r in conn.execute(
"""
select name from sqlite_master
where name like "idx_%"
and type = "table"
"""
)
]
for t in tables.keys():
for hidden_table in hidden_tables:
if t == hidden_table or t.startswith(hidden_table):
tables[t]["hidden"] = True
continue
return tables | python | def inspect_tables(conn, database_metadata):
" List tables and their row counts, excluding uninteresting tables. "
tables = {}
table_names = [
r["name"]
for r in conn.execute(
'select * from sqlite_master where type="table"'
)
]
for table in table_names:
table_metadata = database_metadata.get("tables", {}).get(
table, {}
)
try:
count = conn.execute(
"select count(*) from {}".format(escape_sqlite(table))
).fetchone()[0]
except sqlite3.OperationalError:
# This can happen when running against a FTS virtual table
# e.g. "select count(*) from some_fts;"
count = 0
column_names = table_columns(conn, table)
tables[table] = {
"name": table,
"columns": column_names,
"primary_keys": detect_primary_keys(conn, table),
"count": count,
"hidden": table_metadata.get("hidden") or False,
"fts_table": detect_fts(conn, table),
}
foreign_keys = get_all_foreign_keys(conn)
for table, info in foreign_keys.items():
tables[table]["foreign_keys"] = info
# Mark tables 'hidden' if they relate to FTS virtual tables
hidden_tables = [
r["name"]
for r in conn.execute(
"""
select name from sqlite_master
where rootpage = 0
and sql like '%VIRTUAL TABLE%USING FTS%'
"""
)
]
if detect_spatialite(conn):
# Also hide Spatialite internal tables
hidden_tables += [
"ElementaryGeometries",
"SpatialIndex",
"geometry_columns",
"spatial_ref_sys",
"spatialite_history",
"sql_statements_log",
"sqlite_sequence",
"views_geometry_columns",
"virts_geometry_columns",
] + [
r["name"]
for r in conn.execute(
"""
select name from sqlite_master
where name like "idx_%"
and type = "table"
"""
)
]
for t in tables.keys():
for hidden_table in hidden_tables:
if t == hidden_table or t.startswith(hidden_table):
tables[t]["hidden"] = True
continue
return tables | [
"def",
"inspect_tables",
"(",
"conn",
",",
"database_metadata",
")",
":",
"tables",
"=",
"{",
"}",
"table_names",
"=",
"[",
"r",
"[",
"\"name\"",
"]",
"for",
"r",
"in",
"conn",
".",
"execute",
"(",
"'select * from sqlite_master where type=\"table\"'",
")",
"]"... | List tables and their row counts, excluding uninteresting tables. | [
"List",
"tables",
"and",
"their",
"row",
"counts",
"excluding",
"uninteresting",
"tables",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L35-L115 | train | 219,387 |
simonw/datasette | datasette/filters.py | Filters.convert_unit | def convert_unit(self, column, value):
"If the user has provided a unit in the query, convert it into the column unit, if present."
if column not in self.units:
return value
# Try to interpret the value as a unit
value = self.ureg(value)
if isinstance(value, numbers.Number):
# It's just a bare number, assume it's the column unit
return value
column_unit = self.ureg(self.units[column])
return value.to(column_unit).magnitude | python | def convert_unit(self, column, value):
"If the user has provided a unit in the query, convert it into the column unit, if present."
if column not in self.units:
return value
# Try to interpret the value as a unit
value = self.ureg(value)
if isinstance(value, numbers.Number):
# It's just a bare number, assume it's the column unit
return value
column_unit = self.ureg(self.units[column])
return value.to(column_unit).magnitude | [
"def",
"convert_unit",
"(",
"self",
",",
"column",
",",
"value",
")",
":",
"if",
"column",
"not",
"in",
"self",
".",
"units",
":",
"return",
"value",
"# Try to interpret the value as a unit",
"value",
"=",
"self",
".",
"ureg",
"(",
"value",
")",
"if",
"isi... | If the user has provided a unit in the query, convert it into the column unit, if present. | [
"If",
"the",
"user",
"has",
"provided",
"a",
"unit",
"in",
"the",
"query",
"convert",
"it",
"into",
"the",
"column",
"unit",
"if",
"present",
"."
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/filters.py#L156-L168 | train | 219,388 |
simonw/datasette | datasette/cli.py | skeleton | def skeleton(files, metadata, sqlite_extensions):
"Generate a skeleton metadata.json file for specified SQLite databases"
if os.path.exists(metadata):
click.secho(
"File {} already exists, will not over-write".format(metadata),
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
app = Datasette(files, sqlite_extensions=sqlite_extensions)
databases = {}
for database_name, info in app.inspect().items():
databases[database_name] = {
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"queries": {},
"tables": {
table_name: {
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"units": {},
}
for table_name in (info.get("tables") or {})
},
}
open(metadata, "w").write(
json.dumps(
{
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"databases": databases,
},
indent=4,
)
)
click.echo("Wrote skeleton to {}".format(metadata)) | python | def skeleton(files, metadata, sqlite_extensions):
"Generate a skeleton metadata.json file for specified SQLite databases"
if os.path.exists(metadata):
click.secho(
"File {} already exists, will not over-write".format(metadata),
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
app = Datasette(files, sqlite_extensions=sqlite_extensions)
databases = {}
for database_name, info in app.inspect().items():
databases[database_name] = {
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"queries": {},
"tables": {
table_name: {
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"units": {},
}
for table_name in (info.get("tables") or {})
},
}
open(metadata, "w").write(
json.dumps(
{
"title": None,
"description": None,
"description_html": None,
"license": None,
"license_url": None,
"source": None,
"source_url": None,
"databases": databases,
},
indent=4,
)
)
click.echo("Wrote skeleton to {}".format(metadata)) | [
"def",
"skeleton",
"(",
"files",
",",
"metadata",
",",
"sqlite_extensions",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"metadata",
")",
":",
"click",
".",
"secho",
"(",
"\"File {} already exists, will not over-write\"",
".",
"format",
"(",
"metadat... | Generate a skeleton metadata.json file for specified SQLite databases | [
"Generate",
"a",
"skeleton",
"metadata",
".",
"json",
"file",
"for",
"specified",
"SQLite",
"databases"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L107-L159 | train | 219,389 |
simonw/datasette | datasette/cli.py | plugins | def plugins(all, plugins_dir):
"List currently available plugins"
app = Datasette([], plugins_dir=plugins_dir)
click.echo(json.dumps(app.plugins(all), indent=4)) | python | def plugins(all, plugins_dir):
"List currently available plugins"
app = Datasette([], plugins_dir=plugins_dir)
click.echo(json.dumps(app.plugins(all), indent=4)) | [
"def",
"plugins",
"(",
"all",
",",
"plugins_dir",
")",
":",
"app",
"=",
"Datasette",
"(",
"[",
"]",
",",
"plugins_dir",
"=",
"plugins_dir",
")",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"app",
".",
"plugins",
"(",
"all",
")",
",",
"ind... | List currently available plugins | [
"List",
"currently",
"available",
"plugins"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L169-L172 | train | 219,390 |
simonw/datasette | datasette/cli.py | package | def package(
files,
tag,
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
**extra_metadata
):
"Package specified SQLite files into a new datasette Docker container"
if not shutil.which("docker"):
click.secho(
' The package command requires "docker" to be installed and configured ',
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
with temporary_docker_directory(
files,
"datasette",
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
extra_metadata,
):
args = ["docker", "build"]
if tag:
args.append("-t")
args.append(tag)
args.append(".")
call(args) | python | def package(
files,
tag,
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
**extra_metadata
):
"Package specified SQLite files into a new datasette Docker container"
if not shutil.which("docker"):
click.secho(
' The package command requires "docker" to be installed and configured ',
bg="red",
fg="white",
bold=True,
err=True,
)
sys.exit(1)
with temporary_docker_directory(
files,
"datasette",
metadata,
extra_options,
branch,
template_dir,
plugins_dir,
static,
install,
spatialite,
version_note,
extra_metadata,
):
args = ["docker", "build"]
if tag:
args.append("-t")
args.append(tag)
args.append(".")
call(args) | [
"def",
"package",
"(",
"files",
",",
"tag",
",",
"metadata",
",",
"extra_options",
",",
"branch",
",",
"template_dir",
",",
"plugins_dir",
",",
"static",
",",
"install",
",",
"spatialite",
",",
"version_note",
",",
"*",
"*",
"extra_metadata",
")",
":",
"if... | Package specified SQLite files into a new datasette Docker container | [
"Package",
"specified",
"SQLite",
"files",
"into",
"a",
"new",
"datasette",
"Docker",
"container"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L222-L265 | train | 219,391 |
simonw/datasette | datasette/cli.py | serve | def serve(
files,
immutable,
host,
port,
debug,
reload,
cors,
sqlite_extensions,
inspect_file,
metadata,
template_dir,
plugins_dir,
static,
memory,
config,
version_note,
help_config,
):
"""Serve up specified SQLite database files with a web UI"""
if help_config:
formatter = formatting.HelpFormatter()
with formatter.section("Config options"):
formatter.write_dl([
(option.name, '{} (default={})'.format(
option.help, option.default
))
for option in CONFIG_OPTIONS
])
click.echo(formatter.getvalue())
sys.exit(0)
if reload:
import hupper
reloader = hupper.start_reloader("datasette.cli.serve")
reloader.watch_files(files)
if metadata:
reloader.watch_files([metadata.name])
inspect_data = None
if inspect_file:
inspect_data = json.load(open(inspect_file))
metadata_data = None
if metadata:
metadata_data = json.loads(metadata.read())
click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port))
ds = Datasette(
files,
immutables=immutable,
cache_headers=not debug and not reload,
cors=cors,
inspect_data=inspect_data,
metadata=metadata_data,
sqlite_extensions=sqlite_extensions,
template_dir=template_dir,
plugins_dir=plugins_dir,
static_mounts=static,
config=dict(config),
memory=memory,
version_note=version_note,
)
# Force initial hashing/table counting
ds.inspect()
ds.app().run(host=host, port=port, debug=debug) | python | def serve(
files,
immutable,
host,
port,
debug,
reload,
cors,
sqlite_extensions,
inspect_file,
metadata,
template_dir,
plugins_dir,
static,
memory,
config,
version_note,
help_config,
):
"""Serve up specified SQLite database files with a web UI"""
if help_config:
formatter = formatting.HelpFormatter()
with formatter.section("Config options"):
formatter.write_dl([
(option.name, '{} (default={})'.format(
option.help, option.default
))
for option in CONFIG_OPTIONS
])
click.echo(formatter.getvalue())
sys.exit(0)
if reload:
import hupper
reloader = hupper.start_reloader("datasette.cli.serve")
reloader.watch_files(files)
if metadata:
reloader.watch_files([metadata.name])
inspect_data = None
if inspect_file:
inspect_data = json.load(open(inspect_file))
metadata_data = None
if metadata:
metadata_data = json.loads(metadata.read())
click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port))
ds = Datasette(
files,
immutables=immutable,
cache_headers=not debug and not reload,
cors=cors,
inspect_data=inspect_data,
metadata=metadata_data,
sqlite_extensions=sqlite_extensions,
template_dir=template_dir,
plugins_dir=plugins_dir,
static_mounts=static,
config=dict(config),
memory=memory,
version_note=version_note,
)
# Force initial hashing/table counting
ds.inspect()
ds.app().run(host=host, port=port, debug=debug) | [
"def",
"serve",
"(",
"files",
",",
"immutable",
",",
"host",
",",
"port",
",",
"debug",
",",
"reload",
",",
"cors",
",",
"sqlite_extensions",
",",
"inspect_file",
",",
"metadata",
",",
"template_dir",
",",
"plugins_dir",
",",
"static",
",",
"memory",
",",
... | Serve up specified SQLite database files with a web UI | [
"Serve",
"up",
"specified",
"SQLite",
"database",
"files",
"with",
"a",
"web",
"UI"
] | 11b352b4d52fd02a422776edebb14f12e4994d3b | https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L340-L405 | train | 219,392 |
ResidentMario/missingno | missingno/missingno.py | bar | def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False,
filter=None, n=0, p=0, sort=None):
"""
A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logorithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default).
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
nullity_counts = len(df) - df.isnull().sum()
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
(nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color)
ax1 = plt.gca()
axes = [ax1]
# Start appending elements, starting with a modified bottom x axis.
if labels or (labels is None and len(df.columns) <= 50):
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize)
# Create the numerical ticks.
ax2 = ax1.twinx()
axes.append(ax2)
if not log:
ax1.set_ylim([0, 1])
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually
# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale
# is used, we have to make it match the `ax1` layout ourselves.
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
ax1.set_xticks([])
# Create the third axis, which displays columnar totals above the rest of the plot.
ax3 = ax1.twiny()
axes.append(ax3)
ax3.set_xticks(ax1.get_xticks())
ax3.set_xlim(ax1.get_xlim())
ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left')
ax3.grid(False)
for ax in axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
if inline:
plt.show()
else:
return ax1 | python | def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False,
filter=None, n=0, p=0, sort=None):
"""
A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logorithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default).
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
nullity_counts = len(df) - df.isnull().sum()
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
(nullity_counts / len(df)).plot(kind='bar', figsize=figsize, fontsize=fontsize, log=log, color=color)
ax1 = plt.gca()
axes = [ax1]
# Start appending elements, starting with a modified bottom x axis.
if labels or (labels is None and len(df.columns) <= 50):
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=fontsize)
# Create the numerical ticks.
ax2 = ax1.twinx()
axes.append(ax2)
if not log:
ax1.set_ylim([0, 1])
ax2.set_yticks(ax1.get_yticks())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
# For some reason when a logarithmic plot is specified `ax1` always contains two more ticks than actually
# appears in the plot. The fix is to ignore the first and last entries. Also note that when a log scale
# is used, we have to make it match the `ax1` layout ourselves.
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim())
ax2.set_yticklabels([int(n*len(df)) for n in ax1.get_yticks()], fontsize=fontsize)
else:
ax1.set_xticks([])
# Create the third axis, which displays columnar totals above the rest of the plot.
ax3 = ax1.twiny()
axes.append(ax3)
ax3.set_xticks(ax1.get_xticks())
ax3.set_xlim(ax1.get_xlim())
ax3.set_xticklabels(nullity_counts.values, fontsize=fontsize, rotation=45, ha='left')
ax3.grid(False)
for ax in axes:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
if inline:
plt.show()
else:
return ax1 | [
"def",
"bar",
"(",
"df",
",",
"figsize",
"=",
"(",
"24",
",",
"10",
")",
",",
"fontsize",
"=",
"16",
",",
"labels",
"=",
"None",
",",
"log",
"=",
"False",
",",
"color",
"=",
"'dimgray'",
",",
"inline",
"=",
"False",
",",
"filter",
"=",
"None",
... | A bar chart visualization of the nullity of the given DataFrame.
:param df: The input DataFrame.
:param log: Whether or not to display a logorithmic plot. Defaults to False (linear).
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None (default).
:param figsize: The size of the figure to display.
:param fontsize: The figure's font size. This default to 16.
:param labels: Whether or not to display the column names. Would need to be turned off on particularly large
displays. Defaults to True.
:param color: The color of the filled columns. Default to the RGB multiple `(0.25, 0.25, 0.25)`.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. | [
"A",
"bar",
"chart",
"visualization",
"of",
"the",
"nullity",
"of",
"the",
"given",
"DataFrame",
"."
] | 1d67f91fbab0695a919c6bb72c796db57024e0ca | https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L195-L263 | train | 219,393 |
ResidentMario/missingno | missingno/missingno.py | heatmap | def heatmap(df, inline=False,
filter=None, n=0, p=0, sort=None,
figsize=(20, 12), fontsize=16, labels=True,
cmap='RdBu', vmin=-1, vmax=1, cbar=True
):
"""
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See
`nullity_sort()` for more information.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
# Apply filters and sorts, set up the figure.
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
# Remove completely filled or completely empty variables.
df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]]
# Create and mask the correlation matrix. Construct the base heatmap.
corr_mat = df.isnull().corr()
mask = np.zeros_like(corr_mat)
mask[np.triu_indices_from(mask)] = True
if labels:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
annot=True, annot_kws={'size': fontsize - 2},
vmin=vmin, vmax=vmax)
else:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
vmin=vmin, vmax=vmax)
# Apply visual corrections and modifications.
ax0.xaxis.tick_bottom()
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize)
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.patch.set_visible(False)
for text in ax0.texts:
t = float(text.get_text())
if 0.95 <= t < 1:
text.set_text('<1')
elif -1 < t <= -0.95:
text.set_text('>-1')
elif t == 1:
text.set_text('1')
elif t == -1:
text.set_text('-1')
elif -0.05 < t < 0.05:
text.set_text('')
else:
text.set_text(round(t, 1))
if inline:
plt.show()
else:
return ax0 | python | def heatmap(df, inline=False,
filter=None, n=0, p=0, sort=None,
figsize=(20, 12), fontsize=16, labels=True,
cmap='RdBu', vmin=-1, vmax=1, cbar=True
):
"""
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See
`nullity_sort()` for more information.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
# Apply filters and sorts, set up the figure.
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
# Remove completely filled or completely empty variables.
df = df.iloc[:,[i for i, n in enumerate(np.var(df.isnull(), axis='rows')) if n > 0]]
# Create and mask the correlation matrix. Construct the base heatmap.
corr_mat = df.isnull().corr()
mask = np.zeros_like(corr_mat)
mask[np.triu_indices_from(mask)] = True
if labels:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
annot=True, annot_kws={'size': fontsize - 2},
vmin=vmin, vmax=vmax)
else:
sns.heatmap(corr_mat, mask=mask, cmap=cmap, ax=ax0, cbar=cbar,
vmin=vmin, vmax=vmax)
# Apply visual corrections and modifications.
ax0.xaxis.tick_bottom()
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right', fontsize=fontsize)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), fontsize=fontsize, rotation=0)
ax0.set_yticklabels(ax0.yaxis.get_majorticklabels(), rotation=0, fontsize=fontsize)
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.patch.set_visible(False)
for text in ax0.texts:
t = float(text.get_text())
if 0.95 <= t < 1:
text.set_text('<1')
elif -1 < t <= -0.95:
text.set_text('>-1')
elif t == 1:
text.set_text('1')
elif t == -1:
text.set_text('-1')
elif -0.05 < t < 0.05:
text.set_text('')
else:
text.set_text(round(t, 1))
if inline:
plt.show()
else:
return ax0 | [
"def",
"heatmap",
"(",
"df",
",",
"inline",
"=",
"False",
",",
"filter",
"=",
"None",
",",
"n",
"=",
"0",
",",
"p",
"=",
"0",
",",
"sort",
"=",
"None",
",",
"figsize",
"=",
"(",
"20",
",",
"12",
")",
",",
"fontsize",
"=",
"16",
",",
"labels",... | Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame.
Note that this visualization has no special support for large datasets. For those, try the dendrogram instead.
:param df: The DataFrame whose completeness is being heatmapped.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). See
`nullity_filter()` for more information.
:param n: The cap on the number of columns to include in the filtered DataFrame. See `nullity_filter()` for
more information.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame. See `nullity_filter()` for
more information.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. See
`nullity_sort()` for more information.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to (20, 12).
:param fontsize: The figure's font size.
:param labels: Whether or not to label each matrix entry with its correlation (default is True).
:param cmap: What `matplotlib` colormap to use. Defaults to `RdBu`.
:param vmin: The normalized colormap threshold. Defaults to -1, e.g. the bottom of the color scale.
:param vmax: The normalized colormap threshold. Defaults to 1, e.g. the bottom of the color scale.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. | [
"Presents",
"a",
"seaborn",
"heatmap",
"visualization",
"of",
"nullity",
"correlation",
"in",
"the",
"given",
"DataFrame",
".",
"Note",
"that",
"this",
"visualization",
"has",
"no",
"special",
"support",
"for",
"large",
"datasets",
".",
"For",
"those",
"try",
... | 1d67f91fbab0695a919c6bb72c796db57024e0ca | https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L266-L346 | train | 219,394 |
ResidentMario/missingno | missingno/missingno.py | dendrogram | def dendrogram(df, method='average',
filter=None, n=0, p=0, sort=None,
orientation=None, figsize=None,
fontsize=16, inline=False
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
if not figsize:
if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom':
figsize = (25, 10)
else:
figsize = (25, (25 + len(df.columns) - 50)*0.5)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
# Link the hierarchical output matrix, figure out orientation, construct base dendrogram.
x = np.transpose(df.isnull().astype(int).values)
z = hierarchy.linkage(x, method)
if not orientation:
if len(df.columns) > 50:
orientation = 'left'
else:
orientation = 'bottom'
hierarchy.dendrogram(z,
orientation=orientation,
labels=df.columns.tolist(),
distance_sort='descending',
link_color_func=lambda c: 'black',
leaf_font_size=fontsize,
ax=ax0
)
# Remove extraneous default visual elements.
ax0.set_aspect('auto')
ax0.grid(b=False)
if orientation == 'bottom':
ax0.xaxis.tick_top()
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax0.spines['left'].set_visible(False)
ax0.patch.set_visible(False)
# Set up the categorical axis labels and draw.
if orientation == 'bottom':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left')
elif orientation == 'top':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right')
if orientation == 'bottom' or orientation == 'top':
ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20))
else:
ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20))
if inline:
plt.show()
else:
return ax0 | python | def dendrogram(df, method='average',
filter=None, n=0, p=0, sort=None,
orientation=None, figsize=None,
fontsize=16, inline=False
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing.
"""
if not figsize:
if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom':
figsize = (25, 10)
else:
figsize = (25, (25 + len(df.columns) - 50)*0.5)
plt.figure(figsize=figsize)
gs = gridspec.GridSpec(1, 1)
ax0 = plt.subplot(gs[0])
df = nullity_filter(df, filter=filter, n=n, p=p)
df = nullity_sort(df, sort=sort)
# Link the hierarchical output matrix, figure out orientation, construct base dendrogram.
x = np.transpose(df.isnull().astype(int).values)
z = hierarchy.linkage(x, method)
if not orientation:
if len(df.columns) > 50:
orientation = 'left'
else:
orientation = 'bottom'
hierarchy.dendrogram(z,
orientation=orientation,
labels=df.columns.tolist(),
distance_sort='descending',
link_color_func=lambda c: 'black',
leaf_font_size=fontsize,
ax=ax0
)
# Remove extraneous default visual elements.
ax0.set_aspect('auto')
ax0.grid(b=False)
if orientation == 'bottom':
ax0.xaxis.tick_top()
ax0.xaxis.set_ticks_position('none')
ax0.yaxis.set_ticks_position('none')
ax0.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax0.spines['left'].set_visible(False)
ax0.patch.set_visible(False)
# Set up the categorical axis labels and draw.
if orientation == 'bottom':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left')
elif orientation == 'top':
ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right')
if orientation == 'bottom' or orientation == 'top':
ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20))
else:
ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20))
if inline:
plt.show()
else:
return ax0 | [
"def",
"dendrogram",
"(",
"df",
",",
"method",
"=",
"'average'",
",",
"filter",
"=",
"None",
",",
"n",
"=",
"0",
",",
"p",
"=",
"0",
",",
"sort",
"=",
"None",
",",
"orientation",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"fontsize",
"=",
"16... | Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is
left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables.
:param df: The DataFrame whose completeness is being dendrogrammed.
:param method: The distance measure being used for clustering. This is a parameter that is passed to
`scipy.hierarchy`.
:param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default).
:param n: The cap on the number of columns to include in the filtered DataFrame.
:param p: The cap on the percentage fill of the columns in the filtered DataFrame.
:param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None.
:param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`.
:param fontsize: The figure's font size.
:param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50
columns and left-right if there are more.
:param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will
return its figure.
:return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. | [
"Fits",
"a",
"scipy",
"hierarchical",
"clustering",
"algorithm",
"to",
"the",
"given",
"DataFrame",
"s",
"variables",
"and",
"visualizes",
"the",
"results",
"as",
"a",
"scipy",
"dendrogram",
".",
"The",
"default",
"vertical",
"display",
"will",
"fit",
"up",
"t... | 1d67f91fbab0695a919c6bb72c796db57024e0ca | https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L349-L434 | train | 219,395 |
ResidentMario/missingno | missingno/utils.py | nullity_sort | def nullity_sort(df, sort=None):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
else:
return df | python | def nullity_sort(df, sort=None):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
"""
if sort == 'ascending':
return df.iloc[np.argsort(df.count(axis='columns').values), :]
elif sort == 'descending':
return df.iloc[np.flipud(np.argsort(df.count(axis='columns').values)), :]
else:
return df | [
"def",
"nullity_sort",
"(",
"df",
",",
"sort",
"=",
"None",
")",
":",
"if",
"sort",
"==",
"'ascending'",
":",
"return",
"df",
".",
"iloc",
"[",
"np",
".",
"argsort",
"(",
"df",
".",
"count",
"(",
"axis",
"=",
"'columns'",
")",
".",
"values",
")",
... | Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame. | [
"Sorts",
"a",
"DataFrame",
"according",
"to",
"its",
"nullity",
"in",
"either",
"ascending",
"or",
"descending",
"order",
"."
] | 1d67f91fbab0695a919c6bb72c796db57024e0ca | https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/utils.py#L5-L18 | train | 219,396 |
googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/session_entity_types_client.py | SessionEntityTypesClient.from_service_account_file | def from_service_account_file(cls, filename, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
dialogflow_v2.SessionEntityTypesClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs['credentials'] = credentials
return cls(*args, **kwargs) | python | def from_service_account_file(cls, filename, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
dialogflow_v2.SessionEntityTypesClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs['credentials'] = credentials
return cls(*args, **kwargs) | [
"def",
"from_service_account_file",
"(",
"cls",
",",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"credentials",
"=",
"service_account",
".",
"Credentials",
".",
"from_service_account_file",
"(",
"filename",
")",
"kwargs",
"[",
"'credentials'... | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
dialogflow_v2.SessionEntityTypesClient: The constructed client. | [
"Creates",
"an",
"instance",
"of",
"this",
"client",
"using",
"the",
"provided",
"credentials",
"file",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L75-L91 | train | 219,397 |
googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/session_entity_types_client.py | SessionEntityTypesClient.session_entity_type_path | def session_entity_type_path(cls, project, session, entity_type):
"""Return a fully-qualified session_entity_type string."""
return google.api_core.path_template.expand(
'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}',
project=project,
session=session,
entity_type=entity_type,
) | python | def session_entity_type_path(cls, project, session, entity_type):
"""Return a fully-qualified session_entity_type string."""
return google.api_core.path_template.expand(
'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}',
project=project,
session=session,
entity_type=entity_type,
) | [
"def",
"session_entity_type_path",
"(",
"cls",
",",
"project",
",",
"session",
",",
"entity_type",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}'",
",",
"p... | Return a fully-qualified session_entity_type string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"session_entity_type",
"string",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L105-L112 | train | 219,398 |
googleapis/dialogflow-python-client-v2 | dialogflow_v2/gapic/session_entity_types_client.py | SessionEntityTypesClient.create_session_entity_type | def create_session_entity_type(
self,
parent,
session_entity_type,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
>>>
>>> parent = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``session_entity_type``:
>>> session_entity_type = {}
>>>
>>> response = client.create_session_entity_type(parent, session_entity_type)
Args:
parent (str): Required. The session to create a session entity type for.
Format: ``projects/<Project ID>/agent/sessions/<Session ID>``.
session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'create_session_entity_type' not in self._inner_api_calls:
self._inner_api_calls[
'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_session_entity_type,
default_retry=self._method_configs[
'CreateSessionEntityType'].retry,
default_timeout=self._method_configs[
'CreateSessionEntityType'].timeout,
client_info=self._client_info,
)
request = session_entity_type_pb2.CreateSessionEntityTypeRequest(
parent=parent,
session_entity_type=session_entity_type,
)
return self._inner_api_calls['create_session_entity_type'](
request, retry=retry, timeout=timeout, metadata=metadata) | python | def create_session_entity_type(
self,
parent,
session_entity_type,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
>>>
>>> parent = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``session_entity_type``:
>>> session_entity_type = {}
>>>
>>> response = client.create_session_entity_type(parent, session_entity_type)
Args:
parent (str): Required. The session to create a session entity type for.
Format: ``projects/<Project ID>/agent/sessions/<Session ID>``.
session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'create_session_entity_type' not in self._inner_api_calls:
self._inner_api_calls[
'create_session_entity_type'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_session_entity_type,
default_retry=self._method_configs[
'CreateSessionEntityType'].retry,
default_timeout=self._method_configs[
'CreateSessionEntityType'].timeout,
client_info=self._client_info,
)
request = session_entity_type_pb2.CreateSessionEntityTypeRequest(
parent=parent,
session_entity_type=session_entity_type,
)
return self._inner_api_calls['create_session_entity_type'](
request, retry=retry, timeout=timeout, metadata=metadata) | [
"def",
"create_session_entity_type",
"(",
"self",
",",
"parent",
",",
"session_entity_type",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"... | Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
>>>
>>> parent = client.session_path('[PROJECT]', '[SESSION]')
>>>
>>> # TODO: Initialize ``session_entity_type``:
>>> session_entity_type = {}
>>>
>>> response = client.create_session_entity_type(parent, session_entity_type)
Args:
parent (str): Required. The session to create a session entity type for.
Format: ``projects/<Project ID>/agent/sessions/<Session ID>``.
session_entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.SessionEntityType]): Required. The session entity type to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2.types.SessionEntityType`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.SessionEntityType` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | [
"Creates",
"a",
"session",
"entity",
"type",
"."
] | 8c9c8709222efe427b76c9c8fcc04a0c4a0760b5 | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L351-L415 | train | 219,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.