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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pyroscope/pyrocore | docs/examples/rt-heatmap.py | HeatMap.heatmap | def heatmap(self, df, imagefile):
""" Create the heat map.
"""
import seaborn as sns
import matplotlib.ticker as tkr
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
sns.set()
with sns.axes_style('whitegrid'):
... | python | def heatmap(self, df, imagefile):
""" Create the heat map.
"""
import seaborn as sns
import matplotlib.ticker as tkr
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
sns.set()
with sns.axes_style('whitegrid'):
... | [
"def",
"heatmap",
"(",
"self",
",",
"df",
",",
"imagefile",
")",
":",
"import",
"seaborn",
"as",
"sns",
"import",
"matplotlib",
".",
"ticker",
"as",
"tkr",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"matplotlib",
".",
"colors",
"import",
... | Create the heat map. | [
"Create",
"the",
"heat",
"map",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/docs/examples/rt-heatmap.py#L55-L81 | train |
pyroscope/pyrocore | src/pyrocore/ui/categories.py | CategoryManager.mainloop | def mainloop(self):
""" Manage category views.
"""
# Get client state
proxy = config.engine.open()
views = [x for x in sorted(proxy.view.list()) if x.startswith(self.PREFIX)]
current_view = real_current_view = proxy.ui.current_view()
if current_view not in views:... | python | def mainloop(self):
""" Manage category views.
"""
# Get client state
proxy = config.engine.open()
views = [x for x in sorted(proxy.view.list()) if x.startswith(self.PREFIX)]
current_view = real_current_view = proxy.ui.current_view()
if current_view not in views:... | [
"def",
"mainloop",
"(",
"self",
")",
":",
"# Get client state",
"proxy",
"=",
"config",
".",
"engine",
".",
"open",
"(",
")",
"views",
"=",
"[",
"x",
"for",
"x",
"in",
"sorted",
"(",
"proxy",
".",
"view",
".",
"list",
"(",
")",
")",
"if",
"x",
".... | Manage category views. | [
"Manage",
"category",
"views",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/ui/categories.py#L53-L91 | train |
pyroscope/pyrocore | src/pyrocore/data/config/config.py | _custom_fields | def _custom_fields():
""" Yield custom field definitions.
"""
# Import some commonly needed modules
import os
from pyrocore.torrent import engine, matching
from pyrocore.util import fmt
# PUT CUSTOM FIELD CODE HERE
# Disk space check (as an example)
# see https://pyrocore.readthedo... | python | def _custom_fields():
""" Yield custom field definitions.
"""
# Import some commonly needed modules
import os
from pyrocore.torrent import engine, matching
from pyrocore.util import fmt
# PUT CUSTOM FIELD CODE HERE
# Disk space check (as an example)
# see https://pyrocore.readthedo... | [
"def",
"_custom_fields",
"(",
")",
":",
"# Import some commonly needed modules",
"import",
"os",
"from",
"pyrocore",
".",
"torrent",
"import",
"engine",
",",
"matching",
"from",
"pyrocore",
".",
"util",
"import",
"fmt",
"# PUT CUSTOM FIELD CODE HERE",
"# Disk space chec... | Yield custom field definitions. | [
"Yield",
"custom",
"field",
"definitions",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/data/config/config.py#L7-L35 | train |
pyroscope/pyrocore | src/pyrocore/util/stats.py | engine_data | def engine_data(engine):
""" Get important performance data and metadata from rTorrent.
"""
views = ("default", "main", "started", "stopped", "complete",
"incomplete", "seeding", "leeching", "active", "messages")
methods = [
"throttle.global_up.rate", "throttle.global_up.max_rate",
... | python | def engine_data(engine):
""" Get important performance data and metadata from rTorrent.
"""
views = ("default", "main", "started", "stopped", "complete",
"incomplete", "seeding", "leeching", "active", "messages")
methods = [
"throttle.global_up.rate", "throttle.global_up.max_rate",
... | [
"def",
"engine_data",
"(",
"engine",
")",
":",
"views",
"=",
"(",
"\"default\"",
",",
"\"main\"",
",",
"\"started\"",
",",
"\"stopped\"",
",",
"\"complete\"",
",",
"\"incomplete\"",
",",
"\"seeding\"",
",",
"\"leeching\"",
",",
"\"active\"",
",",
"\"messages\"",... | Get important performance data and metadata from rTorrent. | [
"Get",
"important",
"performance",
"data",
"and",
"metadata",
"from",
"rTorrent",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/stats.py#L25-L54 | train |
pyroscope/pyrocore | src/pyrocore/util/osmagic.py | _write_pidfile | def _write_pidfile(pidfile):
""" Write file with current process ID.
"""
pid = str(os.getpid())
handle = open(pidfile, 'w')
try:
handle.write("%s\n" % pid)
finally:
handle.close() | python | def _write_pidfile(pidfile):
""" Write file with current process ID.
"""
pid = str(os.getpid())
handle = open(pidfile, 'w')
try:
handle.write("%s\n" % pid)
finally:
handle.close() | [
"def",
"_write_pidfile",
"(",
"pidfile",
")",
":",
"pid",
"=",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"handle",
"=",
"open",
"(",
"pidfile",
",",
"'w'",
")",
"try",
":",
"handle",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"pid",
")",
"finally",... | Write file with current process ID. | [
"Write",
"file",
"with",
"current",
"process",
"ID",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/osmagic.py#L30-L38 | train |
pyroscope/pyrocore | src/pyrocore/util/osmagic.py | guard | def guard(pidfile, guardfile=None):
""" Raise an EnvironmentError when the "guardfile" doesn't exist, or
the process with the ID found in "pidfile" is still active.
"""
# Check guard
if guardfile and not os.path.exists(guardfile):
raise EnvironmentError("Guard file '%s' not found, won't ... | python | def guard(pidfile, guardfile=None):
""" Raise an EnvironmentError when the "guardfile" doesn't exist, or
the process with the ID found in "pidfile" is still active.
"""
# Check guard
if guardfile and not os.path.exists(guardfile):
raise EnvironmentError("Guard file '%s' not found, won't ... | [
"def",
"guard",
"(",
"pidfile",
",",
"guardfile",
"=",
"None",
")",
":",
"# Check guard",
"if",
"guardfile",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"guardfile",
")",
":",
"raise",
"EnvironmentError",
"(",
"\"Guard file '%s' not found, won't start!\... | Raise an EnvironmentError when the "guardfile" doesn't exist, or
the process with the ID found in "pidfile" is still active. | [
"Raise",
"an",
"EnvironmentError",
"when",
"the",
"guardfile",
"doesn",
"t",
"exist",
"or",
"the",
"process",
"with",
"the",
"ID",
"found",
"in",
"pidfile",
"is",
"still",
"active",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/osmagic.py#L70-L86 | train |
pyroscope/pyrocore | src/pyrocore/util/osmagic.py | daemonize | def daemonize(pidfile=None, logfile=None, sync=True):
""" Fork the process into the background.
@param pidfile: Optional PID file path.
@param sync: Wait for parent process to disappear?
@param logfile: Optional name of stdin/stderr log file or stream.
"""
log = logging.getLogger("d... | python | def daemonize(pidfile=None, logfile=None, sync=True):
""" Fork the process into the background.
@param pidfile: Optional PID file path.
@param sync: Wait for parent process to disappear?
@param logfile: Optional name of stdin/stderr log file or stream.
"""
log = logging.getLogger("d... | [
"def",
"daemonize",
"(",
"pidfile",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"sync",
"=",
"True",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"daemonize\"",
")",
"ppid",
"=",
"os",
".",
"getpid",
"(",
")",
"try",
":",
"pid",
"="... | Fork the process into the background.
@param pidfile: Optional PID file path.
@param sync: Wait for parent process to disappear?
@param logfile: Optional name of stdin/stderr log file or stream. | [
"Fork",
"the",
"process",
"into",
"the",
"background",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/osmagic.py#L89-L158 | train |
pyroscope/pyrocore | src/pyrocore/util/algo.py | flatten | def flatten(nested, containers=(list, tuple)):
""" Flatten a nested list in-place and return it.
"""
flat = list(nested) # handle iterators / generators
i = 0
while i < len(flat):
while isinstance(flat[i], containers):
if not flat[i]:
# kill empty list
... | python | def flatten(nested, containers=(list, tuple)):
""" Flatten a nested list in-place and return it.
"""
flat = list(nested) # handle iterators / generators
i = 0
while i < len(flat):
while isinstance(flat[i], containers):
if not flat[i]:
# kill empty list
... | [
"def",
"flatten",
"(",
"nested",
",",
"containers",
"=",
"(",
"list",
",",
"tuple",
")",
")",
":",
"flat",
"=",
"list",
"(",
"nested",
")",
"# handle iterators / generators",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"flat",
")",
":",
"while",
"i... | Flatten a nested list in-place and return it. | [
"Flatten",
"a",
"nested",
"list",
"in",
"-",
"place",
"and",
"return",
"it",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/algo.py#L42-L62 | train |
pyroscope/pyrocore | pavement.py | gendocs | def gendocs():
"create some doc pages automatically"
helppage = path("docs/references-cli-usage.rst")
content = [
".. automatically generated using 'paver gendocs'.",
"",
".. contents::",
" :local:",
"",
".. note::",
"",
" The help output... | python | def gendocs():
"create some doc pages automatically"
helppage = path("docs/references-cli-usage.rst")
content = [
".. automatically generated using 'paver gendocs'.",
"",
".. contents::",
" :local:",
"",
".. note::",
"",
" The help output... | [
"def",
"gendocs",
"(",
")",
":",
"helppage",
"=",
"path",
"(",
"\"docs/references-cli-usage.rst\"",
")",
"content",
"=",
"[",
"\".. automatically generated using 'paver gendocs'.\"",
",",
"\"\"",
",",
"\".. contents::\"",
",",
"\" :local:\"",
",",
"\"\"",
",",
"\".... | create some doc pages automatically | [
"create",
"some",
"doc",
"pages",
"automatically"
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/pavement.py#L196-L237 | train |
pyroscope/pyrocore | pavement.py | watchdog_pid | def watchdog_pid():
"""Get watchdog PID via ``netstat``."""
result = sh('netstat -tulpn 2>/dev/null | grep 127.0.0.1:{:d}'
.format(SPHINX_AUTOBUILD_PORT), capture=True, ignore_error=True)
pid = result.strip()
pid = pid.split()[-1] if pid else None
pid = pid.split('/', 1)[0] if pid an... | python | def watchdog_pid():
"""Get watchdog PID via ``netstat``."""
result = sh('netstat -tulpn 2>/dev/null | grep 127.0.0.1:{:d}'
.format(SPHINX_AUTOBUILD_PORT), capture=True, ignore_error=True)
pid = result.strip()
pid = pid.split()[-1] if pid else None
pid = pid.split('/', 1)[0] if pid an... | [
"def",
"watchdog_pid",
"(",
")",
":",
"result",
"=",
"sh",
"(",
"'netstat -tulpn 2>/dev/null | grep 127.0.0.1:{:d}'",
".",
"format",
"(",
"SPHINX_AUTOBUILD_PORT",
")",
",",
"capture",
"=",
"True",
",",
"ignore_error",
"=",
"True",
")",
"pid",
"=",
"result",
".",... | Get watchdog PID via ``netstat``. | [
"Get",
"watchdog",
"PID",
"via",
"netstat",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/pavement.py#L262-L270 | train |
pyroscope/pyrocore | pavement.py | autodocs | def autodocs():
"create Sphinx docs locally, and start a watchdog"
build_dir = path('docs/_build')
index_html = build_dir / 'html/index.html'
if build_dir.exists():
build_dir.rmtree()
with pushd("docs"):
print "\n*** Generating API doc ***\n"
sh("sphinx-apidoc -o apidoc -f -... | python | def autodocs():
"create Sphinx docs locally, and start a watchdog"
build_dir = path('docs/_build')
index_html = build_dir / 'html/index.html'
if build_dir.exists():
build_dir.rmtree()
with pushd("docs"):
print "\n*** Generating API doc ***\n"
sh("sphinx-apidoc -o apidoc -f -... | [
"def",
"autodocs",
"(",
")",
":",
"build_dir",
"=",
"path",
"(",
"'docs/_build'",
")",
"index_html",
"=",
"build_dir",
"/",
"'html/index.html'",
"if",
"build_dir",
".",
"exists",
"(",
")",
":",
"build_dir",
".",
"rmtree",
"(",
")",
"with",
"pushd",
"(",
... | create Sphinx docs locally, and start a watchdog | [
"create",
"Sphinx",
"docs",
"locally",
"and",
"start",
"a",
"watchdog"
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/pavement.py#L275-L299 | train |
pyroscope/pyrocore | pavement.py | stopdocs | def stopdocs():
"stop Sphinx watchdog"
for i in range(4):
pid = watchdog_pid()
if pid:
if not i:
sh('ps {}'.format(pid))
sh('kill {}'.format(pid))
time.sleep(.5)
else:
break | python | def stopdocs():
"stop Sphinx watchdog"
for i in range(4):
pid = watchdog_pid()
if pid:
if not i:
sh('ps {}'.format(pid))
sh('kill {}'.format(pid))
time.sleep(.5)
else:
break | [
"def",
"stopdocs",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"pid",
"=",
"watchdog_pid",
"(",
")",
"if",
"pid",
":",
"if",
"not",
"i",
":",
"sh",
"(",
"'ps {}'",
".",
"format",
"(",
"pid",
")",
")",
"sh",
"(",
"'kill {}'",
... | stop Sphinx watchdog | [
"stop",
"Sphinx",
"watchdog"
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/pavement.py#L303-L313 | train |
pyroscope/pyrocore | pavement.py | coverage | def coverage():
"generate coverage report and show in browser"
coverage_index = path("build/coverage/index.html")
coverage_index.remove()
sh("paver test")
coverage_index.exists() and webbrowser.open(coverage_index) | python | def coverage():
"generate coverage report and show in browser"
coverage_index = path("build/coverage/index.html")
coverage_index.remove()
sh("paver test")
coverage_index.exists() and webbrowser.open(coverage_index) | [
"def",
"coverage",
"(",
")",
":",
"coverage_index",
"=",
"path",
"(",
"\"build/coverage/index.html\"",
")",
"coverage_index",
".",
"remove",
"(",
")",
"sh",
"(",
"\"paver test\"",
")",
"coverage_index",
".",
"exists",
"(",
")",
"and",
"webbrowser",
".",
"open"... | generate coverage report and show in browser | [
"generate",
"coverage",
"report",
"and",
"show",
"in",
"browser"
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/pavement.py#L327-L332 | train |
pyroscope/pyrocore | src/pyrocore/config.py | lookup_announce_alias | def lookup_announce_alias(name):
""" Get canonical alias name and announce URL list for the given alias.
"""
for alias, urls in announce.items():
if alias.lower() == name.lower():
return alias, urls
raise KeyError("Unknown alias %s" % (name,)) | python | def lookup_announce_alias(name):
""" Get canonical alias name and announce URL list for the given alias.
"""
for alias, urls in announce.items():
if alias.lower() == name.lower():
return alias, urls
raise KeyError("Unknown alias %s" % (name,)) | [
"def",
"lookup_announce_alias",
"(",
"name",
")",
":",
"for",
"alias",
",",
"urls",
"in",
"announce",
".",
"items",
"(",
")",
":",
"if",
"alias",
".",
"lower",
"(",
")",
"==",
"name",
".",
"lower",
"(",
")",
":",
"return",
"alias",
",",
"urls",
"ra... | Get canonical alias name and announce URL list for the given alias. | [
"Get",
"canonical",
"alias",
"name",
"and",
"announce",
"URL",
"list",
"for",
"the",
"given",
"alias",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/config.py#L27-L34 | train |
pyroscope/pyrocore | src/pyrocore/config.py | map_announce2alias | def map_announce2alias(url):
""" Get tracker alias for announce URL, and if none is defined, the 2nd level domain.
"""
import urlparse
# Try to find an exact alias URL match and return its label
for alias, urls in announce.items():
if any(i == url for i in urls):
return alias
... | python | def map_announce2alias(url):
""" Get tracker alias for announce URL, and if none is defined, the 2nd level domain.
"""
import urlparse
# Try to find an exact alias URL match and return its label
for alias, urls in announce.items():
if any(i == url for i in urls):
return alias
... | [
"def",
"map_announce2alias",
"(",
"url",
")",
":",
"import",
"urlparse",
"# Try to find an exact alias URL match and return its label",
"for",
"alias",
",",
"urls",
"in",
"announce",
".",
"items",
"(",
")",
":",
"if",
"any",
"(",
"i",
"==",
"url",
"for",
"i",
... | Get tracker alias for announce URL, and if none is defined, the 2nd level domain. | [
"Get",
"tracker",
"alias",
"for",
"announce",
"URL",
"and",
"if",
"none",
"is",
"defined",
"the",
"2nd",
"level",
"domain",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/config.py#L37-L59 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | validate | def validate(key, val):
""" Validate a configuration value.
"""
if val and val.startswith("~/"):
return os.path.expanduser(val)
if key == "output_header_frequency":
return int(val, 10)
if key.endswith("_ecma48"):
return eval("'%s'" % val.replace("'", r"\'")) # pylint: disabl... | python | def validate(key, val):
""" Validate a configuration value.
"""
if val and val.startswith("~/"):
return os.path.expanduser(val)
if key == "output_header_frequency":
return int(val, 10)
if key.endswith("_ecma48"):
return eval("'%s'" % val.replace("'", r"\'")) # pylint: disabl... | [
"def",
"validate",
"(",
"key",
",",
"val",
")",
":",
"if",
"val",
"and",
"val",
".",
"startswith",
"(",
"\"~/\"",
")",
":",
"return",
"os",
".",
"path",
".",
"expanduser",
"(",
"val",
")",
"if",
"key",
"==",
"\"output_header_frequency\"",
":",
"return"... | Validate a configuration value. | [
"Validate",
"a",
"configuration",
"value",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L35-L45 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._update_config | def _update_config(self, namespace): # pylint: disable=no-self-use
""" Inject the items from the given dict into the configuration.
"""
for key, val in namespace.items():
setattr(config, key, val) | python | def _update_config(self, namespace): # pylint: disable=no-self-use
""" Inject the items from the given dict into the configuration.
"""
for key, val in namespace.items():
setattr(config, key, val) | [
"def",
"_update_config",
"(",
"self",
",",
"namespace",
")",
":",
"# pylint: disable=no-self-use",
"for",
"key",
",",
"val",
"in",
"namespace",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"config",
",",
"key",
",",
"val",
")"
] | Inject the items from the given dict into the configuration. | [
"Inject",
"the",
"items",
"from",
"the",
"given",
"dict",
"into",
"the",
"configuration",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L85-L89 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._interpolation_escape | def _interpolation_escape(self, namespace):
""" Re-escape interpolation strings.
"""
for key, val in namespace.items():
if '%' in val:
namespace[key] = self.INTERPOLATION_ESCAPE.sub(lambda match: '%' + match.group(0), val) | python | def _interpolation_escape(self, namespace):
""" Re-escape interpolation strings.
"""
for key, val in namespace.items():
if '%' in val:
namespace[key] = self.INTERPOLATION_ESCAPE.sub(lambda match: '%' + match.group(0), val) | [
"def",
"_interpolation_escape",
"(",
"self",
",",
"namespace",
")",
":",
"for",
"key",
",",
"val",
"in",
"namespace",
".",
"items",
"(",
")",
":",
"if",
"'%'",
"in",
"val",
":",
"namespace",
"[",
"key",
"]",
"=",
"self",
".",
"INTERPOLATION_ESCAPE",
".... | Re-escape interpolation strings. | [
"Re",
"-",
"escape",
"interpolation",
"strings",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L92-L97 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._validate_namespace | def _validate_namespace(self, namespace):
""" Validate the given namespace. This method is idempotent!
"""
# Update config values (so other code can access them in the bootstrap phase)
self._update_config(namespace)
# Validate announce URLs
for key, val in namespace["ann... | python | def _validate_namespace(self, namespace):
""" Validate the given namespace. This method is idempotent!
"""
# Update config values (so other code can access them in the bootstrap phase)
self._update_config(namespace)
# Validate announce URLs
for key, val in namespace["ann... | [
"def",
"_validate_namespace",
"(",
"self",
",",
"namespace",
")",
":",
"# Update config values (so other code can access them in the bootstrap phase)",
"self",
".",
"_update_config",
"(",
"namespace",
")",
"# Validate announce URLs",
"for",
"key",
",",
"val",
"in",
"namespa... | Validate the given namespace. This method is idempotent! | [
"Validate",
"the",
"given",
"namespace",
".",
"This",
"method",
"is",
"idempotent!"
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L100-L130 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._set_from_ini | def _set_from_ini(self, namespace, ini_file):
""" Copy values from loaded INI file to namespace.
"""
# Isolate global values
global_vars = dict((key, val)
for key, val in namespace.items()
if isinstance(val, basestring)
)
# Copy all sections
... | python | def _set_from_ini(self, namespace, ini_file):
""" Copy values from loaded INI file to namespace.
"""
# Isolate global values
global_vars = dict((key, val)
for key, val in namespace.items()
if isinstance(val, basestring)
)
# Copy all sections
... | [
"def",
"_set_from_ini",
"(",
"self",
",",
"namespace",
",",
"ini_file",
")",
":",
"# Isolate global values",
"global_vars",
"=",
"dict",
"(",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"namespace",
".",
"items",
"(",
")",
"if",
"isinsta... | Copy values from loaded INI file to namespace. | [
"Copy",
"values",
"from",
"loaded",
"INI",
"file",
"to",
"namespace",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L133-L162 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._set_defaults | def _set_defaults(self, namespace, optional_cfg_files):
""" Set default values in the given dict.
"""
# Add current configuration directory
namespace["config_dir"] = self.config_dir
# Load defaults
for idx, cfg_file in enumerate([self.CONFIG_INI] + optional_cfg_files):
... | python | def _set_defaults(self, namespace, optional_cfg_files):
""" Set default values in the given dict.
"""
# Add current configuration directory
namespace["config_dir"] = self.config_dir
# Load defaults
for idx, cfg_file in enumerate([self.CONFIG_INI] + optional_cfg_files):
... | [
"def",
"_set_defaults",
"(",
"self",
",",
"namespace",
",",
"optional_cfg_files",
")",
":",
"# Add current configuration directory",
"namespace",
"[",
"\"config_dir\"",
"]",
"=",
"self",
".",
"config_dir",
"# Load defaults",
"for",
"idx",
",",
"cfg_file",
"in",
"enu... | Set default values in the given dict. | [
"Set",
"default",
"values",
"in",
"the",
"given",
"dict",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L165-L186 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._load_ini | def _load_ini(self, namespace, config_file):
""" Load INI style configuration.
"""
self.LOG.debug("Loading %r..." % (config_file,))
ini_file = ConfigParser.SafeConfigParser()
ini_file.optionxform = str # case-sensitive option names
if ini_file.read(config_file):
... | python | def _load_ini(self, namespace, config_file):
""" Load INI style configuration.
"""
self.LOG.debug("Loading %r..." % (config_file,))
ini_file = ConfigParser.SafeConfigParser()
ini_file.optionxform = str # case-sensitive option names
if ini_file.read(config_file):
... | [
"def",
"_load_ini",
"(",
"self",
",",
"namespace",
",",
"config_file",
")",
":",
"self",
".",
"LOG",
".",
"debug",
"(",
"\"Loading %r...\"",
"%",
"(",
"config_file",
",",
")",
")",
"ini_file",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"ini_fi... | Load INI style configuration. | [
"Load",
"INI",
"style",
"configuration",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L189-L199 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader._load_py | def _load_py(self, namespace, config_file):
""" Load scripted configuration.
"""
if config_file and os.path.isfile(config_file):
self.LOG.debug("Loading %r..." % (config_file,))
exec(compile(open(config_file).read(), config_file, 'exec'), # pylint: disable=exec-used
... | python | def _load_py(self, namespace, config_file):
""" Load scripted configuration.
"""
if config_file and os.path.isfile(config_file):
self.LOG.debug("Loading %r..." % (config_file,))
exec(compile(open(config_file).read(), config_file, 'exec'), # pylint: disable=exec-used
... | [
"def",
"_load_py",
"(",
"self",
",",
"namespace",
",",
"config_file",
")",
":",
"if",
"config_file",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"config_file",
")",
":",
"self",
".",
"LOG",
".",
"debug",
"(",
"\"Loading %r...\"",
"%",
"(",
"config_file... | Load scripted configuration. | [
"Load",
"scripted",
"configuration",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L202-L210 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader.load | def load(self, optional_cfg_files=None):
""" Actually load the configuation from either the default location or the given directory.
"""
optional_cfg_files = optional_cfg_files or []
# Guard against coding errors
if self._loaded:
raise RuntimeError("INTERNAL ERROR: A... | python | def load(self, optional_cfg_files=None):
""" Actually load the configuation from either the default location or the given directory.
"""
optional_cfg_files = optional_cfg_files or []
# Guard against coding errors
if self._loaded:
raise RuntimeError("INTERNAL ERROR: A... | [
"def",
"load",
"(",
"self",
",",
"optional_cfg_files",
"=",
"None",
")",
":",
"optional_cfg_files",
"=",
"optional_cfg_files",
"or",
"[",
"]",
"# Guard against coding errors",
"if",
"self",
".",
"_loaded",
":",
"raise",
"RuntimeError",
"(",
"\"INTERNAL ERROR: Attemp... | Actually load the configuation from either the default location or the given directory. | [
"Actually",
"load",
"the",
"configuation",
"from",
"either",
"the",
"default",
"location",
"or",
"the",
"given",
"directory",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L213-L246 | train |
pyroscope/pyrocore | src/pyrocore/util/load_config.py | ConfigLoader.create | def create(self, remove_all_rc_files=False):
""" Create default configuration files at either the default location or the given directory.
"""
# Check and create configuration directory
if os.path.exists(self.config_dir):
self.LOG.debug("Configuration directory %r already exi... | python | def create(self, remove_all_rc_files=False):
""" Create default configuration files at either the default location or the given directory.
"""
# Check and create configuration directory
if os.path.exists(self.config_dir):
self.LOG.debug("Configuration directory %r already exi... | [
"def",
"create",
"(",
"self",
",",
"remove_all_rc_files",
"=",
"False",
")",
":",
"# Check and create configuration directory",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"config_dir",
")",
":",
"self",
".",
"LOG",
".",
"debug",
"(",
"\"Config... | Create default configuration files at either the default location or the given directory. | [
"Create",
"default",
"configuration",
"files",
"at",
"either",
"the",
"default",
"location",
"or",
"the",
"given",
"directory",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/load_config.py#L249-L285 | train |
pyroscope/pyrocore | src/pyrocore/scripts/mktor.py | MetafileCreator.make_magnet_meta | def make_magnet_meta(self, magnet_uri):
""" Create a magnet-uri torrent.
"""
import cgi
import hashlib
if magnet_uri.startswith("magnet:"):
magnet_uri = magnet_uri[7:]
meta = {"magnet-uri": "magnet:" + magnet_uri}
magnet_params = cgi.parse_qs(magnet_u... | python | def make_magnet_meta(self, magnet_uri):
""" Create a magnet-uri torrent.
"""
import cgi
import hashlib
if magnet_uri.startswith("magnet:"):
magnet_uri = magnet_uri[7:]
meta = {"magnet-uri": "magnet:" + magnet_uri}
magnet_params = cgi.parse_qs(magnet_u... | [
"def",
"make_magnet_meta",
"(",
"self",
",",
"magnet_uri",
")",
":",
"import",
"cgi",
"import",
"hashlib",
"if",
"magnet_uri",
".",
"startswith",
"(",
"\"magnet:\"",
")",
":",
"magnet_uri",
"=",
"magnet_uri",
"[",
"7",
":",
"]",
"meta",
"=",
"{",
"\"magnet... | Create a magnet-uri torrent. | [
"Create",
"a",
"magnet",
"-",
"uri",
"torrent",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/mktor.py#L84-L109 | train |
pyroscope/pyrocore | src/pyrocore/util/pymagic.py | get_class_logger | def get_class_logger(obj):
""" Get a logger specific for the given object's class.
"""
return logging.getLogger(obj.__class__.__module__ + '.' + obj.__class__.__name__) | python | def get_class_logger(obj):
""" Get a logger specific for the given object's class.
"""
return logging.getLogger(obj.__class__.__module__ + '.' + obj.__class__.__name__) | [
"def",
"get_class_logger",
"(",
"obj",
")",
":",
"return",
"logging",
".",
"getLogger",
"(",
"obj",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"obj",
".",
"__class__",
".",
"__name__",
")"
] | Get a logger specific for the given object's class. | [
"Get",
"a",
"logger",
"specific",
"for",
"the",
"given",
"object",
"s",
"class",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/pymagic.py#L67-L70 | train |
pyroscope/pyrocore | src/pyrocore/util/pymagic.py | JSONEncoder.default | def default(self, o): # pylint: disable=method-hidden
"""Support more object types."""
if isinstance(o, set):
return list(sorted(o))
elif hasattr(o, 'as_dict'):
return o.as_dict()
else:
return super(JSONEncoder, self).default(o) | python | def default(self, o): # pylint: disable=method-hidden
"""Support more object types."""
if isinstance(o, set):
return list(sorted(o))
elif hasattr(o, 'as_dict'):
return o.as_dict()
else:
return super(JSONEncoder, self).default(o) | [
"def",
"default",
"(",
"self",
",",
"o",
")",
":",
"# pylint: disable=method-hidden",
"if",
"isinstance",
"(",
"o",
",",
"set",
")",
":",
"return",
"list",
"(",
"sorted",
"(",
"o",
")",
")",
"elif",
"hasattr",
"(",
"o",
",",
"'as_dict'",
")",
":",
"r... | Support more object types. | [
"Support",
"more",
"object",
"types",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/pymagic.py#L85-L92 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | fmt_sz | def fmt_sz(intval):
""" Format a byte sized value.
"""
try:
return fmt.human_size(intval)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.human_size(0))) | python | def fmt_sz(intval):
""" Format a byte sized value.
"""
try:
return fmt.human_size(intval)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.human_size(0))) | [
"def",
"fmt_sz",
"(",
"intval",
")",
":",
"try",
":",
"return",
"fmt",
".",
"human_size",
"(",
"intval",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"N/A\"",
".",
"rjust",
"(",
"len",
"(",
"fmt",
".",
"human_size",
"(",
... | Format a byte sized value. | [
"Format",
"a",
"byte",
"sized",
"value",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L41-L47 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | fmt_iso | def fmt_iso(timestamp):
""" Format a UNIX timestamp to an ISO datetime string.
"""
try:
return fmt.iso_datetime(timestamp)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.iso_datetime(0))) | python | def fmt_iso(timestamp):
""" Format a UNIX timestamp to an ISO datetime string.
"""
try:
return fmt.iso_datetime(timestamp)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.iso_datetime(0))) | [
"def",
"fmt_iso",
"(",
"timestamp",
")",
":",
"try",
":",
"return",
"fmt",
".",
"iso_datetime",
"(",
"timestamp",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"N/A\"",
".",
"rjust",
"(",
"len",
"(",
"fmt",
".",
"iso_datetime"... | Format a UNIX timestamp to an ISO datetime string. | [
"Format",
"a",
"UNIX",
"timestamp",
"to",
"an",
"ISO",
"datetime",
"string",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L50-L56 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | fmt_duration | def fmt_duration(duration):
""" Format a duration value in seconds to a readable form.
"""
try:
return fmt.human_duration(float(duration), 0, 2, True)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.human_duration(0, 0, 2, True))) | python | def fmt_duration(duration):
""" Format a duration value in seconds to a readable form.
"""
try:
return fmt.human_duration(float(duration), 0, 2, True)
except (ValueError, TypeError):
return "N/A".rjust(len(fmt.human_duration(0, 0, 2, True))) | [
"def",
"fmt_duration",
"(",
"duration",
")",
":",
"try",
":",
"return",
"fmt",
".",
"human_duration",
"(",
"float",
"(",
"duration",
")",
",",
"0",
",",
"2",
",",
"True",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"N/A\""... | Format a duration value in seconds to a readable form. | [
"Format",
"a",
"duration",
"value",
"in",
"seconds",
"to",
"a",
"readable",
"form",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L59-L65 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | fmt_subst | def fmt_subst(regex, subst):
"""Replace regex with string."""
return lambda text: re.sub(regex, subst, text) if text else text | python | def fmt_subst(regex, subst):
"""Replace regex with string."""
return lambda text: re.sub(regex, subst, text) if text else text | [
"def",
"fmt_subst",
"(",
"regex",
",",
"subst",
")",
":",
"return",
"lambda",
"text",
":",
"re",
".",
"sub",
"(",
"regex",
",",
"subst",
",",
"text",
")",
"if",
"text",
"else",
"text"
] | Replace regex with string. | [
"Replace",
"regex",
"with",
"string",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L89-L91 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | preparse | def preparse(output_format):
""" Do any special processing of a template, and return the result.
"""
try:
return templating.preparse(output_format, lambda path: os.path.join(config.config_dir, "templates", path))
except ImportError as exc:
if "tempita" in str(exc):
raise erro... | python | def preparse(output_format):
""" Do any special processing of a template, and return the result.
"""
try:
return templating.preparse(output_format, lambda path: os.path.join(config.config_dir, "templates", path))
except ImportError as exc:
if "tempita" in str(exc):
raise erro... | [
"def",
"preparse",
"(",
"output_format",
")",
":",
"try",
":",
"return",
"templating",
".",
"preparse",
"(",
"output_format",
",",
"lambda",
"path",
":",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"config_dir",
",",
"\"templates\"",
",",
"path",
... | Do any special processing of a template, and return the result. | [
"Do",
"any",
"special",
"processing",
"of",
"a",
"template",
"and",
"return",
"the",
"result",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L214-L226 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | validate_field_list | def validate_field_list(fields, allow_fmt_specs=False, name_filter=None):
""" Make sure the fields in the given list exist.
@param fields: List of fields (comma-/space-separated if a string).
@type fields: list or str
@return: validated field names.
@rtype: list
"""
formats ... | python | def validate_field_list(fields, allow_fmt_specs=False, name_filter=None):
""" Make sure the fields in the given list exist.
@param fields: List of fields (comma-/space-separated if a string).
@type fields: list or str
@return: validated field names.
@rtype: list
"""
formats ... | [
"def",
"validate_field_list",
"(",
"fields",
",",
"allow_fmt_specs",
"=",
"False",
",",
"name_filter",
"=",
"None",
")",
":",
"formats",
"=",
"[",
"i",
"[",
"4",
":",
"]",
"for",
"i",
"in",
"globals",
"(",
")",
"if",
"i",
".",
"startswith",
"(",
"\"f... | Make sure the fields in the given list exist.
@param fields: List of fields (comma-/space-separated if a string).
@type fields: list or str
@return: validated field names.
@rtype: list | [
"Make",
"sure",
"the",
"fields",
"in",
"the",
"given",
"list",
"exist",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L319-L349 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | validate_sort_fields | def validate_sort_fields(sort_fields):
""" Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending).
"""
# Allow descending order per field by prefixing with '-'
descending = set()
def sort... | python | def validate_sort_fields(sort_fields):
""" Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending).
"""
# Allow descending order per field by prefixing with '-'
descending = set()
def sort... | [
"def",
"validate_sort_fields",
"(",
"sort_fields",
")",
":",
"# Allow descending order per field by prefixing with '-'",
"descending",
"=",
"set",
"(",
")",
"def",
"sort_order_filter",
"(",
"name",
")",
":",
"\"Helper to remove flag and memoize sort order\"",
"if",
"name",
... | Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending). | [
"Make",
"sure",
"the",
"fields",
"in",
"the",
"given",
"list",
"exist",
"and",
"return",
"sorting",
"key",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L352-L390 | train |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | OutputMapping.formatter_help | def formatter_help(cls):
""" Return a list of format specifiers and their documentation.
"""
result = [("raw", "Switch off the default field formatter.")]
for name, method in globals().items():
if name.startswith("fmt_"):
result.append((name[4:], method.__doc... | python | def formatter_help(cls):
""" Return a list of format specifiers and their documentation.
"""
result = [("raw", "Switch off the default field formatter.")]
for name, method in globals().items():
if name.startswith("fmt_"):
result.append((name[4:], method.__doc... | [
"def",
"formatter_help",
"(",
"cls",
")",
":",
"result",
"=",
"[",
"(",
"\"raw\"",
",",
"\"Switch off the default field formatter.\"",
")",
"]",
"for",
"name",
",",
"method",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"name",
".",
"sta... | Return a list of format specifiers and their documentation. | [
"Return",
"a",
"list",
"of",
"format",
"specifiers",
"and",
"their",
"documentation",
"."
] | 89ad01346a570943d20311a0b488440975876612 | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L138-L147 | train |
wroberts/pytimeparse | pytimeparse/timeparse.py | timeparse | def timeparse(sval, granularity='seconds'):
'''
Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Argu... | python | def timeparse(sval, granularity='seconds'):
'''
Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Argu... | [
"def",
"timeparse",
"(",
"sval",
",",
"granularity",
"=",
"'seconds'",
")",
":",
"match",
"=",
"COMPILED_SIGN",
".",
"match",
"(",
"sval",
")",
"sign",
"=",
"-",
"1",
"if",
"match",
".",
"groupdict",
"(",
")",
"[",
"'sign'",
"]",
"==",
"'-'",
"else",... | Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the string value to parse
>>> ... | [
"Parse",
"a",
"time",
"expression",
"returning",
"it",
"as",
"a",
"number",
"of",
"seconds",
".",
"If",
"possible",
"the",
"return",
"value",
"will",
"be",
"an",
"int",
";",
"if",
"this",
"is",
"not",
"possible",
"the",
"return",
"will",
"be",
"a",
"fl... | dc7e783216b98a04d3f749bd82c863d6d7c41f6e | https://github.com/wroberts/pytimeparse/blob/dc7e783216b98a04d3f749bd82c863d6d7c41f6e/pytimeparse/timeparse.py#L118-L181 | train |
tylertreat/BigQuery-Python | bigquery/client.py | get_client | def get_client(project_id=None, credentials=None,
service_url=None, service_account=None,
private_key=None, private_key_file=None,
json_key=None, json_key_file=None,
readonly=True, swallow_results=True,
num_retries=0):
"""Return a singleton ... | python | def get_client(project_id=None, credentials=None,
service_url=None, service_account=None,
private_key=None, private_key_file=None,
json_key=None, json_key_file=None,
readonly=True, swallow_results=True,
num_retries=0):
"""Return a singleton ... | [
"def",
"get_client",
"(",
"project_id",
"=",
"None",
",",
"credentials",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
"service_account",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"private_key_file",
"=",
"None",
",",
"json_key",
"=",
"None",
... | Return a singleton instance of BigQueryClient. Either
AssertionCredentials or a service account and private key combination need
to be provided in order to authenticate requests to BigQuery.
Parameters
----------
project_id : str, optional
The BigQuery project id, required unless json_key o... | [
"Return",
"a",
"singleton",
"instance",
"of",
"BigQueryClient",
".",
"Either",
"AssertionCredentials",
"or",
"a",
"service",
"account",
"and",
"private",
"key",
"combination",
"need",
"to",
"be",
"provided",
"in",
"order",
"to",
"authenticate",
"requests",
"to",
... | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L54-L155 | train |
tylertreat/BigQuery-Python | bigquery/client.py | get_projects | def get_projects(bq_service):
"""Given the BigQuery service, return data about all projects."""
projects_request = bq_service.projects().list().execute()
projects = []
for project in projects_request.get('projects', []):
project_data = {
'id': project['id'],
'name': proj... | python | def get_projects(bq_service):
"""Given the BigQuery service, return data about all projects."""
projects_request = bq_service.projects().list().execute()
projects = []
for project in projects_request.get('projects', []):
project_data = {
'id': project['id'],
'name': proj... | [
"def",
"get_projects",
"(",
"bq_service",
")",
":",
"projects_request",
"=",
"bq_service",
".",
"projects",
"(",
")",
".",
"list",
"(",
")",
".",
"execute",
"(",
")",
"projects",
"=",
"[",
"]",
"for",
"project",
"in",
"projects_request",
".",
"get",
"(",... | Given the BigQuery service, return data about all projects. | [
"Given",
"the",
"BigQuery",
"service",
"return",
"data",
"about",
"all",
"projects",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L158-L169 | train |
tylertreat/BigQuery-Python | bigquery/client.py | _get_bq_service | def _get_bq_service(credentials=None, service_url=None):
"""Construct an authorized BigQuery service object."""
assert credentials, 'Must provide ServiceAccountCredentials'
http = credentials.authorize(Http())
service = build(
'bigquery',
'v2',
http=http,
discoveryServi... | python | def _get_bq_service(credentials=None, service_url=None):
"""Construct an authorized BigQuery service object."""
assert credentials, 'Must provide ServiceAccountCredentials'
http = credentials.authorize(Http())
service = build(
'bigquery',
'v2',
http=http,
discoveryServi... | [
"def",
"_get_bq_service",
"(",
"credentials",
"=",
"None",
",",
"service_url",
"=",
"None",
")",
":",
"assert",
"credentials",
",",
"'Must provide ServiceAccountCredentials'",
"http",
"=",
"credentials",
".",
"authorize",
"(",
"Http",
"(",
")",
")",
"service",
"... | Construct an authorized BigQuery service object. | [
"Construct",
"an",
"authorized",
"BigQuery",
"service",
"object",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L172-L186 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._submit_query_job | def _submit_query_job(self, query_data):
""" Submit a query job to BigQuery.
This is similar to BigQueryClient.query, but gives the user
direct access to the query method on the offical BigQuery
python client.
For fine-grained control over a query job, see:
... | python | def _submit_query_job(self, query_data):
""" Submit a query job to BigQuery.
This is similar to BigQueryClient.query, but gives the user
direct access to the query method on the offical BigQuery
python client.
For fine-grained control over a query job, see:
... | [
"def",
"_submit_query_job",
"(",
"self",
",",
"query_data",
")",
":",
"logger",
".",
"debug",
"(",
"'Submitting query job: %s'",
"%",
"query_data",
")",
"job_collection",
"=",
"self",
".",
"bigquery",
".",
"jobs",
"(",
")",
"try",
":",
"query_reply",
"=",
"j... | Submit a query job to BigQuery.
This is similar to BigQueryClient.query, but gives the user
direct access to the query method on the offical BigQuery
python client.
For fine-grained control over a query job, see:
https://google-api-client-libraries.appspot.c... | [
"Submit",
"a",
"query",
"job",
"to",
"BigQuery",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L226-L279 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._insert_job | def _insert_job(self, body_object):
""" Submit a job to BigQuery
Direct proxy to the insert() method of the offical BigQuery
python client.
Able to submit load, link, query, copy, or extract jobs.
For more details, see:
https://google-api-client-lib... | python | def _insert_job(self, body_object):
""" Submit a job to BigQuery
Direct proxy to the insert() method of the offical BigQuery
python client.
Able to submit load, link, query, copy, or extract jobs.
For more details, see:
https://google-api-client-lib... | [
"def",
"_insert_job",
"(",
"self",
",",
"body_object",
")",
":",
"logger",
".",
"debug",
"(",
"'Submitting job: %s'",
"%",
"body_object",
")",
"job_collection",
"=",
"self",
".",
"bigquery",
".",
"jobs",
"(",
")",
"return",
"job_collection",
".",
"insert",
"... | Submit a job to BigQuery
Direct proxy to the insert() method of the offical BigQuery
python client.
Able to submit load, link, query, copy, or extract jobs.
For more details, see:
https://google-api-client-libraries.appspot.com/documentation/bigquery/v2/pyt... | [
"Submit",
"a",
"job",
"to",
"BigQuery"
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L302-L333 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.query | def query(self, query, max_results=None, timeout=0, dry_run=False, use_legacy_sql=None, external_udf_uris=None):
"""Submit a query to BigQuery.
Parameters
----------
query : str
BigQuery query string
max_results : int, optional
The maximum number of rows ... | python | def query(self, query, max_results=None, timeout=0, dry_run=False, use_legacy_sql=None, external_udf_uris=None):
"""Submit a query to BigQuery.
Parameters
----------
query : str
BigQuery query string
max_results : int, optional
The maximum number of rows ... | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"max_results",
"=",
"None",
",",
"timeout",
"=",
"0",
",",
"dry_run",
"=",
"False",
",",
"use_legacy_sql",
"=",
"None",
",",
"external_udf_uris",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Exec... | Submit a query to BigQuery.
Parameters
----------
query : str
BigQuery query string
max_results : int, optional
The maximum number of rows to return per page of results.
timeout : float, optional
How long to wait for the query to complete, in ... | [
"Submit",
"a",
"query",
"to",
"BigQuery",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L335-L387 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_query_schema | def get_query_schema(self, job_id):
"""Retrieve the schema of a query by job id.
Parameters
----------
job_id : str
The job_id that references a BigQuery query
Returns
-------
list
A ``list`` of ``dict`` objects that represent the schema.... | python | def get_query_schema(self, job_id):
"""Retrieve the schema of a query by job id.
Parameters
----------
job_id : str
The job_id that references a BigQuery query
Returns
-------
list
A ``list`` of ``dict`` objects that represent the schema.... | [
"def",
"get_query_schema",
"(",
"self",
",",
"job_id",
")",
":",
"query_reply",
"=",
"self",
".",
"get_query_results",
"(",
"job_id",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"0",
")",
"if",
"not",
"query_reply",
"[",
"'jobComplete'",
"]",
":",
"logge... | Retrieve the schema of a query by job id.
Parameters
----------
job_id : str
The job_id that references a BigQuery query
Returns
-------
list
A ``list`` of ``dict`` objects that represent the schema. | [
"Retrieve",
"the",
"schema",
"of",
"a",
"query",
"by",
"job",
"id",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L389-L409 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_table_schema | def get_table_schema(self, dataset, table, project_id=None):
"""Return the table schema.
Parameters
----------
dataset : str
The dataset containing the `table`.
table : str
The table to get the schema for
project_id: str, optional
The ... | python | def get_table_schema(self, dataset, table, project_id=None):
"""Return the table schema.
Parameters
----------
dataset : str
The dataset containing the `table`.
table : str
The table to get the schema for
project_id: str, optional
The ... | [
"def",
"get_table_schema",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"result",
"=",
"self",
".",
"bigquery",
".",
"tables",
... | Return the table schema.
Parameters
----------
dataset : str
The dataset containing the `table`.
table : str
The table to get the schema for
project_id: str, optional
The project of the dataset.
Returns
-------
list
... | [
"Return",
"the",
"table",
"schema",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L411-L442 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.check_job | def check_job(self, job_id):
"""Return the state and number of results of a query by job id.
Parameters
----------
job_id : str
The job id of the query to check.
Returns
-------
tuple
(``bool``, ``int``) Whether or not the query has compl... | python | def check_job(self, job_id):
"""Return the state and number of results of a query by job id.
Parameters
----------
job_id : str
The job id of the query to check.
Returns
-------
tuple
(``bool``, ``int``) Whether or not the query has compl... | [
"def",
"check_job",
"(",
"self",
",",
"job_id",
")",
":",
"query_reply",
"=",
"self",
".",
"get_query_results",
"(",
"job_id",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"0",
")",
"return",
"(",
"query_reply",
".",
"get",
"(",
"'jobComplete'",
",",
"F... | Return the state and number of results of a query by job id.
Parameters
----------
job_id : str
The job id of the query to check.
Returns
-------
tuple
(``bool``, ``int``) Whether or not the query has completed and the
total number of... | [
"Return",
"the",
"state",
"and",
"number",
"of",
"results",
"of",
"a",
"query",
"by",
"job",
"id",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L444-L463 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_query_rows | def get_query_rows(self, job_id, offset=None, limit=None, timeout=0):
"""Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
... | python | def get_query_rows(self, job_id, offset=None, limit=None, timeout=0):
"""Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
... | [
"def",
"get_query_rows",
"(",
"self",
",",
"job_id",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"# Get query results",
"query_reply",
"=",
"self",
".",
"get_query_results",
"(",
"job_id",
",",
"offset",
"=",
... | Retrieve a list of rows from a query table by job id.
This method will append results from multiple pages together. If you
want to manually page through results, you can use `get_query_results`
method directly.
Parameters
----------
job_id : str
The job id th... | [
"Retrieve",
"a",
"list",
"of",
"rows",
"from",
"a",
"query",
"table",
"by",
"job",
"id",
".",
"This",
"method",
"will",
"append",
"results",
"from",
"multiple",
"pages",
"together",
".",
"If",
"you",
"want",
"to",
"manually",
"page",
"through",
"results",
... | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L465-L508 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.check_dataset | def check_dataset(self, dataset_id, project_id=None):
"""Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
... | python | def check_dataset(self, dataset_id, project_id=None):
"""Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
... | [
"def",
"check_dataset",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"dataset",
"=",
"self",
".",
"get_dataset",
"(",
"dataset_id",
",",
"project_id",
")",
"return",
"bool",
"(",
"dataset",
")"
] | Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
True if dataset at `dataset_id` exists, else Fasle | [
"Check",
"to",
"see",
"if",
"a",
"dataset",
"exists",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L510-L526 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_dataset | def get_dataset(self, dataset_id, project_id=None):
"""Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
... | python | def get_dataset(self, dataset_id, project_id=None):
"""Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
... | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"dataset",
"=",
"self",
".",
"bigquery",
".",
"datasets",
"(",
")",
"."... | Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
dict
Contains dataset object if ... | [
"Retrieve",
"a",
"dataset",
"if",
"it",
"exists",
"otherwise",
"return",
"an",
"empty",
"dict",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L528-L552 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_table | def get_table(self, dataset, table, project_id=None):
""" Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, option... | python | def get_table(self, dataset, table, project_id=None):
""" Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, option... | [
"def",
"get_table",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"table",
"=",
"self",
".",
"bigquery",
".",
"tables",
"(",
"... | Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, optional
The project that the table is in
Returns
... | [
"Retrieve",
"a",
"table",
"if",
"it",
"exists",
"otherwise",
"return",
"an",
"empty",
"dict",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L574-L599 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.create_table | def create_table(self, dataset, table, schema,
expiration_time=None, time_partitioning=False,
project_id=None):
"""Create a new table in the dataset.
Parameters
----------
dataset : str
The dataset to create the table in
tabl... | python | def create_table(self, dataset, table, schema,
expiration_time=None, time_partitioning=False,
project_id=None):
"""Create a new table in the dataset.
Parameters
----------
dataset : str
The dataset to create the table in
tabl... | [
"def",
"create_table",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"schema",
",",
"expiration_time",
"=",
"None",
",",
"time_partitioning",
"=",
"False",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
... | Create a new table in the dataset.
Parameters
----------
dataset : str
The dataset to create the table in
table : str
The name of the table to create
schema : dict
The table schema
expiration_time : int or double, optional
... | [
"Create",
"a",
"new",
"table",
"in",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L601-L661 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.patch_table | def patch_table(self, dataset, table, schema, project_id=None):
"""Patch an existing table in the dataset.
Parameters
----------
dataset : str
The dataset to patch the table in
table : str
The name of the table to patch
schema : dict
T... | python | def patch_table(self, dataset, table, schema, project_id=None):
"""Patch an existing table in the dataset.
Parameters
----------
dataset : str
The dataset to patch the table in
table : str
The name of the table to patch
schema : dict
T... | [
"def",
"patch_table",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"schema",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"body",
"=",
"{",
"'schema'",
":",
"{",
"'fields'",
":",
... | Patch an existing table in the dataset.
Parameters
----------
dataset : str
The dataset to patch the table in
table : str
The name of the table to patch
schema : dict
The table schema
project_id: str, optional
The project t... | [
"Patch",
"an",
"existing",
"table",
"in",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L714-L762 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.create_view | def create_view(self, dataset, view, query, use_legacy_sql=None, project_id=None):
"""Create a new view in the dataset.
Parameters
----------
dataset : str
The dataset to create the view in
view : str
The name of the view to create
query : dict
... | python | def create_view(self, dataset, view, query, use_legacy_sql=None, project_id=None):
"""Create a new view in the dataset.
Parameters
----------
dataset : str
The dataset to create the view in
view : str
The name of the view to create
query : dict
... | [
"def",
"create_view",
"(",
"self",
",",
"dataset",
",",
"view",
",",
"query",
",",
"use_legacy_sql",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"body",
"=",
"{",
"'tab... | Create a new view in the dataset.
Parameters
----------
dataset : str
The dataset to create the view in
view : str
The name of the view to create
query : dict
A query that BigQuery executes when the view is referenced.
use_lega... | [
"Create",
"a",
"new",
"view",
"in",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L764-L820 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.delete_table | def delete_table(self, dataset, table, project_id=None):
"""Delete a table from the dataset.
Parameters
----------
dataset : str
The dataset to delete the table from.
table : str
The name of the table to delete
project_id: str, optional
... | python | def delete_table(self, dataset, table, project_id=None):
"""Delete a table from the dataset.
Parameters
----------
dataset : str
The dataset to delete the table from.
table : str
The name of the table to delete
project_id: str, optional
... | [
"def",
"delete_table",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"response",
"=",
"self",
".",
"bigquery",
".",
"tables",
"(... | Delete a table from the dataset.
Parameters
----------
dataset : str
The dataset to delete the table from.
table : str
The name of the table to delete
project_id: str, optional
String id of the project
Returns
-------
... | [
"Delete",
"a",
"table",
"from",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L822-L859 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_tables | def get_tables(self, dataset_id, app_id, start_time, end_time, project_id=None):
"""Retrieve a list of tables that are related to the given app id
and are inside the range of start and end times.
Parameters
----------
dataset_id : str
The BigQuery dataset id to consi... | python | def get_tables(self, dataset_id, app_id, start_time, end_time, project_id=None):
"""Retrieve a list of tables that are related to the given app id
and are inside the range of start and end times.
Parameters
----------
dataset_id : str
The BigQuery dataset id to consi... | [
"def",
"get_tables",
"(",
"self",
",",
"dataset_id",
",",
"app_id",
",",
"start_time",
",",
"end_time",
",",
"project_id",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"start_time",
",",
"datetime",
")",
":",
"start_time",
"=",
"calendar",
".",
"timegm"... | Retrieve a list of tables that are related to the given app id
and are inside the range of start and end times.
Parameters
----------
dataset_id : str
The BigQuery dataset id to consider.
app_id : str
The appspot name
start_time : Union[datetime, ... | [
"Retrieve",
"a",
"list",
"of",
"tables",
"that",
"are",
"related",
"to",
"the",
"given",
"app",
"id",
"and",
"are",
"inside",
"the",
"range",
"of",
"start",
"and",
"end",
"times",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L861-L893 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.wait_for_job | def wait_for_job(self, job, interval=5, timeout=60):
"""
Waits until the job indicated by job_resource is done or has failed
Parameters
----------
job : Union[dict, str]
``dict`` representing a BigQuery job resource, or a ``str``
representing the BigQuery... | python | def wait_for_job(self, job, interval=5, timeout=60):
"""
Waits until the job indicated by job_resource is done or has failed
Parameters
----------
job : Union[dict, str]
``dict`` representing a BigQuery job resource, or a ``str``
representing the BigQuery... | [
"def",
"wait_for_job",
"(",
"self",
",",
"job",
",",
"interval",
"=",
"5",
",",
"timeout",
"=",
"60",
")",
":",
"complete",
"=",
"False",
"job_id",
"=",
"str",
"(",
"job",
"if",
"isinstance",
"(",
"job",
",",
"(",
"six",
".",
"binary_type",
",",
"s... | Waits until the job indicated by job_resource is done or has failed
Parameters
----------
job : Union[dict, str]
``dict`` representing a BigQuery job resource, or a ``str``
representing the BigQuery job id
interval : float, optional
Polling interval i... | [
"Waits",
"until",
"the",
"job",
"indicated",
"by",
"job_resource",
"is",
"done",
"or",
"has",
"failed"
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1274-L1321 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.push_rows | def push_rows(self, dataset, table, rows, insert_id_key=None,
skip_invalid_rows=None, ignore_unknown_values=None,
template_suffix=None, project_id=None):
"""Upload rows to BigQuery table.
Parameters
----------
dataset : str
The dataset to ... | python | def push_rows(self, dataset, table, rows, insert_id_key=None,
skip_invalid_rows=None, ignore_unknown_values=None,
template_suffix=None, project_id=None):
"""Upload rows to BigQuery table.
Parameters
----------
dataset : str
The dataset to ... | [
"def",
"push_rows",
"(",
"self",
",",
"dataset",
",",
"table",
",",
"rows",
",",
"insert_id_key",
"=",
"None",
",",
"skip_invalid_rows",
"=",
"None",
",",
"ignore_unknown_values",
"=",
"None",
",",
"template_suffix",
"=",
"None",
",",
"project_id",
"=",
"Non... | Upload rows to BigQuery table.
Parameters
----------
dataset : str
The dataset to upload to
table : str
The name of the table to insert rows into
rows : list
A ``list`` of rows (``dict`` objects) to add to the table
insert_id_k... | [
"Upload",
"rows",
"to",
"BigQuery",
"table",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1323-L1415 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.get_all_tables | def get_all_tables(self, dataset_id, project_id=None):
"""Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains th... | python | def get_all_tables(self, dataset_id, project_id=None):
"""Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains th... | [
"def",
"get_all_tables",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"tables_data",
"=",
"self",
".",
"_get_all_tables_for_dataset",
"(",
"dataset_id",
",",
"project_id",
")",
"tables",
"=",
"[",
"]",
"for",
"table",
"in",
"tabl... | Retrieve a list of tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table data for.
project_id: str
Unique ``str`` identifying the BigQuery project contains the dataset
Returns
-------
A ``list`` with... | [
"Retrieve",
"a",
"list",
"of",
"tables",
"for",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1417-L1438 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._get_all_tables_for_dataset | def _get_all_tables_for_dataset(self, dataset_id, project_id=None):
"""Retrieve a list of all tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table names for
project_id: str
Unique ``str`` identifying the BigQuery pr... | python | def _get_all_tables_for_dataset(self, dataset_id, project_id=None):
"""Retrieve a list of all tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table names for
project_id: str
Unique ``str`` identifying the BigQuery pr... | [
"def",
"_get_all_tables_for_dataset",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"result",
"=",
"self",
".",
"bigquery",
".",
"tables",
"(",
")",
".",
... | Retrieve a list of all tables for the dataset.
Parameters
----------
dataset_id : str
The dataset to retrieve table names for
project_id: str
Unique ``str`` identifying the BigQuery project contains the dataset
Returns
-------
dict
... | [
"Retrieve",
"a",
"list",
"of",
"all",
"tables",
"for",
"the",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1472-L1502 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._parse_table_list_response | def _parse_table_list_response(self, list_response):
"""Parse the response received from calling list on tables.
Parameters
----------
list_response
The response found by calling list on a BigQuery table object.
Returns
-------
dict
Dates... | python | def _parse_table_list_response(self, list_response):
"""Parse the response received from calling list on tables.
Parameters
----------
list_response
The response found by calling list on a BigQuery table object.
Returns
-------
dict
Dates... | [
"def",
"_parse_table_list_response",
"(",
"self",
",",
"list_response",
")",
":",
"tables",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"table",
"in",
"list_response",
".",
"get",
"(",
"'tables'",
",",
"[",
"]",
")",
":",
"table_ref",
"=",
"table",
".",
... | Parse the response received from calling list on tables.
Parameters
----------
list_response
The response found by calling list on a BigQuery table object.
Returns
-------
dict
Dates referenced by table names | [
"Parse",
"the",
"response",
"received",
"from",
"calling",
"list",
"on",
"tables",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1504-L1540 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._parse_table_name | def _parse_table_name(self, table_id):
"""Parse a table name in the form of appid_YYYY_MM or
YYYY_MM_appid and return a tuple consisting of YYYY-MM and the app id.
Returns (None, None) in the event of a name like <desc>_YYYYMMDD_<int>
Parameters
----------
table_id : st... | python | def _parse_table_name(self, table_id):
"""Parse a table name in the form of appid_YYYY_MM or
YYYY_MM_appid and return a tuple consisting of YYYY-MM and the app id.
Returns (None, None) in the event of a name like <desc>_YYYYMMDD_<int>
Parameters
----------
table_id : st... | [
"def",
"_parse_table_name",
"(",
"self",
",",
"table_id",
")",
":",
"# Prefix date",
"attributes",
"=",
"table_id",
".",
"split",
"(",
"'_'",
")",
"year_month",
"=",
"\"-\"",
".",
"join",
"(",
"attributes",
"[",
":",
"2",
"]",
")",
"app_id",
"=",
"\"-\""... | Parse a table name in the form of appid_YYYY_MM or
YYYY_MM_appid and return a tuple consisting of YYYY-MM and the app id.
Returns (None, None) in the event of a name like <desc>_YYYYMMDD_<int>
Parameters
----------
table_id : str
The table id as listed by BigQuery
... | [
"Parse",
"a",
"table",
"name",
"in",
"the",
"form",
"of",
"appid_YYYY_MM",
"or",
"YYYY_MM_appid",
"and",
"return",
"a",
"tuple",
"consisting",
"of",
"YYYY",
"-",
"MM",
"and",
"the",
"app",
"id",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1542-L1581 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._filter_tables_by_time | def _filter_tables_by_time(self, tables, start_time, end_time):
"""Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int... | python | def _filter_tables_by_time(self, tables, start_time, end_time):
"""Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int... | [
"def",
"_filter_tables_by_time",
"(",
"self",
",",
"tables",
",",
"start_time",
",",
"end_time",
")",
":",
"return",
"[",
"table_name",
"for",
"(",
"table_name",
",",
"unix_seconds",
")",
"in",
"tables",
".",
"items",
"(",
")",
"if",
"self",
".",
"_in_rang... | Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int
The unix time after which records will be fetched
end_... | [
"Filter",
"a",
"table",
"dictionary",
"and",
"return",
"table",
"names",
"based",
"on",
"the",
"range",
"of",
"start",
"and",
"end",
"times",
"in",
"unix",
"seconds",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1583-L1603 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._in_range | def _in_range(self, start_time, end_time, time):
"""Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
t... | python | def _in_range(self, start_time, end_time, time):
"""Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
t... | [
"def",
"_in_range",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"time",
")",
":",
"ONE_MONTH",
"=",
"2764800",
"# 32 days",
"return",
"start_time",
"<=",
"time",
"<=",
"end_time",
"or",
"time",
"<=",
"start_time",
"<=",
"time",
"+",
"ONE_MONTH",
... | Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
time : int
The unix time to check
Return... | [
"Indicate",
"if",
"the",
"given",
"time",
"falls",
"inside",
"of",
"the",
"given",
"range",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1605-L1627 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._transform_row | def _transform_row(self, row, schema):
"""Apply the given schema to the given BigQuery data row.
Parameters
----------
row
A single BigQuery row to transform
schema : list
The BigQuery table schema to apply to the row, specifically
the list of... | python | def _transform_row(self, row, schema):
"""Apply the given schema to the given BigQuery data row.
Parameters
----------
row
A single BigQuery row to transform
schema : list
The BigQuery table schema to apply to the row, specifically
the list of... | [
"def",
"_transform_row",
"(",
"self",
",",
"row",
",",
"schema",
")",
":",
"log",
"=",
"{",
"}",
"# Match each schema column with its associated row value",
"for",
"index",
",",
"col_dict",
"in",
"enumerate",
"(",
"schema",
")",
":",
"col_name",
"=",
"col_dict",... | Apply the given schema to the given BigQuery data row.
Parameters
----------
row
A single BigQuery row to transform
schema : list
The BigQuery table schema to apply to the row, specifically
the list of field dicts.
Returns
-------
... | [
"Apply",
"the",
"given",
"schema",
"to",
"the",
"given",
"BigQuery",
"data",
"row",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1664-L1711 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._recurse_on_row | def _recurse_on_row(self, col_dict, nested_value):
"""Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQue... | python | def _recurse_on_row(self, col_dict, nested_value):
"""Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQue... | [
"def",
"_recurse_on_row",
"(",
"self",
",",
"col_dict",
",",
"nested_value",
")",
":",
"row_value",
"=",
"None",
"# Multiple nested records",
"if",
"col_dict",
"[",
"'mode'",
"]",
"==",
"'REPEATED'",
"and",
"isinstance",
"(",
"nested_value",
",",
"list",
")",
... | Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQuery row.
Returns
-------
Union[dict, l... | [
"Apply",
"the",
"schema",
"specified",
"by",
"the",
"given",
"dict",
"to",
"the",
"nested",
"value",
"by",
"recursing",
"on",
"it",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1713-L1740 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient._generate_hex_for_uris | def _generate_hex_for_uris(self, uris):
"""Given uris, generate and return hex version of it
Parameters
----------
uris : list
Containing all uris
Returns
-------
str
Hexed uris
"""
return sha256((":".join(uris) + str(time... | python | def _generate_hex_for_uris(self, uris):
"""Given uris, generate and return hex version of it
Parameters
----------
uris : list
Containing all uris
Returns
-------
str
Hexed uris
"""
return sha256((":".join(uris) + str(time... | [
"def",
"_generate_hex_for_uris",
"(",
"self",
",",
"uris",
")",
":",
"return",
"sha256",
"(",
"(",
"\":\"",
".",
"join",
"(",
"uris",
")",
"+",
"str",
"(",
"time",
"(",
")",
")",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | Given uris, generate and return hex version of it
Parameters
----------
uris : list
Containing all uris
Returns
-------
str
Hexed uris | [
"Given",
"uris",
"generate",
"and",
"return",
"hex",
"version",
"of",
"it"
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1742-L1755 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.create_dataset | def create_dataset(self, dataset_id, friendly_name=None, description=None,
access=None, location=None, project_id=None):
"""Create a new BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (t... | python | def create_dataset(self, dataset_id, friendly_name=None, description=None,
access=None, location=None, project_id=None):
"""Create a new BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (t... | [
"def",
"create_dataset",
"(",
"self",
",",
"dataset_id",
",",
"friendly_name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"access",
"=",
"None",
",",
"location",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".... | Create a new BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (the
referenceID of the dataset, not the integer id of the dataset)
friendly_name: str, optional
A human readable nam... | [
"Create",
"a",
"new",
"BigQuery",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1782-L1835 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.delete_dataset | def delete_dataset(self, dataset_id, delete_contents=False, project_id=None):
"""Delete a BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (the
referenceId of the dataset)
Unique ... | python | def delete_dataset(self, dataset_id, delete_contents=False, project_id=None):
"""Delete a BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (the
referenceId of the dataset)
Unique ... | [
"def",
"delete_dataset",
"(",
"self",
",",
"dataset_id",
",",
"delete_contents",
"=",
"False",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"datasets",
"=",
"self",
".",
"b... | Delete a BigQuery dataset.
Parameters
----------
dataset_id : str
Unique ``str`` identifying the dataset with the project (the
referenceId of the dataset)
Unique ``str`` identifying the BigQuery project contains the dataset
delete_contents : b... | [
"Delete",
"a",
"BigQuery",
"dataset",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1861-L1904 | train |
tylertreat/BigQuery-Python | bigquery/client.py | BigQueryClient.update_dataset | def update_dataset(self, dataset_id, friendly_name=None, description=None,
access=None, project_id=None):
"""Updates information in an existing dataset. The update method
replaces the entire dataset resource, whereas the patch method only
replaces fields that are provided ... | python | def update_dataset(self, dataset_id, friendly_name=None, description=None,
access=None, project_id=None):
"""Updates information in an existing dataset. The update method
replaces the entire dataset resource, whereas the patch method only
replaces fields that are provided ... | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset_id",
",",
"friendly_name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"access",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"proj... | Updates information in an existing dataset. The update method
replaces the entire dataset resource, whereas the patch method only
replaces fields that are provided in the submitted dataset resource.
Parameters
----------
dataset_id : str
Unique ``str`` identifying th... | [
"Updates",
"information",
"in",
"an",
"existing",
"dataset",
".",
"The",
"update",
"method",
"replaces",
"the",
"entire",
"dataset",
"resource",
"whereas",
"the",
"patch",
"method",
"only",
"replaces",
"fields",
"that",
"are",
"provided",
"in",
"the",
"submitted... | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1906-L1956 | train |
tylertreat/BigQuery-Python | bigquery/schema_builder.py | schema_from_record | def schema_from_record(record, timestamp_parser=default_timestamp_parser):
"""Generate a BigQuery schema given an example of a record that is to be
inserted into BigQuery.
Parameters
----------
record : dict
Example of a record that is to be inserted into BigQuery
timestamp_parser : fun... | python | def schema_from_record(record, timestamp_parser=default_timestamp_parser):
"""Generate a BigQuery schema given an example of a record that is to be
inserted into BigQuery.
Parameters
----------
record : dict
Example of a record that is to be inserted into BigQuery
timestamp_parser : fun... | [
"def",
"schema_from_record",
"(",
"record",
",",
"timestamp_parser",
"=",
"default_timestamp_parser",
")",
":",
"return",
"[",
"describe_field",
"(",
"k",
",",
"v",
",",
"timestamp_parser",
"=",
"timestamp_parser",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",... | Generate a BigQuery schema given an example of a record that is to be
inserted into BigQuery.
Parameters
----------
record : dict
Example of a record that is to be inserted into BigQuery
timestamp_parser : function, optional
Unary function taking a ``str`` and returning and ``bool``... | [
"Generate",
"a",
"BigQuery",
"schema",
"given",
"an",
"example",
"of",
"a",
"record",
"that",
"is",
"to",
"be",
"inserted",
"into",
"BigQuery",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/schema_builder.py#L22-L39 | train |
tylertreat/BigQuery-Python | bigquery/schema_builder.py | describe_field | def describe_field(k, v, timestamp_parser=default_timestamp_parser):
"""Given a key representing a column name and value representing the value
stored in the column, return a representation of the BigQuery schema
element describing that field. Raise errors if invalid value types are
provided.
Param... | python | def describe_field(k, v, timestamp_parser=default_timestamp_parser):
"""Given a key representing a column name and value representing the value
stored in the column, return a representation of the BigQuery schema
element describing that field. Raise errors if invalid value types are
provided.
Param... | [
"def",
"describe_field",
"(",
"k",
",",
"v",
",",
"timestamp_parser",
"=",
"default_timestamp_parser",
")",
":",
"def",
"bq_schema_field",
"(",
"name",
",",
"bq_type",
",",
"mode",
")",
":",
"return",
"{",
"\"name\"",
":",
"name",
",",
"\"type\"",
":",
"bq... | Given a key representing a column name and value representing the value
stored in the column, return a representation of the BigQuery schema
element describing that field. Raise errors if invalid value types are
provided.
Parameters
----------
k : Union[str, unicode]
Key representing th... | [
"Given",
"a",
"key",
"representing",
"a",
"column",
"name",
"and",
"value",
"representing",
"the",
"value",
"stored",
"in",
"the",
"column",
"return",
"a",
"representation",
"of",
"the",
"BigQuery",
"schema",
"element",
"describing",
"that",
"field",
".",
"Rai... | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/schema_builder.py#L42-L98 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | render_query | def render_query(dataset, tables, select=None, conditions=None,
groupings=None, having=None, order_by=None, limit=None):
"""Render a query that will run over the given tables using the specified
parameters.
Parameters
----------
dataset : str
The BigQuery dataset to query d... | python | def render_query(dataset, tables, select=None, conditions=None,
groupings=None, having=None, order_by=None, limit=None):
"""Render a query that will run over the given tables using the specified
parameters.
Parameters
----------
dataset : str
The BigQuery dataset to query d... | [
"def",
"render_query",
"(",
"dataset",
",",
"tables",
",",
"select",
"=",
"None",
",",
"conditions",
"=",
"None",
",",
"groupings",
"=",
"None",
",",
"having",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"Non... | Render a query that will run over the given tables using the specified
parameters.
Parameters
----------
dataset : str
The BigQuery dataset to query data from
tables : Union[dict, list]
The table in `dataset` to query.
select : dict, optional
The keys function as column ... | [
"Render",
"a",
"query",
"that",
"will",
"run",
"over",
"the",
"given",
"tables",
"using",
"the",
"specified",
"parameters",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L7-L59 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_select | def _render_select(selections):
"""Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `sele... | python | def _render_select(selections):
"""Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `sele... | [
"def",
"_render_select",
"(",
"selections",
")",
":",
"if",
"not",
"selections",
":",
"return",
"'SELECT *'",
"rendered_selections",
"=",
"[",
"]",
"for",
"name",
",",
"options",
"in",
"selections",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"... | Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `selections` dict formatting | [
"Render",
"the",
"selection",
"part",
"of",
"a",
"query",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L62-L100 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _format_select | def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applie... | python | def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applie... | [
"def",
"_format_select",
"(",
"formatter",
",",
"name",
")",
":",
"for",
"caster",
"in",
"formatter",
".",
"split",
"(",
"'-'",
")",
":",
"if",
"caster",
"==",
"'SEC_TO_MICRO'",
":",
"name",
"=",
"\"%s*1000000\"",
"%",
"name",
"elif",
"':'",
"in",
"caste... | Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applied to the selector
foo would result in... | [
"Modify",
"the",
"query",
"selector",
"by",
"applying",
"any",
"formatters",
"to",
"it",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L103-L131 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_sources | def _render_sources(dataset, tables):
"""Render the source part of a query.
Parameters
----------
dataset : str
The data set to fetch log data from.
tables : Union[dict, list]
The tables to fetch log data from
Returns
-------
str
A string that represents the "fr... | python | def _render_sources(dataset, tables):
"""Render the source part of a query.
Parameters
----------
dataset : str
The data set to fetch log data from.
tables : Union[dict, list]
The tables to fetch log data from
Returns
-------
str
A string that represents the "fr... | [
"def",
"_render_sources",
"(",
"dataset",
",",
"tables",
")",
":",
"if",
"isinstance",
"(",
"tables",
",",
"dict",
")",
":",
"if",
"tables",
".",
"get",
"(",
"'date_range'",
",",
"False",
")",
":",
"try",
":",
"dataset_table",
"=",
"'.'",
".",
"join",
... | Render the source part of a query.
Parameters
----------
dataset : str
The data set to fetch log data from.
tables : Union[dict, list]
The tables to fetch log data from
Returns
-------
str
A string that represents the "from" part of a query. | [
"Render",
"the",
"source",
"part",
"of",
"a",
"query",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L134-L164 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_conditions | def _render_conditions(conditions):
"""Render the conditions part of a query.
Parameters
----------
conditions : list
A list of dictionary items to filter a table.
Returns
-------
str
A string that represents the "where" part of a query
See Also
--------
render... | python | def _render_conditions(conditions):
"""Render the conditions part of a query.
Parameters
----------
conditions : list
A list of dictionary items to filter a table.
Returns
-------
str
A string that represents the "where" part of a query
See Also
--------
render... | [
"def",
"_render_conditions",
"(",
"conditions",
")",
":",
"if",
"not",
"conditions",
":",
"return",
"\"\"",
"rendered_conditions",
"=",
"[",
"]",
"for",
"condition",
"in",
"conditions",
":",
"field",
"=",
"condition",
".",
"get",
"(",
"'field'",
")",
"field_... | Render the conditions part of a query.
Parameters
----------
conditions : list
A list of dictionary items to filter a table.
Returns
-------
str
A string that represents the "where" part of a query
See Also
--------
render_query : Further clarification of `conditio... | [
"Render",
"the",
"conditions",
"part",
"of",
"a",
"query",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L167-L205 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_condition | def _render_condition(field, field_type, comparators):
"""Render a single query condition.
Parameters
----------
field : str
The field the condition applies to
field_type : str
The data type of the field.
comparators : array_like
An iterable of logic operators to use.
... | python | def _render_condition(field, field_type, comparators):
"""Render a single query condition.
Parameters
----------
field : str
The field the condition applies to
field_type : str
The data type of the field.
comparators : array_like
An iterable of logic operators to use.
... | [
"def",
"_render_condition",
"(",
"field",
",",
"field_type",
",",
"comparators",
")",
":",
"field_type",
"=",
"field_type",
".",
"upper",
"(",
")",
"negated_conditions",
",",
"normal_conditions",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"comparator",
"in",
"comp... | Render a single query condition.
Parameters
----------
field : str
The field the condition applies to
field_type : str
The data type of the field.
comparators : array_like
An iterable of logic operators to use.
Returns
-------
str
a condition string. | [
"Render",
"a",
"single",
"query",
"condition",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L208-L272 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_condition_value | def _render_condition_value(value, field_type):
"""Render a query condition value.
Parameters
----------
value : Union[bool, int, float, str, datetime]
The value of the condition
field_type : str
The data type of the field
Returns
-------
str
A value string.
... | python | def _render_condition_value(value, field_type):
"""Render a query condition value.
Parameters
----------
value : Union[bool, int, float, str, datetime]
The value of the condition
field_type : str
The data type of the field
Returns
-------
str
A value string.
... | [
"def",
"_render_condition_value",
"(",
"value",
",",
"field_type",
")",
":",
"# BigQuery cannot cast strings to booleans, convert to ints",
"if",
"field_type",
"==",
"\"BOOLEAN\"",
":",
"value",
"=",
"1",
"if",
"value",
"else",
"0",
"elif",
"field_type",
"in",
"(",
... | Render a query condition value.
Parameters
----------
value : Union[bool, int, float, str, datetime]
The value of the condition
field_type : str
The data type of the field
Returns
-------
str
A value string. | [
"Render",
"a",
"query",
"condition",
"value",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L275-L298 | train |
tylertreat/BigQuery-Python | bigquery/query_builder.py | _render_having | def _render_having(having_conditions):
"""Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
r... | python | def _render_having(having_conditions):
"""Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
r... | [
"def",
"_render_having",
"(",
"having_conditions",
")",
":",
"if",
"not",
"having_conditions",
":",
"return",
"\"\"",
"rendered_conditions",
"=",
"[",
"]",
"for",
"condition",
"in",
"having_conditions",
":",
"field",
"=",
"condition",
".",
"get",
"(",
"'field'",... | Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
render_query : Further clarification of `condit... | [
"Render",
"the",
"having",
"part",
"of",
"a",
"query",
"."
] | 88d99de42d954d49fc281460068f0e95003da098 | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/query_builder.py#L321-L358 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.init_app | def init_app(self, app):
# type: (Flask) -> None
"""Init the Flask-MQTT addon."""
self.client_id = app.config.get("MQTT_CLIENT_ID", "")
if isinstance(self.client_id, unicode):
self.client._client_id = self.client_id.encode('utf-8')
else:
self.client._clie... | python | def init_app(self, app):
# type: (Flask) -> None
"""Init the Flask-MQTT addon."""
self.client_id = app.config.get("MQTT_CLIENT_ID", "")
if isinstance(self.client_id, unicode):
self.client._client_id = self.client_id.encode('utf-8')
else:
self.client._clie... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"# type: (Flask) -> None",
"self",
".",
"client_id",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"MQTT_CLIENT_ID\"",
",",
"\"\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"client_id",
",",
"unicode"... | Init the Flask-MQTT addon. | [
"Init",
"the",
"Flask",
"-",
"MQTT",
"addon",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L87-L133 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.subscribe | def subscribe(self, topic, qos=0):
# type: (str, int) -> Tuple[int, int]
"""
Subscribe to a certain topic.
:param topic: a string specifying the subscription topic to
subscribe to.
:param qos: the desired quality of service level for the subscription.
... | python | def subscribe(self, topic, qos=0):
# type: (str, int) -> Tuple[int, int]
"""
Subscribe to a certain topic.
:param topic: a string specifying the subscription topic to
subscribe to.
:param qos: the desired quality of service level for the subscription.
... | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"qos",
"=",
"0",
")",
":",
"# type: (str, int) -> Tuple[int, int]",
"# TODO: add support for list of topics",
"# don't subscribe if already subscribed",
"# try to subscribe",
"result",
",",
"mid",
"=",
"self",
".",
"clie... | Subscribe to a certain topic.
:param topic: a string specifying the subscription topic to
subscribe to.
:param qos: the desired quality of service level for the subscription.
Defaults to 0.
:rtype: (int, int)
:result: (result, mid)
A topic is a ... | [
"Subscribe",
"to",
"a",
"certain",
"topic",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L225-L268 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.unsubscribe | def unsubscribe(self, topic):
# type: (str) -> Optional[Tuple[int, int]]
"""
Unsubscribe from a single topic.
:param topic: a single string that is the subscription topic to
unsubscribe from
:rtype: (int, int)
:result: (result, mid)
Return... | python | def unsubscribe(self, topic):
# type: (str) -> Optional[Tuple[int, int]]
"""
Unsubscribe from a single topic.
:param topic: a single string that is the subscription topic to
unsubscribe from
:rtype: (int, int)
:result: (result, mid)
Return... | [
"def",
"unsubscribe",
"(",
"self",
",",
"topic",
")",
":",
"# type: (str) -> Optional[Tuple[int, int]]",
"# don't unsubscribe if not in topics",
"if",
"topic",
"in",
"self",
".",
"topics",
":",
"result",
",",
"mid",
"=",
"self",
".",
"client",
".",
"unsubscribe",
... | Unsubscribe from a single topic.
:param topic: a single string that is the subscription topic to
unsubscribe from
:rtype: (int, int)
:result: (result, mid)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS
to indicate success or (MQTT_ERR_NO... | [
"Unsubscribe",
"from",
"a",
"single",
"topic",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L270-L302 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.unsubscribe_all | def unsubscribe_all(self):
# type: () -> None
"""Unsubscribe from all topics."""
topics = list(self.topics.keys())
for topic in topics:
self.unsubscribe(topic) | python | def unsubscribe_all(self):
# type: () -> None
"""Unsubscribe from all topics."""
topics = list(self.topics.keys())
for topic in topics:
self.unsubscribe(topic) | [
"def",
"unsubscribe_all",
"(",
"self",
")",
":",
"# type: () -> None",
"topics",
"=",
"list",
"(",
"self",
".",
"topics",
".",
"keys",
"(",
")",
")",
"for",
"topic",
"in",
"topics",
":",
"self",
".",
"unsubscribe",
"(",
"topic",
")"
] | Unsubscribe from all topics. | [
"Unsubscribe",
"from",
"all",
"topics",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L304-L309 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.publish | def publish(self, topic, payload=None, qos=0, retain=False):
# type: (str, bytes, int, bool) -> Tuple[int, int]
"""
Send a message to the broker.
:param topic: the topic that the message should be published on
:param payload: the actual message to send. If not given, or set to
... | python | def publish(self, topic, payload=None, qos=0, retain=False):
# type: (str, bytes, int, bool) -> Tuple[int, int]
"""
Send a message to the broker.
:param topic: the topic that the message should be published on
:param payload: the actual message to send. If not given, or set to
... | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"payload",
"=",
"None",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
")",
":",
"# type: (str, bytes, int, bool) -> Tuple[int, int]",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"client",
... | Send a message to the broker.
:param topic: the topic that the message should be published on
:param payload: the actual message to send. If not given, or set to
None a zero length message will be used. Passing an
int or float will result in the payload b... | [
"Send",
"a",
"message",
"to",
"the",
"broker",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L311-L343 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.on_subscribe | def on_subscribe(self):
# type: () -> Callable
"""Decorate a callback function to handle subscritions.
**Usage:**::
@mqtt.on_subscribe()
def handle_subscribe(client, userdata, mid, granted_qos):
print('Subscription id {} granted with qos {}.'
... | python | def on_subscribe(self):
# type: () -> Callable
"""Decorate a callback function to handle subscritions.
**Usage:**::
@mqtt.on_subscribe()
def handle_subscribe(client, userdata, mid, granted_qos):
print('Subscription id {} granted with qos {}.'
... | [
"def",
"on_subscribe",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"decorator",
"(",
"handler",
")",
":",
"# type: (Callable) -> Callable",
"self",
".",
"client",
".",
"on_subscribe",
"=",
"handler",
"return",
"handler",
"return",
"decorator"
] | Decorate a callback function to handle subscritions.
**Usage:**::
@mqtt.on_subscribe()
def handle_subscribe(client, userdata, mid, granted_qos):
print('Subscription id {} granted with qos {}.'
.format(mid, granted_qos)) | [
"Decorate",
"a",
"callback",
"function",
"to",
"handle",
"subscritions",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L421-L437 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.on_unsubscribe | def on_unsubscribe(self):
# type: () -> Callable
"""Decorate a callback funtion to handle unsubscribtions.
**Usage:**::
@mqtt.unsubscribe()
def handle_unsubscribe(client, userdata, mid)
print('Unsubscribed from topic (id: {})'
.form... | python | def on_unsubscribe(self):
# type: () -> Callable
"""Decorate a callback funtion to handle unsubscribtions.
**Usage:**::
@mqtt.unsubscribe()
def handle_unsubscribe(client, userdata, mid)
print('Unsubscribed from topic (id: {})'
.form... | [
"def",
"on_unsubscribe",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"decorator",
"(",
"handler",
")",
":",
"# type: (Callable) -> Callable",
"self",
".",
"client",
".",
"on_unsubscribe",
"=",
"handler",
"return",
"handler",
"return",
"decorator"
] | Decorate a callback funtion to handle unsubscribtions.
**Usage:**::
@mqtt.unsubscribe()
def handle_unsubscribe(client, userdata, mid)
print('Unsubscribed from topic (id: {})'
.format(mid)') | [
"Decorate",
"a",
"callback",
"funtion",
"to",
"handle",
"unsubscribtions",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L439-L455 | train |
stlehmann/Flask-MQTT | flask_mqtt/__init__.py | Mqtt.on_log | def on_log(self):
# type: () -> Callable
"""Decorate a callback function to handle MQTT logging.
**Example Usage:**
::
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(client, userdata, level, buf)
"""
def d... | python | def on_log(self):
# type: () -> Callable
"""Decorate a callback function to handle MQTT logging.
**Example Usage:**
::
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(client, userdata, level, buf)
"""
def d... | [
"def",
"on_log",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"decorator",
"(",
"handler",
")",
":",
"# type: (Callable) -> Callable",
"self",
".",
"client",
".",
"on_log",
"=",
"handler",
"return",
"handler",
"return",
"decorator"
] | Decorate a callback function to handle MQTT logging.
**Example Usage:**
::
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(client, userdata, level, buf) | [
"Decorate",
"a",
"callback",
"function",
"to",
"handle",
"MQTT",
"logging",
"."
] | 77d474ab87484ae6eaef2fee3bf02406beee2e17 | https://github.com/stlehmann/Flask-MQTT/blob/77d474ab87484ae6eaef2fee3bf02406beee2e17/flask_mqtt/__init__.py#L457-L474 | train |
kennethreitz/bucketstore | bucketstore.py | list | def list():
"""Lists buckets, by name."""
s3 = boto3.resource('s3')
return [b.name for b in s3.buckets.all()] | python | def list():
"""Lists buckets, by name."""
s3 = boto3.resource('s3')
return [b.name for b in s3.buckets.all()] | [
"def",
"list",
"(",
")",
":",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"return",
"[",
"b",
".",
"name",
"for",
"b",
"in",
"s3",
".",
"buckets",
".",
"all",
"(",
")",
"]"
] | Lists buckets, by name. | [
"Lists",
"buckets",
"by",
"name",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L6-L9 | train |
kennethreitz/bucketstore | bucketstore.py | S3Bucket.delete | def delete(self, key=None):
"""Deletes the given key, or the whole bucket."""
# Delete the whole bucket.
if key is None:
# Delete everything in the bucket.
for key in self.all():
key.delete()
# Delete the bucket.
return self._boto... | python | def delete(self, key=None):
"""Deletes the given key, or the whole bucket."""
# Delete the whole bucket.
if key is None:
# Delete everything in the bucket.
for key in self.all():
key.delete()
# Delete the bucket.
return self._boto... | [
"def",
"delete",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"# Delete the whole bucket.",
"if",
"key",
"is",
"None",
":",
"# Delete everything in the bucket.",
"for",
"key",
"in",
"self",
".",
"all",
"(",
")",
":",
"key",
".",
"delete",
"(",
")",
"#... | Deletes the given key, or the whole bucket. | [
"Deletes",
"the",
"given",
"key",
"or",
"the",
"whole",
"bucket",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L80-L94 | train |
kennethreitz/bucketstore | bucketstore.py | S3Key.rename | def rename(self, new_name):
"""Renames the key to a given new name."""
# Write the new object.
self.bucket.set(new_name, self.get(), self.meta)
# Delete the current key.
self.delete()
# Set the new name.
self.name = new_name | python | def rename(self, new_name):
"""Renames the key to a given new name."""
# Write the new object.
self.bucket.set(new_name, self.get(), self.meta)
# Delete the current key.
self.delete()
# Set the new name.
self.name = new_name | [
"def",
"rename",
"(",
"self",
",",
"new_name",
")",
":",
"# Write the new object.",
"self",
".",
"bucket",
".",
"set",
"(",
"new_name",
",",
"self",
".",
"get",
"(",
")",
",",
"self",
".",
"meta",
")",
"# Delete the current key.",
"self",
".",
"delete",
... | Renames the key to a given new name. | [
"Renames",
"the",
"key",
"to",
"a",
"given",
"new",
"name",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L126-L135 | train |
kennethreitz/bucketstore | bucketstore.py | S3Key.is_public | def is_public(self):
"""Returns True if the public-read ACL is set for the Key."""
for grant in self._boto_object.Acl().grants:
if 'AllUsers' in grant['Grantee'].get('URI', ''):
if grant['Permission'] == 'READ':
return True
return False | python | def is_public(self):
"""Returns True if the public-read ACL is set for the Key."""
for grant in self._boto_object.Acl().grants:
if 'AllUsers' in grant['Grantee'].get('URI', ''):
if grant['Permission'] == 'READ':
return True
return False | [
"def",
"is_public",
"(",
"self",
")",
":",
"for",
"grant",
"in",
"self",
".",
"_boto_object",
".",
"Acl",
"(",
")",
".",
"grants",
":",
"if",
"'AllUsers'",
"in",
"grant",
"[",
"'Grantee'",
"]",
".",
"get",
"(",
"'URI'",
",",
"''",
")",
":",
"if",
... | Returns True if the public-read ACL is set for the Key. | [
"Returns",
"True",
"if",
"the",
"public",
"-",
"read",
"ACL",
"is",
"set",
"for",
"the",
"Key",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L142-L149 | train |
kennethreitz/bucketstore | bucketstore.py | S3Key.url | def url(self):
"""Returns the public URL for the given key."""
if self.is_public:
return '{0}/{1}/{2}'.format(
self.bucket._boto_s3.meta.client.meta.endpoint_url,
self.bucket.name,
self.name
)
else:
raise ValueEr... | python | def url(self):
"""Returns the public URL for the given key."""
if self.is_public:
return '{0}/{1}/{2}'.format(
self.bucket._boto_s3.meta.client.meta.endpoint_url,
self.bucket.name,
self.name
)
else:
raise ValueEr... | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_public",
":",
"return",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"self",
".",
"bucket",
".",
"_boto_s3",
".",
"meta",
".",
"client",
".",
"meta",
".",
"endpoint_url",
",",
"self",
".",
"bucket",
... | Returns the public URL for the given key. | [
"Returns",
"the",
"public",
"URL",
"for",
"the",
"given",
"key",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L167-L178 | train |
kennethreitz/bucketstore | bucketstore.py | S3Key.temp_url | def temp_url(self, duration=120):
"""Returns a temporary URL for the given key."""
return self.bucket._boto_s3.meta.client.generate_presigned_url(
'get_object',
Params={'Bucket': self.bucket.name, 'Key': self.name},
ExpiresIn=duration
) | python | def temp_url(self, duration=120):
"""Returns a temporary URL for the given key."""
return self.bucket._boto_s3.meta.client.generate_presigned_url(
'get_object',
Params={'Bucket': self.bucket.name, 'Key': self.name},
ExpiresIn=duration
) | [
"def",
"temp_url",
"(",
"self",
",",
"duration",
"=",
"120",
")",
":",
"return",
"self",
".",
"bucket",
".",
"_boto_s3",
".",
"meta",
".",
"client",
".",
"generate_presigned_url",
"(",
"'get_object'",
",",
"Params",
"=",
"{",
"'Bucket'",
":",
"self",
"."... | Returns a temporary URL for the given key. | [
"Returns",
"a",
"temporary",
"URL",
"for",
"the",
"given",
"key",
"."
] | 2d79584d44b9c422192d7fdf08a85a49addf83d5 | https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L180-L186 | train |
cs50/python-cs50 | src/cs50/cs50.py | eprint | def eprint(*args, **kwargs):
"""
Print an error message to standard error, prefixing it with
file name and line number from which method was called.
"""
end = kwargs.get("end", "\n")
sep = kwargs.get("sep", " ")
(filename, lineno) = inspect.stack()[1][1:3]
print("{}:{}: ".format(filename... | python | def eprint(*args, **kwargs):
"""
Print an error message to standard error, prefixing it with
file name and line number from which method was called.
"""
end = kwargs.get("end", "\n")
sep = kwargs.get("sep", " ")
(filename, lineno) = inspect.stack()[1][1:3]
print("{}:{}: ".format(filename... | [
"def",
"eprint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"end",
"=",
"kwargs",
".",
"get",
"(",
"\"end\"",
",",
"\"\\n\"",
")",
"sep",
"=",
"kwargs",
".",
"get",
"(",
"\"sep\"",
",",
"\" \"",
")",
"(",
"filename",
",",
"lineno",
")",... | Print an error message to standard error, prefixing it with
file name and line number from which method was called. | [
"Print",
"an",
"error",
"message",
"to",
"standard",
"error",
"prefixing",
"it",
"with",
"file",
"name",
"and",
"line",
"number",
"from",
"which",
"method",
"was",
"called",
"."
] | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L35-L44 | train |
cs50/python-cs50 | src/cs50/cs50.py | formatException | def formatException(type, value, tb):
"""
Format traceback, darkening entries from global site-packages directories
and user-specific site-packages directory.
https://stackoverflow.com/a/46071447/5156190
"""
# Absolute paths to site-packages
packages = tuple(join(abspath(p), "") for p in s... | python | def formatException(type, value, tb):
"""
Format traceback, darkening entries from global site-packages directories
and user-specific site-packages directory.
https://stackoverflow.com/a/46071447/5156190
"""
# Absolute paths to site-packages
packages = tuple(join(abspath(p), "") for p in s... | [
"def",
"formatException",
"(",
"type",
",",
"value",
",",
"tb",
")",
":",
"# Absolute paths to site-packages",
"packages",
"=",
"tuple",
"(",
"join",
"(",
"abspath",
"(",
"p",
")",
",",
"\"\"",
")",
"for",
"p",
"in",
"sys",
".",
"path",
"[",
"1",
":",
... | Format traceback, darkening entries from global site-packages directories
and user-specific site-packages directory.
https://stackoverflow.com/a/46071447/5156190 | [
"Format",
"traceback",
"darkening",
"entries",
"from",
"global",
"site",
"-",
"packages",
"directories",
"and",
"user",
"-",
"specific",
"site",
"-",
"packages",
"directory",
"."
] | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L47-L67 | train |
cs50/python-cs50 | src/cs50/cs50.py | get_char | def get_char(prompt=None):
"""
Read a line of text from standard input and return the equivalent char;
if text is not a single char, user is prompted to retry. If line can't
be read, return None.
"""
while True:
s = get_string(prompt)
if s is None:
return None
... | python | def get_char(prompt=None):
"""
Read a line of text from standard input and return the equivalent char;
if text is not a single char, user is prompted to retry. If line can't
be read, return None.
"""
while True:
s = get_string(prompt)
if s is None:
return None
... | [
"def",
"get_char",
"(",
"prompt",
"=",
"None",
")",
":",
"while",
"True",
":",
"s",
"=",
"get_string",
"(",
"prompt",
")",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"return",
"s",
"[",
"0",
"]",... | Read a line of text from standard input and return the equivalent char;
if text is not a single char, user is prompted to retry. If line can't
be read, return None. | [
"Read",
"a",
"line",
"of",
"text",
"from",
"standard",
"input",
"and",
"return",
"the",
"equivalent",
"char",
";",
"if",
"text",
"is",
"not",
"a",
"single",
"char",
"user",
"is",
"prompted",
"to",
"retry",
".",
"If",
"line",
"can",
"t",
"be",
"read",
... | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L73-L88 | train |
cs50/python-cs50 | src/cs50/cs50.py | get_float | def get_float(prompt=None):
"""
Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is Non... | python | def get_float(prompt=None):
"""
Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is Non... | [
"def",
"get_float",
"(",
"prompt",
"=",
"None",
")",
":",
"while",
"True",
":",
"s",
"=",
"get_string",
"(",
"prompt",
")",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"s",
")",
">",
"0",
"and",
"re",
".",
"search",
"(",
"... | Read a line of text from standard input and return the equivalent float
as precisely as possible; if text does not represent a double, user is
prompted to retry. If line can't be read, return None. | [
"Read",
"a",
"line",
"of",
"text",
"from",
"standard",
"input",
"and",
"return",
"the",
"equivalent",
"float",
"as",
"precisely",
"as",
"possible",
";",
"if",
"text",
"does",
"not",
"represent",
"a",
"double",
"user",
"is",
"prompted",
"to",
"retry",
".",
... | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L91-L109 | train |
cs50/python-cs50 | src/cs50/cs50.py | get_int | def get_int(prompt=None):
"""
Read a line of text from standard input and return the equivalent int;
if text does not represent an int, user is prompted to retry. If line
can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is None:
return None
... | python | def get_int(prompt=None):
"""
Read a line of text from standard input and return the equivalent int;
if text does not represent an int, user is prompted to retry. If line
can't be read, return None.
"""
while True:
s = get_string(prompt)
if s is None:
return None
... | [
"def",
"get_int",
"(",
"prompt",
"=",
"None",
")",
":",
"while",
"True",
":",
"s",
"=",
"get_string",
"(",
"prompt",
")",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"re",
".",
"search",
"(",
"r\"^[+-]?\\d+$\"",
",",
"s",
")",
":",
"try",... | Read a line of text from standard input and return the equivalent int;
if text does not represent an int, user is prompted to retry. If line
can't be read, return None. | [
"Read",
"a",
"line",
"of",
"text",
"from",
"standard",
"input",
"and",
"return",
"the",
"equivalent",
"int",
";",
"if",
"text",
"does",
"not",
"represent",
"an",
"int",
"user",
"is",
"prompted",
"to",
"retry",
".",
"If",
"line",
"can",
"t",
"be",
"read... | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/cs50.py#L112-L132 | train |
cs50/python-cs50 | src/cs50/sql.py | _connect | def _connect(dbapi_connection, connection_record):
"""Enables foreign key support."""
# If back end is sqlite
if type(dbapi_connection) is sqlite3.Connection:
# Respect foreign key constraints by default
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
... | python | def _connect(dbapi_connection, connection_record):
"""Enables foreign key support."""
# If back end is sqlite
if type(dbapi_connection) is sqlite3.Connection:
# Respect foreign key constraints by default
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
... | [
"def",
"_connect",
"(",
"dbapi_connection",
",",
"connection_record",
")",
":",
"# If back end is sqlite",
"if",
"type",
"(",
"dbapi_connection",
")",
"is",
"sqlite3",
".",
"Connection",
":",
"# Respect foreign key constraints by default",
"cursor",
"=",
"dbapi_connection... | Enables foreign key support. | [
"Enables",
"foreign",
"key",
"support",
"."
] | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/sql.py#L233-L242 | train |
cs50/python-cs50 | src/cs50/sql.py | SQL._parse | def _parse(self, e):
"""Parses an exception, returns its message."""
# MySQL
matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
if matches:
return matches.group(1)
# PostgreSQL
matches = re.search(r"^\(psycopg2\.Opera... | python | def _parse(self, e):
"""Parses an exception, returns its message."""
# MySQL
matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
if matches:
return matches.group(1)
# PostgreSQL
matches = re.search(r"^\(psycopg2\.Opera... | [
"def",
"_parse",
"(",
"self",
",",
"e",
")",
":",
"# MySQL",
"matches",
"=",
"re",
".",
"search",
"(",
"r\"^\\(_mysql_exceptions\\.OperationalError\\) \\(\\d+, \\\"(.+)\\\"\\)$\"",
",",
"str",
"(",
"e",
")",
")",
"if",
"matches",
":",
"return",
"matches",
".",
... | Parses an exception, returns its message. | [
"Parses",
"an",
"exception",
"returns",
"its",
"message",
"."
] | f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a | https://github.com/cs50/python-cs50/blob/f987e9036bcf1bf60adf50a2827cc2cd5b9fd08a/src/cs50/sql.py#L68-L87 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.