repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
pydanny/watdarepo | watdarepo/main.py | identify_vcs | def identify_vcs(repo_url, guess=False, repo_aliases=REPO_ALIASES):
"""
Determines the type of repo that `repo_url` represents.
:param repo_url: Repo URL of unknown type.
:returns: VCS type (git, hg, etc) or raises UnknownVCS exception.
"""
repo_url = unicode(repo_url)
# Do basic alias chec... | python | def identify_vcs(repo_url, guess=False, repo_aliases=REPO_ALIASES):
"""
Determines the type of repo that `repo_url` represents.
:param repo_url: Repo URL of unknown type.
:returns: VCS type (git, hg, etc) or raises UnknownVCS exception.
"""
repo_url = unicode(repo_url)
# Do basic alias chec... | [
"def",
"identify_vcs",
"(",
"repo_url",
",",
"guess",
"=",
"False",
",",
"repo_aliases",
"=",
"REPO_ALIASES",
")",
":",
"repo_url",
"=",
"unicode",
"(",
"repo_url",
")",
"# Do basic alias check",
"vcs",
"=",
"identify_vcs_vs_alias",
"(",
"repo_url",
",",
"guess"... | Determines the type of repo that `repo_url` represents.
:param repo_url: Repo URL of unknown type.
:returns: VCS type (git, hg, etc) or raises UnknownVCS exception. | [
"Determines",
"the",
"type",
"of",
"repo",
"that",
"repo_url",
"represents",
".",
":",
"param",
"repo_url",
":",
"Repo",
"URL",
"of",
"unknown",
"type",
".",
":",
"returns",
":",
"VCS",
"type",
"(",
"git",
"hg",
"etc",
")",
"or",
"raises",
"UnknownVCS",
... | train | https://github.com/pydanny/watdarepo/blob/e252a7ed7e6d9888b127c8865d28230f41847897/watdarepo/main.py#L49-L72 |
pydanny/watdarepo | watdarepo/main.py | identify_hosting_service | def identify_hosting_service(repo_url, hosting_services=HOSTING_SERVICES):
"""
Determines the hosting service of `repo_url`.
:param repo_url: Repo URL of unknown type.
:returns: Hosting service or raises UnknownHostingService exception.
"""
repo_url = unicode(repo_url)
for service in hostin... | python | def identify_hosting_service(repo_url, hosting_services=HOSTING_SERVICES):
"""
Determines the hosting service of `repo_url`.
:param repo_url: Repo URL of unknown type.
:returns: Hosting service or raises UnknownHostingService exception.
"""
repo_url = unicode(repo_url)
for service in hostin... | [
"def",
"identify_hosting_service",
"(",
"repo_url",
",",
"hosting_services",
"=",
"HOSTING_SERVICES",
")",
":",
"repo_url",
"=",
"unicode",
"(",
"repo_url",
")",
"for",
"service",
"in",
"hosting_services",
":",
"if",
"service",
"in",
"repo_url",
":",
"return",
"... | Determines the hosting service of `repo_url`.
:param repo_url: Repo URL of unknown type.
:returns: Hosting service or raises UnknownHostingService exception. | [
"Determines",
"the",
"hosting",
"service",
"of",
"repo_url",
".",
":",
"param",
"repo_url",
":",
"Repo",
"URL",
"of",
"unknown",
"type",
".",
":",
"returns",
":",
"Hosting",
"service",
"or",
"raises",
"UnknownHostingService",
"exception",
"."
] | train | https://github.com/pydanny/watdarepo/blob/e252a7ed7e6d9888b127c8865d28230f41847897/watdarepo/main.py#L75-L87 |
pydanny/watdarepo | watdarepo/main.py | watdarepo | def watdarepo(repo_url, mode='d', guess=False, repo_aliases=REPO_ALIASES, hosting_services=HOSTING_SERVICES):
"""
Gets vcs and hosting service for repo_urls
:param repo_url: Repo URL of unknown type.
:param mode: Return dictionary (default) or object
:param guess: Whether or not to make guesses
... | python | def watdarepo(repo_url, mode='d', guess=False, repo_aliases=REPO_ALIASES, hosting_services=HOSTING_SERVICES):
"""
Gets vcs and hosting service for repo_urls
:param repo_url: Repo URL of unknown type.
:param mode: Return dictionary (default) or object
:param guess: Whether or not to make guesses
... | [
"def",
"watdarepo",
"(",
"repo_url",
",",
"mode",
"=",
"'d'",
",",
"guess",
"=",
"False",
",",
"repo_aliases",
"=",
"REPO_ALIASES",
",",
"hosting_services",
"=",
"HOSTING_SERVICES",
")",
":",
"repo_url",
"=",
"unicode",
"(",
"repo_url",
")",
"# Set the repo_ur... | Gets vcs and hosting service for repo_urls
:param repo_url: Repo URL of unknown type.
:param mode: Return dictionary (default) or object
:param guess: Whether or not to make guesses
:returns: Hosting service or raises UnknownHostingService exception. | [
"Gets",
"vcs",
"and",
"hosting",
"service",
"for",
"repo_urls",
":",
"param",
"repo_url",
":",
"Repo",
"URL",
"of",
"unknown",
"type",
".",
":",
"param",
"mode",
":",
"Return",
"dictionary",
"(",
"default",
")",
"or",
"object",
":",
"param",
"guess",
":"... | train | https://github.com/pydanny/watdarepo/blob/e252a7ed7e6d9888b127c8865d28230f41847897/watdarepo/main.py#L90-L124 |
pingviini/aja | src/aja/tasks/__init__.py | create | def create(buildout_directory, buildout_extends):
"""Create buildout directory
"""
##
# Resolve arguments
directory = get_buildout_directory(buildout_directory)
extends = get_buildout_extends(buildout_extends)
##
# Create buildout directory
local('mkdir -p {0:s}'.format(directory))
... | python | def create(buildout_directory, buildout_extends):
"""Create buildout directory
"""
##
# Resolve arguments
directory = get_buildout_directory(buildout_directory)
extends = get_buildout_extends(buildout_extends)
##
# Create buildout directory
local('mkdir -p {0:s}'.format(directory))
... | [
"def",
"create",
"(",
"buildout_directory",
",",
"buildout_extends",
")",
":",
"##",
"# Resolve arguments",
"directory",
"=",
"get_buildout_directory",
"(",
"buildout_directory",
")",
"extends",
"=",
"get_buildout_extends",
"(",
"buildout_extends",
")",
"##",
"# Create ... | Create buildout directory | [
"Create",
"buildout",
"directory"
] | train | https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/tasks/__init__.py#L55-L82 |
ajvb/webpype | webpype/client.py | WebPypeClient.execute_from_file | def execute_from_file(self, url, file_var):
'''
Identical to WebPypeClient.execute(), except this function accepts a
file path or file type instead of a dictionary.
'''
if isinstance(file_var, file):
f = file_var
elif isinstance(file_var, str):
tr... | python | def execute_from_file(self, url, file_var):
'''
Identical to WebPypeClient.execute(), except this function accepts a
file path or file type instead of a dictionary.
'''
if isinstance(file_var, file):
f = file_var
elif isinstance(file_var, str):
tr... | [
"def",
"execute_from_file",
"(",
"self",
",",
"url",
",",
"file_var",
")",
":",
"if",
"isinstance",
"(",
"file_var",
",",
"file",
")",
":",
"f",
"=",
"file_var",
"elif",
"isinstance",
"(",
"file_var",
",",
"str",
")",
":",
"try",
":",
"f",
"=",
"open... | Identical to WebPypeClient.execute(), except this function accepts a
file path or file type instead of a dictionary. | [
"Identical",
"to",
"WebPypeClient",
".",
"execute",
"()",
"except",
"this",
"function",
"accepts",
"a",
"file",
"path",
"or",
"file",
"type",
"instead",
"of",
"a",
"dictionary",
"."
] | train | https://github.com/ajvb/webpype/blob/cc9ed84c81b98a83925630b417ddb67b7567b677/webpype/client.py#L82-L100 |
ajvb/webpype | webpype/client.py | WebPypeClient.execute_from_url | def execute_from_url(self, url, input_url):
'''
Identical to WebPypeClient.execute(), except this function accepts a
url instead of a dictionary or string.
'''
inputs = self._request(input_url)
resp = self.execute(url, inputs)
return resp | python | def execute_from_url(self, url, input_url):
'''
Identical to WebPypeClient.execute(), except this function accepts a
url instead of a dictionary or string.
'''
inputs = self._request(input_url)
resp = self.execute(url, inputs)
return resp | [
"def",
"execute_from_url",
"(",
"self",
",",
"url",
",",
"input_url",
")",
":",
"inputs",
"=",
"self",
".",
"_request",
"(",
"input_url",
")",
"resp",
"=",
"self",
".",
"execute",
"(",
"url",
",",
"inputs",
")",
"return",
"resp"
] | Identical to WebPypeClient.execute(), except this function accepts a
url instead of a dictionary or string. | [
"Identical",
"to",
"WebPypeClient",
".",
"execute",
"()",
"except",
"this",
"function",
"accepts",
"a",
"url",
"instead",
"of",
"a",
"dictionary",
"or",
"string",
"."
] | train | https://github.com/ajvb/webpype/blob/cc9ed84c81b98a83925630b417ddb67b7567b677/webpype/client.py#L102-L110 |
jamieleshaw/lurklib | lurklib/exceptions.py | _Exceptions.exception | def exception(self, ncode):
"""
Looks up the exception in error_dictionary and raises it.
Required arguments:
* ncode - Error numerical code.
"""
error = self.error_dictionary[ncode]
error_msg = self._buffer[self._index - 1].split(None, 3)[3]
exec('raise s... | python | def exception(self, ncode):
"""
Looks up the exception in error_dictionary and raises it.
Required arguments:
* ncode - Error numerical code.
"""
error = self.error_dictionary[ncode]
error_msg = self._buffer[self._index - 1].split(None, 3)[3]
exec('raise s... | [
"def",
"exception",
"(",
"self",
",",
"ncode",
")",
":",
"error",
"=",
"self",
".",
"error_dictionary",
"[",
"ncode",
"]",
"error_msg",
"=",
"self",
".",
"_buffer",
"[",
"self",
".",
"_index",
"-",
"1",
"]",
".",
"split",
"(",
"None",
",",
"3",
")"... | Looks up the exception in error_dictionary and raises it.
Required arguments:
* ncode - Error numerical code. | [
"Looks",
"up",
"the",
"exception",
"in",
"error_dictionary",
"and",
"raises",
"it",
".",
"Required",
"arguments",
":",
"*",
"ncode",
"-",
"Error",
"numerical",
"code",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/exceptions.py#L194-L202 |
tBaxter/django-fretboard | fretboard/templatetags/truncatechars.py | truncatechars | def truncatechars(value,arg=50):
'''
Takes a string and truncates it to the requested amount, by inserting an ellipses into the middle.
'''
arg = int(arg)
if arg < len(value):
half = (arg-3)/2
return "%s...%s" % (value[:half],value[-half:])
return value | python | def truncatechars(value,arg=50):
'''
Takes a string and truncates it to the requested amount, by inserting an ellipses into the middle.
'''
arg = int(arg)
if arg < len(value):
half = (arg-3)/2
return "%s...%s" % (value[:half],value[-half:])
return value | [
"def",
"truncatechars",
"(",
"value",
",",
"arg",
"=",
"50",
")",
":",
"arg",
"=",
"int",
"(",
"arg",
")",
"if",
"arg",
"<",
"len",
"(",
"value",
")",
":",
"half",
"=",
"(",
"arg",
"-",
"3",
")",
"/",
"2",
"return",
"\"%s...%s\"",
"%",
"(",
"... | Takes a string and truncates it to the requested amount, by inserting an ellipses into the middle. | [
"Takes",
"a",
"string",
"and",
"truncates",
"it",
"to",
"the",
"requested",
"amount",
"by",
"inserting",
"an",
"ellipses",
"into",
"the",
"middle",
"."
] | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/truncatechars.py#L5-L13 |
insilicolife/micti | build/lib/MICTI/GM.py | GM.logpdf_diagonal_gaussian | def logpdf_diagonal_gaussian(self, x, mean, cov):
'''
Compute logpdf of a multivariate Gaussian distribution with diagonal covariance at a given point x.
A multivariate Gaussian distribution with a diagonal covariance is equivalent
to a collection of independent Gaussian random variables... | python | def logpdf_diagonal_gaussian(self, x, mean, cov):
'''
Compute logpdf of a multivariate Gaussian distribution with diagonal covariance at a given point x.
A multivariate Gaussian distribution with a diagonal covariance is equivalent
to a collection of independent Gaussian random variables... | [
"def",
"logpdf_diagonal_gaussian",
"(",
"self",
",",
"x",
",",
"mean",
",",
"cov",
")",
":",
"n",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"dim",
"=",
"x",
".",
"shape",
"[",
"1",
"]",
"assert",
"(",
"dim",
"==",
"len",
"(",
"mean",
")",
"and",
... | Compute logpdf of a multivariate Gaussian distribution with diagonal covariance at a given point x.
A multivariate Gaussian distribution with a diagonal covariance is equivalent
to a collection of independent Gaussian random variables.
x should be a sparse matrix. The logpdf will be computed fo... | [
"Compute",
"logpdf",
"of",
"a",
"multivariate",
"Gaussian",
"distribution",
"with",
"diagonal",
"covariance",
"at",
"a",
"given",
"point",
"x",
".",
"A",
"multivariate",
"Gaussian",
"distribution",
"with",
"a",
"diagonal",
"covariance",
"is",
"equivalent",
"to",
... | train | https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/build/lib/MICTI/GM.py#L33-L54 |
insilicolife/micti | build/lib/MICTI/GM.py | GM.log_sum_exp | def log_sum_exp(self,x, axis):
'''Compute the log of a sum of exponentials'''
x_max = np.max(x, axis=axis)
if axis == 1:
return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) )
else:
return x_max + np.log( np.sum(np.exp(x-x_max), axis=0) ) | python | def log_sum_exp(self,x, axis):
'''Compute the log of a sum of exponentials'''
x_max = np.max(x, axis=axis)
if axis == 1:
return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) )
else:
return x_max + np.log( np.sum(np.exp(x-x_max), axis=0) ) | [
"def",
"log_sum_exp",
"(",
"self",
",",
"x",
",",
"axis",
")",
":",
"x_max",
"=",
"np",
".",
"max",
"(",
"x",
",",
"axis",
"=",
"axis",
")",
"if",
"axis",
"==",
"1",
":",
"return",
"x_max",
"+",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
... | Compute the log of a sum of exponentials | [
"Compute",
"the",
"log",
"of",
"a",
"sum",
"of",
"exponentials"
] | train | https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/build/lib/MICTI/GM.py#L100-L106 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | Energy.e | def e(self, k, n, τ, σ):
"""Band energy.
:param k: Momentum :math:`k`.
:type k: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
:type σ: int
... | python | def e(self, k, n, τ, σ):
"""Band energy.
:param k: Momentum :math:`k`.
:type k: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
:type σ: int
... | [
"def",
"e",
"(",
"self",
",",
"k",
",",
"n",
",",
"τ,",
" ",
"):",
"",
"",
"d",
"=",
"self",
".",
"_dichalcogenide",
"at",
",",
"Δ,",
" ",
" =",
"d",
"a",
"t",
", ",
"d",
"Δ",
",",
" d",
".",
"",
"",
"",
"sqrt",
"=",
"numpy",
".",
"sqrt... | Band energy.
:param k: Momentum :math:`k`.
:type k: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
:type σ: int
:return: :math:`E^n_{τ σ} (k)`
... | [
"Band",
"energy",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L17-L39 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | Energy.k | def k(self, e, n, τ, σ):
"""Inverse energy-momentum relation.
:param e: Energy :math:`E`.
:type e: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
... | python | def k(self, e, n, τ, σ):
"""Inverse energy-momentum relation.
:param e: Energy :math:`E`.
:type e: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
... | [
"def",
"k",
"(",
"self",
",",
"e",
",",
"n",
",",
"τ,",
" ",
"):",
"",
"",
"d",
"=",
"self",
".",
"_dichalcogenide",
"at",
",",
"Δ,",
" ",
" =",
"d",
"a",
"t",
", ",
"d",
"Δ",
",",
" d",
".",
"",
"",
"",
"sqrt",
"=",
"numpy",
".",
"sqrt... | Inverse energy-momentum relation.
:param e: Energy :math:`E`.
:type e: float
:param n: Band index :math:`n = ±1`.
:type n: int
:param τ: Valley index :math:`τ = ±1`.
:type τ: int
:param σ: Spin index :math:`σ = ±1`.
:type σ: int
:return: :math... | [
"Inverse",
"energy",
"-",
"momentum",
"relation",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L43-L68 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | UpperValenceBand.Δμ(s | def Δμ(self):
"""Chemical potential offset.
The distance of the chemical potential
from the top of the upper valence band.
:return: :math:`Δμ`
:rtype: float
:default: :math:`-λ`
"""
if not hasattr(self, '_Δμ'): self.Δμ = -self._dichalcogenide.λ
r... | python | def Δμ(self):
"""Chemical potential offset.
The distance of the chemical potential
from the top of the upper valence band.
:return: :math:`Δμ`
:rtype: float
:default: :math:`-λ`
"""
if not hasattr(self, '_Δμ'): self.Δμ = -self._dichalcogenide.λ
r... | [
"def",
"Δμ(s",
"e",
"lf):",
"",
"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_Δμ'):",
" ",
"s",
"lf.Δ",
"μ",
" = -",
"e",
"f",
"._di",
"c",
"halcogenide.λ",
"",
"",
"return",
"self",
".",
"_Δμ"
] | Chemical potential offset.
The distance of the chemical potential
from the top of the upper valence band.
:return: :math:`Δμ`
:rtype: float
:default: :math:`-λ` | [
"Chemical",
"potential",
"offset",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L88-L99 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | UpperValenceBand.ξ_bounds( | def ξ_bounds(self):
"""Allowed range for the variable :math:`ξ = E - μ`.
:return: :math:`(\\left|Δμ\\right| - 2 λ, \\left|Δμ\\right|)`
:rtype: tuple
"""
λ, Δμ = self._dichalcogenide.λ, self.Δμ
return (abs(Δμ) - 2 * λ, abs(Δμ)) | python | def ξ_bounds(self):
"""Allowed range for the variable :math:`ξ = E - μ`.
:return: :math:`(\\left|Δμ\\right| - 2 λ, \\left|Δμ\\right|)`
:rtype: tuple
"""
λ, Δμ = self._dichalcogenide.λ, self.Δμ
return (abs(Δμ) - 2 * λ, abs(Δμ)) | [
"def",
"ξ_bounds(",
"s",
"elf)",
":",
"",
"λ,",
" ",
"μ = ",
"e",
"f._d",
"i",
"chalcogenide.λ,",
" ",
"se",
"l",
".Δμ",
"",
"",
"return",
"(",
"abs",
"(",
"Δμ) ",
"-",
"2",
"*",
"λ",
" a",
"b",
"(Δμ",
")",
")",
"",
""
] | Allowed range for the variable :math:`ξ = E - μ`.
:return: :math:`(\\left|Δμ\\right| - 2 λ, \\left|Δμ\\right|)`
:rtype: tuple | [
"Allowed",
"range",
"for",
"the",
"variable",
":",
"math",
":",
"ξ",
"=",
"E",
"-",
"μ",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L119-L126 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | UpperValenceBand.ρ( | def ρ(self, e):
"""Density of states.
:param e: Energy :math:`E`.
:type e: float
:return: :math:`ρ(E) = \\left|k'(E) k(E)\\right|`
:rtype: float
"""
d = self._dichalcogenide
at, λ = d.at, d.λ
return abs(2 * e - λ) * (2 * at**2)**(-1) | python | def ρ(self, e):
"""Density of states.
:param e: Energy :math:`E`.
:type e: float
:return: :math:`ρ(E) = \\left|k'(E) k(E)\\right|`
:rtype: float
"""
d = self._dichalcogenide
at, λ = d.at, d.λ
return abs(2 * e - λ) * (2 * at**2)**(-1) | [
"def",
"ρ(",
"s",
"elf,",
" ",
")",
":",
"",
"d",
"=",
"self",
".",
"_dichalcogenide",
"at",
",",
"λ ",
" ",
".",
"a",
"t,",
" ",
".",
"λ",
"",
"return",
"abs",
"(",
"2",
"*",
"e",
"-",
"λ)",
" ",
" ",
"2",
" ",
" ",
"t*",
"*2",
")",
"*... | Density of states.
:param e: Energy :math:`E`.
:type e: float
:return: :math:`ρ(E) = \\left|k'(E) k(E)\\right|`
:rtype: float | [
"Density",
"of",
"states",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L128-L139 |
razor-x/dichalcogenides | dichalcogenides/dichalcogenide/energy.py | UpperValenceBand.trig | def trig(self, name):
"""Trigonometric functions of the energy.
* ``sin θ`` - :math:`\\sin θ(E)`
* ``cos θ`` - :math:`\\cos θ(E)`
* ``sin^2 θ/2`` - :math:`\\sin^2 \\frac{θ(E)}{2}`
* ``cos^2 θ/2`` - :math:`\\cos^2 \\frac{θ(E)}{2}`
:param name: One of the ... | python | def trig(self, name):
"""Trigonometric functions of the energy.
* ``sin θ`` - :math:`\\sin θ(E)`
* ``cos θ`` - :math:`\\cos θ(E)`
* ``sin^2 θ/2`` - :math:`\\sin^2 \\frac{θ(E)}{2}`
* ``cos^2 θ/2`` - :math:`\\cos^2 \\frac{θ(E)}{2}`
:param name: One of the ... | [
"def",
"trig",
"(",
"self",
",",
"name",
")",
":",
"fn",
"=",
"{",
"}",
"λ,",
" ",
" =",
"s",
"lf._",
"d",
"ichalcogenide.λ",
",",
" s",
"e",
"f._d",
"i",
"chalcogenide.Δ",
"",
"",
"sqrt",
"=",
"numpy",
".",
"sqrt",
"x",
"=",
"lambda",
"e",
":"... | Trigonometric functions of the energy.
* ``sin θ`` - :math:`\\sin θ(E)`
* ``cos θ`` - :math:`\\cos θ(E)`
* ``sin^2 θ/2`` - :math:`\\sin^2 \\frac{θ(E)}{2}`
* ``cos^2 θ/2`` - :math:`\\cos^2 \\frac{θ(E)}{2}`
:param name: One of the above function names.
:ty... | [
"Trigonometric",
"functions",
"of",
"the",
"energy",
"."
] | train | https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/dichalcogenide/energy.py#L141-L165 |
SmartDeveloperHub/agora-client | agora/client/execution.py | __extend_uri | def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short... | python | def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short... | [
"def",
"__extend_uri",
"(",
"prefixes",
",",
"short",
")",
":",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"short",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"short",
".",
"replace",
"(",
"prefix",
"+",
"':'",
",",
"prefixes",
"[",
"pref... | Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return: | [
"Extend",
"a",
"prefixed",
"uri",
"with",
"the",
"help",
"of",
"a",
"specific",
"dictionary",
"of",
"prefixes",
":",
"param",
"prefixes",
":",
"Dictionary",
"of",
"prefixes",
":",
"param",
"short",
":",
"Prefixed",
"uri",
"to",
"be",
"extended",
":",
"retu... | train | https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L68-L78 |
SmartDeveloperHub/agora-client | agora/client/execution.py | PlanExecutor.__extract_patterns_and_spaces | def __extract_patterns_and_spaces(self):
"""
Analyses the search plan graph in order to build the required data structures from patterns
and spaces.
:return:
"""
def __decorate_nodes(nodes, space):
"""
Performs a backward search from a list of pat... | python | def __extract_patterns_and_spaces(self):
"""
Analyses the search plan graph in order to build the required data structures from patterns
and spaces.
:return:
"""
def __decorate_nodes(nodes, space):
"""
Performs a backward search from a list of pat... | [
"def",
"__extract_patterns_and_spaces",
"(",
"self",
")",
":",
"def",
"__decorate_nodes",
"(",
"nodes",
",",
"space",
")",
":",
"\"\"\"\n Performs a backward search from a list of pattern nodes and assigns a set of search spaces\n to all encountered nodes.\n ... | Analyses the search plan graph in order to build the required data structures from patterns
and spaces.
:return: | [
"Analyses",
"the",
"search",
"plan",
"graph",
"in",
"order",
"to",
"build",
"the",
"required",
"data",
"structures",
"from",
"patterns",
"and",
"spaces",
".",
":",
"return",
":"
] | train | https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L100-L164 |
SmartDeveloperHub/agora-client | agora/client/execution.py | PlanExecutor.get_fragment | def get_fragment(self, **kwargs):
"""
Return a complete fragment.
:param gp:
:return:
"""
gen, namespaces, plan = self.get_fragment_generator(**kwargs)
graph = ConjunctiveGraph()
[graph.bind(prefix, u) for (prefix, u) in namespaces]
[graph.add((s, ... | python | def get_fragment(self, **kwargs):
"""
Return a complete fragment.
:param gp:
:return:
"""
gen, namespaces, plan = self.get_fragment_generator(**kwargs)
graph = ConjunctiveGraph()
[graph.bind(prefix, u) for (prefix, u) in namespaces]
[graph.add((s, ... | [
"def",
"get_fragment",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"gen",
",",
"namespaces",
",",
"plan",
"=",
"self",
".",
"get_fragment_generator",
"(",
"*",
"*",
"kwargs",
")",
"graph",
"=",
"ConjunctiveGraph",
"(",
")",
"[",
"graph",
".",
"bind... | Return a complete fragment.
:param gp:
:return: | [
"Return",
"a",
"complete",
"fragment",
".",
":",
"param",
"gp",
":",
":",
"return",
":"
] | train | https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L166-L177 |
SmartDeveloperHub/agora-client | agora/client/execution.py | PlanExecutor.get_fragment_generator | def get_fragment_generator(self, on_load=None, on_seeds=None, on_plink=None, on_link=None, on_type=None,
on_type_validation=None, on_tree=None, workers=None, stop_event=None, queue_wait=None,
queue_size=100, provider=None, lazy=True):
"""
Cre... | python | def get_fragment_generator(self, on_load=None, on_seeds=None, on_plink=None, on_link=None, on_type=None,
on_type_validation=None, on_tree=None, workers=None, stop_event=None, queue_wait=None,
queue_size=100, provider=None, lazy=True):
"""
Cre... | [
"def",
"get_fragment_generator",
"(",
"self",
",",
"on_load",
"=",
"None",
",",
"on_seeds",
"=",
"None",
",",
"on_plink",
"=",
"None",
",",
"on_link",
"=",
"None",
",",
"on_type",
"=",
"None",
",",
"on_type_validation",
"=",
"None",
",",
"on_tree",
"=",
... | Create a fragment generator that executes the search plan.
:param on_load: Function to be called just after a new URI is dereferenced
:param on_seeds: Function to be called just after a seed of a tree is identified
:param on_plink: Function to be called when a pattern link is reached
:pa... | [
"Create",
"a",
"fragment",
"generator",
"that",
"executes",
"the",
"search",
"plan",
".",
":",
"param",
"on_load",
":",
"Function",
"to",
"be",
"called",
"just",
"after",
"a",
"new",
"URI",
"is",
"dereferenced",
":",
"param",
"on_seeds",
":",
"Function",
"... | train | https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L179-L595 |
neuroticnerd/armory | armory/phone/cli.py | CLI | def CLI(ctx, config, list_lookups):
"""Lookup basic phone number information or send SMS messages"""
loglevel = 'info'
verbosity = getattr(logging, loglevel.upper(), 'INFO')
#verbosity = logging.DEBUG
ctx.obj = {
'verbosity': verbosity,
'logfile': None,
'config': {'lookups': ... | python | def CLI(ctx, config, list_lookups):
"""Lookup basic phone number information or send SMS messages"""
loglevel = 'info'
verbosity = getattr(logging, loglevel.upper(), 'INFO')
#verbosity = logging.DEBUG
ctx.obj = {
'verbosity': verbosity,
'logfile': None,
'config': {'lookups': ... | [
"def",
"CLI",
"(",
"ctx",
",",
"config",
",",
"list_lookups",
")",
":",
"loglevel",
"=",
"'info'",
"verbosity",
"=",
"getattr",
"(",
"logging",
",",
"loglevel",
".",
"upper",
"(",
")",
",",
"'INFO'",
")",
"#verbosity = logging.DEBUG",
"ctx",
".",
"obj",
... | Lookup basic phone number information or send SMS messages | [
"Lookup",
"basic",
"phone",
"number",
"information",
"or",
"send",
"SMS",
"messages"
] | train | https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/phone/cli.py#L37-L132 |
neuroticnerd/armory | armory/phone/cli.py | lookup | def lookup(ctx, number, comment, cache):
"""Get the carrier and country code for a phone number"""
phone = PhoneNumber(number, comment=comment)
info('{0} | {1}'.format(phone.number, ctx.obj['config']['lookups'].keys()))
if phone.number in ctx.obj['config']['lookups']:
info('{0} is already cached... | python | def lookup(ctx, number, comment, cache):
"""Get the carrier and country code for a phone number"""
phone = PhoneNumber(number, comment=comment)
info('{0} | {1}'.format(phone.number, ctx.obj['config']['lookups'].keys()))
if phone.number in ctx.obj['config']['lookups']:
info('{0} is already cached... | [
"def",
"lookup",
"(",
"ctx",
",",
"number",
",",
"comment",
",",
"cache",
")",
":",
"phone",
"=",
"PhoneNumber",
"(",
"number",
",",
"comment",
"=",
"comment",
")",
"info",
"(",
"'{0} | {1}'",
".",
"format",
"(",
"phone",
".",
"number",
",",
"ctx",
"... | Get the carrier and country code for a phone number | [
"Get",
"the",
"carrier",
"and",
"country",
"code",
"for",
"a",
"phone",
"number"
] | train | https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/phone/cli.py#L149-L164 |
b3j0f/annotation | b3j0f/annotation/check.py | Condition._interception | def _interception(self, joinpoint):
"""Intercept call of joinpoint callee in doing pre/post conditions.
"""
if self.pre_cond is not None:
self.pre_cond(joinpoint)
result = joinpoint.proceed()
if self.post_cond is not None:
joinpoint.exec_ctx[Condition.R... | python | def _interception(self, joinpoint):
"""Intercept call of joinpoint callee in doing pre/post conditions.
"""
if self.pre_cond is not None:
self.pre_cond(joinpoint)
result = joinpoint.proceed()
if self.post_cond is not None:
joinpoint.exec_ctx[Condition.R... | [
"def",
"_interception",
"(",
"self",
",",
"joinpoint",
")",
":",
"if",
"self",
".",
"pre_cond",
"is",
"not",
"None",
":",
"self",
".",
"pre_cond",
"(",
"joinpoint",
")",
"result",
"=",
"joinpoint",
".",
"proceed",
"(",
")",
"if",
"self",
".",
"post_con... | Intercept call of joinpoint callee in doing pre/post conditions. | [
"Intercept",
"call",
"of",
"joinpoint",
"callee",
"in",
"doing",
"pre",
"/",
"post",
"conditions",
"."
] | train | https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/check.py#L79-L92 |
dlancer/django-appcore | appcore/views/decorators.py | anonymous_required | def anonymous_required(function):
"""Redirect to user profile if user is already logged-in"""
def wrapper(*args, **kwargs):
if args[0].user.is_authenticated():
url = settings.ANONYMOUS_REQUIRED_REDIRECT_URL
return HttpResponseRedirect(reverse(url))
return function(*args,... | python | def anonymous_required(function):
"""Redirect to user profile if user is already logged-in"""
def wrapper(*args, **kwargs):
if args[0].user.is_authenticated():
url = settings.ANONYMOUS_REQUIRED_REDIRECT_URL
return HttpResponseRedirect(reverse(url))
return function(*args,... | [
"def",
"anonymous_required",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"[",
"0",
"]",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"url",
"=",
"settings",
".",
"ANONYMOUS_R... | Redirect to user profile if user is already logged-in | [
"Redirect",
"to",
"user",
"profile",
"if",
"user",
"is",
"already",
"logged",
"-",
"in"
] | train | https://github.com/dlancer/django-appcore/blob/8ba82a9268f23afd451e6ffd0367c54509108348/appcore/views/decorators.py#L7-L16 |
minhhoit/yacms | yacms/generic/templatetags/disqus_tags.py | disqus_sso_script | def disqus_sso_script(context):
"""
Provides a generic context variable which adds single-sign-on
support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and
``COMMENTS_DISQUS_API_SECRET_KEY`` are specified.
"""
settings = context["settings"]
public_key = getattr(settings, "COMMENTS_DISQUS_A... | python | def disqus_sso_script(context):
"""
Provides a generic context variable which adds single-sign-on
support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and
``COMMENTS_DISQUS_API_SECRET_KEY`` are specified.
"""
settings = context["settings"]
public_key = getattr(settings, "COMMENTS_DISQUS_A... | [
"def",
"disqus_sso_script",
"(",
"context",
")",
":",
"settings",
"=",
"context",
"[",
"\"settings\"",
"]",
"public_key",
"=",
"getattr",
"(",
"settings",
",",
"\"COMMENTS_DISQUS_API_PUBLIC_KEY\"",
",",
"\"\"",
")",
"secret_key",
"=",
"getattr",
"(",
"settings",
... | Provides a generic context variable which adds single-sign-on
support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and
``COMMENTS_DISQUS_API_SECRET_KEY`` are specified. | [
"Provides",
"a",
"generic",
"context",
"variable",
"which",
"adds",
"single",
"-",
"sign",
"-",
"on",
"support",
"to",
"DISQUS",
"if",
"COMMENTS_DISQUS_API_PUBLIC_KEY",
"and",
"COMMENTS_DISQUS_API_SECRET_KEY",
"are",
"specified",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/disqus_tags.py#L26-L39 |
coghost/izen | izen/prettify.py | Prettify.init_color_symbols | def init_color_symbols(self):
"""
'home', 'popover', 'get', 'scroll', 'paginate',
'sleep', 'git', 'browser', 'bug',
'end', 'right', 'wrong', 'save', 'main', 'raw'
- font support: https://github.com/ryanoasis/nerd-fonts
"""
# symbols = OrderedDict({})
... | python | def init_color_symbols(self):
"""
'home', 'popover', 'get', 'scroll', 'paginate',
'sleep', 'git', 'browser', 'bug',
'end', 'right', 'wrong', 'save', 'main', 'raw'
- font support: https://github.com/ryanoasis/nerd-fonts
"""
# symbols = OrderedDict({})
... | [
"def",
"init_color_symbols",
"(",
"self",
")",
":",
"# symbols = OrderedDict({})",
"if",
"self",
".",
"is_prod",
":",
"return",
"keys",
"=",
"[",
"'home'",
",",
"'popover'",
",",
"'get'",
",",
"'scroll'",
",",
"'paginate'",
",",
"'sleep'",
",",
"'git'",
",",... | 'home', 'popover', 'get', 'scroll', 'paginate',
'sleep', 'git', 'browser', 'bug',
'end', 'right', 'wrong', 'save', 'main', 'raw'
- font support: https://github.com/ryanoasis/nerd-fonts | [
"home",
"popover",
"get",
"scroll",
"paginate",
"sleep",
"git",
"browser",
"bug",
"end",
"right",
"wrong",
"save",
"main",
"raw"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/prettify.py#L62-L91 |
coghost/izen | izen/prettify.py | Prettify.log_random_sleep | def log_random_sleep(self, minimum=3.0, scale=1.0, hints=None):
"""wrap random sleep.
- log it for debug purpose only
"""
hints = '{} slept'.format(hints) if hints else 'slept'
st = time.time()
helper.random_sleep(minimum, scale)
log.debug('{} {} {}s'.format(
... | python | def log_random_sleep(self, minimum=3.0, scale=1.0, hints=None):
"""wrap random sleep.
- log it for debug purpose only
"""
hints = '{} slept'.format(hints) if hints else 'slept'
st = time.time()
helper.random_sleep(minimum, scale)
log.debug('{} {} {}s'.format(
... | [
"def",
"log_random_sleep",
"(",
"self",
",",
"minimum",
"=",
"3.0",
",",
"scale",
"=",
"1.0",
",",
"hints",
"=",
"None",
")",
":",
"hints",
"=",
"'{} slept'",
".",
"format",
"(",
"hints",
")",
"if",
"hints",
"else",
"'slept'",
"st",
"=",
"time",
".",... | wrap random sleep.
- log it for debug purpose only | [
"wrap",
"random",
"sleep",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/prettify.py#L93-L102 |
klorenz/python-argdeco | argdeco/config.py | config_factory | def config_factory(ConfigClass=dict, prefix=None,
config_file=None
):
'''return a class, which implements the compiler_factory API
:param ConfigClass:
defaults to dict. A simple factory (without parameter) for a
dictionary-like object, which implements __setitem__() method.
Ad... | python | def config_factory(ConfigClass=dict, prefix=None,
config_file=None
):
'''return a class, which implements the compiler_factory API
:param ConfigClass:
defaults to dict. A simple factory (without parameter) for a
dictionary-like object, which implements __setitem__() method.
Ad... | [
"def",
"config_factory",
"(",
"ConfigClass",
"=",
"dict",
",",
"prefix",
"=",
"None",
",",
"config_file",
"=",
"None",
")",
":",
"config_factory",
"=",
"ConfigClass",
"class",
"ConfigFactory",
":",
"def",
"__init__",
"(",
"self",
",",
"command",
")",
":",
... | return a class, which implements the compiler_factory API
:param ConfigClass:
defaults to dict. A simple factory (without parameter) for a
dictionary-like object, which implements __setitem__() method.
Additionally you can implement following methods:
:``init_args``: A method to ... | [
"return",
"a",
"class",
"which",
"implements",
"the",
"compiler_factory",
"API"
] | train | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/config.py#L167-L277 |
klorenz/python-argdeco | argdeco/config.py | ConfigDict.flatten | def flatten(self, D):
'''flatten a nested dictionary D to a flat dictionary
nested keys are separated by '.'
'''
if not isinstance(D, dict):
return D
result = {}
for k,v in D.items():
if isinstance(v, dict):
for _k,_v in self.fla... | python | def flatten(self, D):
'''flatten a nested dictionary D to a flat dictionary
nested keys are separated by '.'
'''
if not isinstance(D, dict):
return D
result = {}
for k,v in D.items():
if isinstance(v, dict):
for _k,_v in self.fla... | [
"def",
"flatten",
"(",
"self",
",",
"D",
")",
":",
"if",
"not",
"isinstance",
"(",
"D",
",",
"dict",
")",
":",
"return",
"D",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"D",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",... | flatten a nested dictionary D to a flat dictionary
nested keys are separated by '.' | [
"flatten",
"a",
"nested",
"dictionary",
"D",
"to",
"a",
"flat",
"dictionary"
] | train | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/config.py#L115-L131 |
klorenz/python-argdeco | argdeco/config.py | ConfigDict.update | def update(self, E=None, **F):
'''flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
... | python | def update(self, E=None, **F):
'''flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
... | [
"def",
"update",
"(",
"self",
",",
"E",
"=",
"None",
",",
"*",
"*",
"F",
")",
":",
"def",
"_update",
"(",
"D",
")",
":",
"for",
"k",
",",
"v",
"in",
"D",
".",
"items",
"(",
")",
":",
"if",
"super",
"(",
"ConfigDict",
",",
"self",
")",
".",
... | flatten nested dictionaries to update pathwise
>>> Config({'foo': {'bar': 'glork'}}).update({'foo': {'blub': 'bla'}})
{'foo': {'bar': 'glork', 'blub': 'bla'}
In contrast to:
>>> {'foo': {'bar': 'glork'}}.update({'foo': {'blub': 'bla'}})
{'foo: {'blub': 'bla'}'} | [
"flatten",
"nested",
"dictionaries",
"to",
"update",
"pathwise"
] | train | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/config.py#L134-L163 |
redodo/formats | formats/helpers.py | discover_json | def discover_json(bank=None, **meta):
"""Discovers the JSON format and registers it if available.
To speed up JSON parsing and composing, install `simplejson`::
pip install simplejson
The standard library module `json` will be used by default.
:param bank: The format bank to register the for... | python | def discover_json(bank=None, **meta):
"""Discovers the JSON format and registers it if available.
To speed up JSON parsing and composing, install `simplejson`::
pip install simplejson
The standard library module `json` will be used by default.
:param bank: The format bank to register the for... | [
"def",
"discover_json",
"(",
"bank",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"try",
":",
"import",
"simplejson",
"as",
"json",
"except",
"ImportError",
":",
"import",
"json",
"if",
"bank",
"is",
"None",
":",
"bank",
"=",
"default_bank",
"bank",
"... | Discovers the JSON format and registers it if available.
To speed up JSON parsing and composing, install `simplejson`::
pip install simplejson
The standard library module `json` will be used by default.
:param bank: The format bank to register the format in
:param meta: Extra information ass... | [
"Discovers",
"the",
"JSON",
"format",
"and",
"registers",
"it",
"if",
"available",
"."
] | train | https://github.com/redodo/formats/blob/5bc7a79a2c93ef895534edbbf83f1efe2f62e081/formats/helpers.py#L7-L25 |
redodo/formats | formats/helpers.py | discover_yaml | def discover_yaml(bank=None, **meta):
"""Discovers the YAML format and registers it if available.
Install YAML support via PIP::
pip install PyYAML
:param bank: The format bank to register the format in
:param meta: Extra information associated with the format
"""
try:
import ... | python | def discover_yaml(bank=None, **meta):
"""Discovers the YAML format and registers it if available.
Install YAML support via PIP::
pip install PyYAML
:param bank: The format bank to register the format in
:param meta: Extra information associated with the format
"""
try:
import ... | [
"def",
"discover_yaml",
"(",
"bank",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"try",
":",
"import",
"yaml",
"if",
"bank",
"is",
"None",
":",
"bank",
"=",
"default_bank",
"bank",
".",
"register",
"(",
"'yaml'",
",",
"yaml",
".",
"load",
",",
"y... | Discovers the YAML format and registers it if available.
Install YAML support via PIP::
pip install PyYAML
:param bank: The format bank to register the format in
:param meta: Extra information associated with the format | [
"Discovers",
"the",
"YAML",
"format",
"and",
"registers",
"it",
"if",
"available",
"."
] | train | https://github.com/redodo/formats/blob/5bc7a79a2c93ef895534edbbf83f1efe2f62e081/formats/helpers.py#L28-L44 |
roaet/wafflehaus.neutron | wafflehaus/neutron/shared_network/trusted.py | filter_factory | def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def trusted_shared_nets(app):
return TrustedSharedNetwork(app, conf)
return trusted_shared_nets | python | def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def trusted_shared_nets(app):
return TrustedSharedNetwork(app, conf)
return trusted_shared_nets | [
"def",
"filter_factory",
"(",
"global_conf",
",",
"*",
"*",
"local_conf",
")",
":",
"conf",
"=",
"global_conf",
".",
"copy",
"(",
")",
"conf",
".",
"update",
"(",
"local_conf",
")",
"def",
"trusted_shared_nets",
"(",
"app",
")",
":",
"return",
"TrustedShar... | Returns a WSGI filter app for use with paste.deploy. | [
"Returns",
"a",
"WSGI",
"filter",
"app",
"for",
"use",
"with",
"paste",
".",
"deploy",
"."
] | train | https://github.com/roaet/wafflehaus.neutron/blob/01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c/wafflehaus/neutron/shared_network/trusted.py#L104-L111 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | import_legislators | def import_legislators(src):
"""
Read the legislators from the csv files into a single Dataframe. Intended
for importing new data.
"""
logger.info("Importing Legislators From: {0}".format(src))
current = pd.read_csv("{0}/{1}/legislators-current.csv".format(
src, LEGISLATOR_DIR))
hist... | python | def import_legislators(src):
"""
Read the legislators from the csv files into a single Dataframe. Intended
for importing new data.
"""
logger.info("Importing Legislators From: {0}".format(src))
current = pd.read_csv("{0}/{1}/legislators-current.csv".format(
src, LEGISLATOR_DIR))
hist... | [
"def",
"import_legislators",
"(",
"src",
")",
":",
"logger",
".",
"info",
"(",
"\"Importing Legislators From: {0}\"",
".",
"format",
"(",
"src",
")",
")",
"current",
"=",
"pd",
".",
"read_csv",
"(",
"\"{0}/{1}/legislators-current.csv\"",
".",
"format",
"(",
"src... | Read the legislators from the csv files into a single Dataframe. Intended
for importing new data. | [
"Read",
"the",
"legislators",
"from",
"the",
"csv",
"files",
"into",
"a",
"single",
"Dataframe",
".",
"Intended",
"for",
"importing",
"new",
"data",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L38-L50 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | save_legislators | def save_legislators(legislators, destination):
"""
Output legislators datafrom to csv.
"""
logger.info("Saving Legislators To: {0}".format(destination))
legislators.to_csv("{0}/legislators.csv".format(destination),
encoding='utf-8') | python | def save_legislators(legislators, destination):
"""
Output legislators datafrom to csv.
"""
logger.info("Saving Legislators To: {0}".format(destination))
legislators.to_csv("{0}/legislators.csv".format(destination),
encoding='utf-8') | [
"def",
"save_legislators",
"(",
"legislators",
",",
"destination",
")",
":",
"logger",
".",
"info",
"(",
"\"Saving Legislators To: {0}\"",
".",
"format",
"(",
"destination",
")",
")",
"legislators",
".",
"to_csv",
"(",
"\"{0}/legislators.csv\"",
".",
"format",
"("... | Output legislators datafrom to csv. | [
"Output",
"legislators",
"datafrom",
"to",
"csv",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L53-L59 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | import_committees | def import_committees(src):
"""
Read the committees from the csv files into a single Dataframe. Intended for importing new data.
"""
committees = []
subcommittees = []
with open("{0}/{1}/committees-current.yaml".format(src, LEGISLATOR_DIR),
'r') as stream:
committees += ya... | python | def import_committees(src):
"""
Read the committees from the csv files into a single Dataframe. Intended for importing new data.
"""
committees = []
subcommittees = []
with open("{0}/{1}/committees-current.yaml".format(src, LEGISLATOR_DIR),
'r') as stream:
committees += ya... | [
"def",
"import_committees",
"(",
"src",
")",
":",
"committees",
"=",
"[",
"]",
"subcommittees",
"=",
"[",
"]",
"with",
"open",
"(",
"\"{0}/{1}/committees-current.yaml\"",
".",
"format",
"(",
"src",
",",
"LEGISLATOR_DIR",
")",
",",
"'r'",
")",
"as",
"stream",... | Read the committees from the csv files into a single Dataframe. Intended for importing new data. | [
"Read",
"the",
"committees",
"from",
"the",
"csv",
"files",
"into",
"a",
"single",
"Dataframe",
".",
"Intended",
"for",
"importing",
"new",
"data",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L73-L108 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | move_committees | def move_committees(src, dest):
"""
Import stupid yaml files, convert to something useful.
"""
comm, sub_comm = import_committees(src)
save_committees(comm, dest)
save_subcommittees(comm, dest) | python | def move_committees(src, dest):
"""
Import stupid yaml files, convert to something useful.
"""
comm, sub_comm = import_committees(src)
save_committees(comm, dest)
save_subcommittees(comm, dest) | [
"def",
"move_committees",
"(",
"src",
",",
"dest",
")",
":",
"comm",
",",
"sub_comm",
"=",
"import_committees",
"(",
"src",
")",
"save_committees",
"(",
"comm",
",",
"dest",
")",
"save_subcommittees",
"(",
"comm",
",",
"dest",
")"
] | Import stupid yaml files, convert to something useful. | [
"Import",
"stupid",
"yaml",
"files",
"convert",
"to",
"something",
"useful",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L126-L132 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | make_congress_dir | def make_congress_dir(congress, dest):
"""
If the directory for a given congress does not exist. Make it.
"""
congress_dir = "{0}/{1}".format(dest, congress)
path = os.path.dirname(congress_dir)
logger.debug("CSV DIR: {}".format(path))
if not os.path.exists(congress_dir):
logger.inf... | python | def make_congress_dir(congress, dest):
"""
If the directory for a given congress does not exist. Make it.
"""
congress_dir = "{0}/{1}".format(dest, congress)
path = os.path.dirname(congress_dir)
logger.debug("CSV DIR: {}".format(path))
if not os.path.exists(congress_dir):
logger.inf... | [
"def",
"make_congress_dir",
"(",
"congress",
",",
"dest",
")",
":",
"congress_dir",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"dest",
",",
"congress",
")",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"congress_dir",
")",
"logger",
".",
"debug",
"(... | If the directory for a given congress does not exist. Make it. | [
"If",
"the",
"directory",
"for",
"a",
"given",
"congress",
"does",
"not",
"exist",
".",
"Make",
"it",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L135-L146 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | save_congress | def save_congress(congress, dest):
"""
Takes a congress object with legislation, sponser, cosponsor, commities
and subjects attributes and saves each item to it's own csv file.
"""
try:
logger.debug(congress.name)
logger.debug(dest)
congress_dir = make_congress_dir(congress.n... | python | def save_congress(congress, dest):
"""
Takes a congress object with legislation, sponser, cosponsor, commities
and subjects attributes and saves each item to it's own csv file.
"""
try:
logger.debug(congress.name)
logger.debug(dest)
congress_dir = make_congress_dir(congress.n... | [
"def",
"save_congress",
"(",
"congress",
",",
"dest",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"congress",
".",
"name",
")",
"logger",
".",
"debug",
"(",
"dest",
")",
"congress_dir",
"=",
"make_congress_dir",
"(",
"congress",
".",
"name",
",",
... | Takes a congress object with legislation, sponser, cosponsor, commities
and subjects attributes and saves each item to it's own csv file. | [
"Takes",
"a",
"congress",
"object",
"with",
"legislation",
"sponser",
"cosponsor",
"commities",
"and",
"subjects",
"attributes",
"and",
"saves",
"each",
"item",
"to",
"it",
"s",
"own",
"csv",
"file",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L158-L195 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_legislation | def extract_legislation(bill):
"""
Returns a list of the legislation fields we need for our legislation DataFrame
:param bill:
:return list:
"""
record = []
record.append(bill.get('congress', None))
record.append(bill.get('bill_id', None))
record.append(bill.get('bill_type', None))
... | python | def extract_legislation(bill):
"""
Returns a list of the legislation fields we need for our legislation DataFrame
:param bill:
:return list:
"""
record = []
record.append(bill.get('congress', None))
record.append(bill.get('bill_id', None))
record.append(bill.get('bill_type', None))
... | [
"def",
"extract_legislation",
"(",
"bill",
")",
":",
"record",
"=",
"[",
"]",
"record",
".",
"append",
"(",
"bill",
".",
"get",
"(",
"'congress'",
",",
"None",
")",
")",
"record",
".",
"append",
"(",
"bill",
".",
"get",
"(",
"'bill_id'",
",",
"None",... | Returns a list of the legislation fields we need for our legislation DataFrame
:param bill:
:return list: | [
"Returns",
"a",
"list",
"of",
"the",
"legislation",
"fields",
"we",
"need",
"for",
"our",
"legislation",
"DataFrame",
":",
"param",
"bill",
":",
":",
"return",
"list",
":"
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L223-L243 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_sponsor | def extract_sponsor(bill):
"""
Return a list of the fields we need to map a sponser to a bill
"""
logger.debug("Extracting Sponsor")
sponsor_map = []
sponsor = bill.get('sponsor', None)
if sponsor:
sponsor_map.append(sponsor.get('type'))
sponsor_map.append(sponsor.get('thomas... | python | def extract_sponsor(bill):
"""
Return a list of the fields we need to map a sponser to a bill
"""
logger.debug("Extracting Sponsor")
sponsor_map = []
sponsor = bill.get('sponsor', None)
if sponsor:
sponsor_map.append(sponsor.get('type'))
sponsor_map.append(sponsor.get('thomas... | [
"def",
"extract_sponsor",
"(",
"bill",
")",
":",
"logger",
".",
"debug",
"(",
"\"Extracting Sponsor\"",
")",
"sponsor_map",
"=",
"[",
"]",
"sponsor",
"=",
"bill",
".",
"get",
"(",
"'sponsor'",
",",
"None",
")",
"if",
"sponsor",
":",
"sponsor_map",
".",
"... | Return a list of the fields we need to map a sponser to a bill | [
"Return",
"a",
"list",
"of",
"the",
"fields",
"we",
"need",
"to",
"map",
"a",
"sponser",
"to",
"a",
"bill"
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L246-L260 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_cosponsors | def extract_cosponsors(bill):
"""
Return a list of list relating cosponsors to legislation.
"""
logger.debug("Extracting Cosponsors")
cosponsor_map = []
cosponsors = bill.get('cosponsors', [])
bill_id = bill.get('bill_id', None)
for co in cosponsors:
co_list = []
co_list... | python | def extract_cosponsors(bill):
"""
Return a list of list relating cosponsors to legislation.
"""
logger.debug("Extracting Cosponsors")
cosponsor_map = []
cosponsors = bill.get('cosponsors', [])
bill_id = bill.get('bill_id', None)
for co in cosponsors:
co_list = []
co_list... | [
"def",
"extract_cosponsors",
"(",
"bill",
")",
":",
"logger",
".",
"debug",
"(",
"\"Extracting Cosponsors\"",
")",
"cosponsor_map",
"=",
"[",
"]",
"cosponsors",
"=",
"bill",
".",
"get",
"(",
"'cosponsors'",
",",
"[",
"]",
")",
"bill_id",
"=",
"bill",
".",
... | Return a list of list relating cosponsors to legislation. | [
"Return",
"a",
"list",
"of",
"list",
"relating",
"cosponsors",
"to",
"legislation",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L263-L282 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_subjects | def extract_subjects(bill):
"""
Return a list subject for legislation.
"""
logger.debug("Extracting Subjects")
subject_map = []
subjects = bill.get('subjects', [])
bill_id = bill.get('bill_id', None)
bill_type = bill.get('bill_type', None)
for sub in subjects:
subject_map.ap... | python | def extract_subjects(bill):
"""
Return a list subject for legislation.
"""
logger.debug("Extracting Subjects")
subject_map = []
subjects = bill.get('subjects', [])
bill_id = bill.get('bill_id', None)
bill_type = bill.get('bill_type', None)
for sub in subjects:
subject_map.ap... | [
"def",
"extract_subjects",
"(",
"bill",
")",
":",
"logger",
".",
"debug",
"(",
"\"Extracting Subjects\"",
")",
"subject_map",
"=",
"[",
"]",
"subjects",
"=",
"bill",
".",
"get",
"(",
"'subjects'",
",",
"[",
"]",
")",
"bill_id",
"=",
"bill",
".",
"get",
... | Return a list subject for legislation. | [
"Return",
"a",
"list",
"subject",
"for",
"legislation",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L285-L300 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_committees | def extract_committees(bill):
"""
Returns committee associations from a bill.
"""
bill_id = bill.get('bill_id', None)
logger.debug("Extracting Committees for {0}".format(bill_id))
committees = bill.get('committees', None)
committee_map = []
for c in committees:
logger.debug("Pr... | python | def extract_committees(bill):
"""
Returns committee associations from a bill.
"""
bill_id = bill.get('bill_id', None)
logger.debug("Extracting Committees for {0}".format(bill_id))
committees = bill.get('committees', None)
committee_map = []
for c in committees:
logger.debug("Pr... | [
"def",
"extract_committees",
"(",
"bill",
")",
":",
"bill_id",
"=",
"bill",
".",
"get",
"(",
"'bill_id'",
",",
"None",
")",
"logger",
".",
"debug",
"(",
"\"Extracting Committees for {0}\"",
".",
"format",
"(",
"bill_id",
")",
")",
"committees",
"=",
"bill",
... | Returns committee associations from a bill. | [
"Returns",
"committee",
"associations",
"from",
"a",
"bill",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L303-L331 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | extract_events | def extract_events(bill):
"""
Returns all events from legislation. Thing of this as a log for congress.
There are alot of events that occur around legislation. For now we are
going to kepe it simple. Introduction, cosponsor, votes dates
"""
events = []
#logger.debug(events)
bill_id = bi... | python | def extract_events(bill):
"""
Returns all events from legislation. Thing of this as a log for congress.
There are alot of events that occur around legislation. For now we are
going to kepe it simple. Introduction, cosponsor, votes dates
"""
events = []
#logger.debug(events)
bill_id = bi... | [
"def",
"extract_events",
"(",
"bill",
")",
":",
"events",
"=",
"[",
"]",
"#logger.debug(events)",
"bill_id",
"=",
"bill",
".",
"get",
"(",
"'bill_id'",
",",
"None",
")",
"if",
"bill_id",
":",
"for",
"event",
"in",
"bill",
".",
"get",
"(",
"'actions'",
... | Returns all events from legislation. Thing of this as a log for congress.
There are alot of events that occur around legislation. For now we are
going to kepe it simple. Introduction, cosponsor, votes dates | [
"Returns",
"all",
"events",
"from",
"legislation",
".",
"Thing",
"of",
"this",
"as",
"a",
"log",
"for",
"congress",
".",
"There",
"are",
"alot",
"of",
"events",
"that",
"occur",
"around",
"legislation",
".",
"For",
"now",
"we",
"are",
"going",
"to",
"kep... | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L335-L367 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | process_amendments | def process_amendments(congress):
"""
Traverse amendments for a project
"""
amend_dir = "{0}/{1}/amendments".format(congress['src'],
congress['congress'])
logger.info("Processing Amendments for {0}".format(congress['congress']))
amendments = []
f... | python | def process_amendments(congress):
"""
Traverse amendments for a project
"""
amend_dir = "{0}/{1}/amendments".format(congress['src'],
congress['congress'])
logger.info("Processing Amendments for {0}".format(congress['congress']))
amendments = []
f... | [
"def",
"process_amendments",
"(",
"congress",
")",
":",
"amend_dir",
"=",
"\"{0}/{1}/amendments\"",
".",
"format",
"(",
"congress",
"[",
"'src'",
"]",
",",
"congress",
"[",
"'congress'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Processing Amendments for {0}\"",
... | Traverse amendments for a project | [
"Traverse",
"amendments",
"for",
"a",
"project"
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L414-L461 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | lis_to_bio_map | def lis_to_bio_map(folder):
"""
Senators have a lis_id that is used in some places. That's dumb. Build a
dict from lis_id to bioguide_id which every member of congress has.
"""
logger.info("Opening legislator csv for lis_dct creation")
lis_dic = {}
leg_path = "{0}/legislators.csv".format(fol... | python | def lis_to_bio_map(folder):
"""
Senators have a lis_id that is used in some places. That's dumb. Build a
dict from lis_id to bioguide_id which every member of congress has.
"""
logger.info("Opening legislator csv for lis_dct creation")
lis_dic = {}
leg_path = "{0}/legislators.csv".format(fol... | [
"def",
"lis_to_bio_map",
"(",
"folder",
")",
":",
"logger",
".",
"info",
"(",
"\"Opening legislator csv for lis_dct creation\"",
")",
"lis_dic",
"=",
"{",
"}",
"leg_path",
"=",
"\"{0}/legislators.csv\"",
".",
"format",
"(",
"folder",
")",
"logger",
".",
"info",
... | Senators have a lis_id that is used in some places. That's dumb. Build a
dict from lis_id to bioguide_id which every member of congress has. | [
"Senators",
"have",
"a",
"lis_id",
"that",
"is",
"used",
"in",
"some",
"places",
".",
"That",
"s",
"dumb",
".",
"Build",
"a",
"dict",
"from",
"lis_id",
"to",
"bioguide_id",
"which",
"every",
"member",
"of",
"congress",
"has",
"."
] | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L580-L594 |
hackthefed/govtrack2csv | govtrack2csv/__init__.py | convert_congress | def convert_congress(congress):
"""
Recurse the passed govtrack congress directory and convert it's contents
to a set of csv files from the legislation contained therein.
:return dict: A Dictionary of DataFrames
"""
logger.info("Begin processing Congress {0}".format(congress['congress']))
... | python | def convert_congress(congress):
"""
Recurse the passed govtrack congress directory and convert it's contents
to a set of csv files from the legislation contained therein.
:return dict: A Dictionary of DataFrames
"""
logger.info("Begin processing Congress {0}".format(congress['congress']))
... | [
"def",
"convert_congress",
"(",
"congress",
")",
":",
"logger",
".",
"info",
"(",
"\"Begin processing Congress {0}\"",
".",
"format",
"(",
"congress",
"[",
"'congress'",
"]",
")",
")",
"congress_obj",
"=",
"Congress",
"(",
"congress",
")",
"lis_to_bio",
"=",
"... | Recurse the passed govtrack congress directory and convert it's contents
to a set of csv files from the legislation contained therein.
:return dict: A Dictionary of DataFrames | [
"Recurse",
"the",
"passed",
"govtrack",
"congress",
"directory",
"and",
"convert",
"it",
"s",
"contents",
"to",
"a",
"set",
"of",
"csv",
"files",
"from",
"the",
"legislation",
"contained",
"therein",
".",
":",
"return",
"dict",
":",
"A",
"Dictionary",
"of",
... | train | https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L597-L697 |
svetlyak40wt/twiggy-goodies | twiggy_goodies/std_logging.py | RedirectLoggingHandler.convert_level | def convert_level(self, record):
"""Converts a logging level into a logbook level."""
level = record.levelno
if level >= logging.CRITICAL:
return levels.CRITICAL
if level >= logging.ERROR:
return levels.ERROR
if level >= logging.WARNING:
return... | python | def convert_level(self, record):
"""Converts a logging level into a logbook level."""
level = record.levelno
if level >= logging.CRITICAL:
return levels.CRITICAL
if level >= logging.ERROR:
return levels.ERROR
if level >= logging.WARNING:
return... | [
"def",
"convert_level",
"(",
"self",
",",
"record",
")",
":",
"level",
"=",
"record",
".",
"levelno",
"if",
"level",
">=",
"logging",
".",
"CRITICAL",
":",
"return",
"levels",
".",
"CRITICAL",
"if",
"level",
">=",
"logging",
".",
"ERROR",
":",
"return",
... | Converts a logging level into a logbook level. | [
"Converts",
"a",
"logging",
"level",
"into",
"a",
"logbook",
"level",
"."
] | train | https://github.com/svetlyak40wt/twiggy-goodies/blob/71528d5959fab81eb8d0e4373f20d37a013ac00e/twiggy_goodies/std_logging.py#L19-L30 |
svetlyak40wt/twiggy-goodies | twiggy_goodies/std_logging.py | RedirectLoggingHandler.find_extra | def find_extra(self, record):
"""Tries to find custom data from the old logging record. The
return value is a dictionary that is merged with the log record
extra dictionaries.
"""
rv = vars(record).copy()
for key in ('name', 'msg', 'args', 'levelname', 'levelno',
... | python | def find_extra(self, record):
"""Tries to find custom data from the old logging record. The
return value is a dictionary that is merged with the log record
extra dictionaries.
"""
rv = vars(record).copy()
for key in ('name', 'msg', 'args', 'levelname', 'levelno',
... | [
"def",
"find_extra",
"(",
"self",
",",
"record",
")",
":",
"rv",
"=",
"vars",
"(",
"record",
")",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"(",
"'name'",
",",
"'msg'",
",",
"'args'",
",",
"'levelname'",
",",
"'levelno'",
",",
"'pathname'",
",",
"... | Tries to find custom data from the old logging record. The
return value is a dictionary that is merged with the log record
extra dictionaries. | [
"Tries",
"to",
"find",
"custom",
"data",
"from",
"the",
"old",
"logging",
"record",
".",
"The",
"return",
"value",
"is",
"a",
"dictionary",
"that",
"is",
"merged",
"with",
"the",
"log",
"record",
"extra",
"dictionaries",
"."
] | train | https://github.com/svetlyak40wt/twiggy-goodies/blob/71528d5959fab81eb8d0e4373f20d37a013ac00e/twiggy_goodies/std_logging.py#L32-L44 |
abe-winter/pg13-py | setup.py | get_version | def get_version(fname):
"grab __version__ variable from fname (assuming fname is a python file). parses without importing."
assign_stmts = [s for s in ast.parse(open(fname).read()).body if isinstance(s,ast.Assign)]
valid_targets = [s for s in assign_stmts if len(s.targets) == 1 and s.targets[0].id == '__versio... | python | def get_version(fname):
"grab __version__ variable from fname (assuming fname is a python file). parses without importing."
assign_stmts = [s for s in ast.parse(open(fname).read()).body if isinstance(s,ast.Assign)]
valid_targets = [s for s in assign_stmts if len(s.targets) == 1 and s.targets[0].id == '__versio... | [
"def",
"get_version",
"(",
"fname",
")",
":",
"assign_stmts",
"=",
"[",
"s",
"for",
"s",
"in",
"ast",
".",
"parse",
"(",
"open",
"(",
"fname",
")",
".",
"read",
"(",
")",
")",
".",
"body",
"if",
"isinstance",
"(",
"s",
",",
"ast",
".",
"Assign",
... | grab __version__ variable from fname (assuming fname is a python file). parses without importing. | [
"grab",
"__version__",
"variable",
"from",
"fname",
"(",
"assuming",
"fname",
"is",
"a",
"python",
"file",
")",
".",
"parses",
"without",
"importing",
"."
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/setup.py#L3-L7 |
openpermissions/perch | perch/views.py | view | def view(db_name):
"""
Register a map function as a view
Currently, only a single map function can be created for each view
NOTE: the map function source is saved in CouchDB, so it cannot depend on
anything outside the function's scope.
:param db_name: the database name
"""
def decora... | python | def view(db_name):
"""
Register a map function as a view
Currently, only a single map function can be created for each view
NOTE: the map function source is saved in CouchDB, so it cannot depend on
anything outside the function's scope.
:param db_name: the database name
"""
def decora... | [
"def",
"view",
"(",
"db_name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"v",
"=",
"View",
"(",
"db_name",
",",
"func",
")",
"v",
".",
"register",
"(",
")",
"return",
"v",
"return",
"decorator"
] | Register a map function as a view
Currently, only a single map function can be created for each view
NOTE: the map function source is saved in CouchDB, so it cannot depend on
anything outside the function's scope.
:param db_name: the database name | [
"Register",
"a",
"map",
"function",
"as",
"a",
"view"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L107-L122 |
openpermissions/perch | perch/views.py | load_design_docs | def load_design_docs():
"""
Load design docs for registered views
"""
url = ':'.join([options.url_registry_db, str(options.db_port)])
client = partial(couch.BlockingCouch, couch_url=url)
for name, docs in _views.items():
db = client(db_name=name)
views = []
for doc in d... | python | def load_design_docs():
"""
Load design docs for registered views
"""
url = ':'.join([options.url_registry_db, str(options.db_port)])
client = partial(couch.BlockingCouch, couch_url=url)
for name, docs in _views.items():
db = client(db_name=name)
views = []
for doc in d... | [
"def",
"load_design_docs",
"(",
")",
":",
"url",
"=",
"':'",
".",
"join",
"(",
"[",
"options",
".",
"url_registry_db",
",",
"str",
"(",
"options",
".",
"db_port",
")",
"]",
")",
"client",
"=",
"partial",
"(",
"couch",
".",
"BlockingCouch",
",",
"couch_... | Load design docs for registered views | [
"Load",
"design",
"docs",
"for",
"registered",
"views"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L125-L148 |
openpermissions/perch | perch/views.py | active_user_organisations_resource | def active_user_organisations_resource(doc):
"""Get user.organisations subresouces"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
for org_id, resource in doc.get('organisations', {}).items():
if resource['state'] != 'deactivated':
resource['id'] = org_... | python | def active_user_organisations_resource(doc):
"""Get user.organisations subresouces"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
for org_id, resource in doc.get('organisations', {}).items():
if resource['state'] != 'deactivated':
resource['id'] = org_... | [
"def",
"active_user_organisations_resource",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"org_id",
",",
"resource",
"in",
"doc",
".",... | Get user.organisations subresouces | [
"Get",
"user",
".",
"organisations",
"subresouces"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L172-L179 |
openpermissions/perch | perch/views.py | user_organisations_resource | def user_organisations_resource(doc):
"""Get user.organisations subresouces"""
if doc.get('type') == 'user':
for org_id, resource in doc.get('organisations', {}).items():
resource['id'] = org_id
resource['user_id'] = doc['_id']
yield [doc['_id'], org_id], resource | python | def user_organisations_resource(doc):
"""Get user.organisations subresouces"""
if doc.get('type') == 'user':
for org_id, resource in doc.get('organisations', {}).items():
resource['id'] = org_id
resource['user_id'] = doc['_id']
yield [doc['_id'], org_id], resource | [
"def",
"user_organisations_resource",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
":",
"for",
"org_id",
",",
"resource",
"in",
"doc",
".",
"get",
"(",
"'organisations'",
",",
"{",
"}",
")",
".",
"items",
"(",
")... | Get user.organisations subresouces | [
"Get",
"user",
".",
"organisations",
"subresouces"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L183-L189 |
openpermissions/perch | perch/views.py | active_joined_organisations | def active_joined_organisations(doc):
"""View for getting organisations associated with a user"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
for org_id, state in doc.get('organisations', {}).items():
if state['state'] == 'deactivated':
continue
... | python | def active_joined_organisations(doc):
"""View for getting organisations associated with a user"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
for org_id, state in doc.get('organisations', {}).items():
if state['state'] == 'deactivated':
continue
... | [
"def",
"active_joined_organisations",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"org_id",
",",
"state",
"in",
"doc",
".",
"get",
... | View for getting organisations associated with a user | [
"View",
"for",
"getting",
"organisations",
"associated",
"with",
"a",
"user"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L193-L206 |
openpermissions/perch | perch/views.py | joined_organisations | def joined_organisations(doc):
"""View for getting organisations associated with a user"""
if doc.get('type') == 'user':
for org_id, state in doc.get('organisations', {}).items():
org = {'_id': org_id}
yield [doc['_id'], None], org
try:
yield [doc['_i... | python | def joined_organisations(doc):
"""View for getting organisations associated with a user"""
if doc.get('type') == 'user':
for org_id, state in doc.get('organisations', {}).items():
org = {'_id': org_id}
yield [doc['_id'], None], org
try:
yield [doc['_i... | [
"def",
"joined_organisations",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
":",
"for",
"org_id",
",",
"state",
"in",
"doc",
".",
"get",
"(",
"'organisations'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
... | View for getting organisations associated with a user | [
"View",
"for",
"getting",
"organisations",
"associated",
"with",
"a",
"user"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L210-L220 |
openpermissions/perch | perch/views.py | admin_emails | def admin_emails(doc):
"""View for admin email addresses (organisation and global)"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
if doc.get('role') == 'administrator':
yield None, doc['email']
for org_id, state in doc.get('organisations', {}).items():
... | python | def admin_emails(doc):
"""View for admin email addresses (organisation and global)"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
if doc.get('role') == 'administrator':
yield None, doc['email']
for org_id, state in doc.get('organisations', {}).items():
... | [
"def",
"admin_emails",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"if",
"doc",
".",
"get",
"(",
"'role'",
")",
"==",
"'administrator'",... | View for admin email addresses (organisation and global) | [
"View",
"for",
"admin",
"email",
"addresses",
"(",
"organisation",
"and",
"global",
")"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L232-L239 |
openpermissions/perch | perch/views.py | reference_links | def reference_links(doc):
"""Get reference links"""
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for asset_id_type, link in doc.get('reference_links', {}).get('links', {}).items():
value = {
'organisation_id': doc['_id'],
'link':... | python | def reference_links(doc):
"""Get reference links"""
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for asset_id_type, link in doc.get('reference_links', {}).get('links', {}).items():
value = {
'organisation_id': doc['_id'],
'link':... | [
"def",
"reference_links",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'organisation'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"asset_id_type",
",",
"link",
"in",
"doc",
".",
"get"... | Get reference links | [
"Get",
"reference",
"links"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L264-L272 |
openpermissions/perch | perch/views.py | active_services | def active_services(doc):
"""View for getting active services"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service_type = service.get('service_type')
org = doc['_... | python | def active_services(doc):
"""View for getting active services"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service_type = service.get('service_type')
org = doc['_... | [
"def",
"active_services",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"service_id",
",",
"service",
"in",
"doc",
".",
"get",
"(",
"'services'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
"... | View for getting active services | [
"View",
"for",
"getting",
"active",
"services"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L276-L290 |
openpermissions/perch | perch/views.py | services | def services(doc):
"""View for getting services"""
for service_id, service in doc.get('services', {}).items():
service_type = service.get('service_type')
org = doc['_id']
service['id'] = service_id
service['organisation_id'] = org
yield service_id, service
yield ... | python | def services(doc):
"""View for getting services"""
for service_id, service in doc.get('services', {}).items():
service_type = service.get('service_type')
org = doc['_id']
service['id'] = service_id
service['organisation_id'] = org
yield service_id, service
yield ... | [
"def",
"services",
"(",
"doc",
")",
":",
"for",
"service_id",
",",
"service",
"in",
"doc",
".",
"get",
"(",
"'services'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"service_type",
"=",
"service",
".",
"get",
"(",
"'service_type'",
")",
"org",
... | View for getting services | [
"View",
"for",
"getting",
"services"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L294-L306 |
openpermissions/perch | perch/views.py | active_service_location | def active_service_location(doc):
"""View for getting active service by location"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service['id'] = service_id
service['... | python | def active_service_location(doc):
"""View for getting active service by location"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service['id'] = service_id
service['... | [
"def",
"active_service_location",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"service_id",
",",
"service",
"in",
"doc",
".",
"get",
"(",
"'services'",
",",
"{",
"}",
")",
".",
"items",
"(",
... | View for getting active service by location | [
"View",
"for",
"getting",
"active",
"service",
"by",
"location"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L310-L320 |
openpermissions/perch | perch/views.py | service_location | def service_location(doc):
"""View for getting service by location"""
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
location = service.get('location', None)
if location:
yield location, ... | python | def service_location(doc):
"""View for getting service by location"""
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
location = service.get('location', None)
if location:
yield location, ... | [
"def",
"service_location",
"(",
"doc",
")",
":",
"for",
"service_id",
",",
"service",
"in",
"doc",
".",
"get",
"(",
"'services'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"service",
"[",
"'id'",
"]",
"=",
"service_id",
"service",
"[",
"'organ... | View for getting service by location | [
"View",
"for",
"getting",
"service",
"by",
"location"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L324-L332 |
openpermissions/perch | perch/views.py | service_name | def service_name(doc):
"""View for getting service by name"""
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
name = service.get('name', None)
if name:
yield name, service | python | def service_name(doc):
"""View for getting service by name"""
for service_id, service in doc.get('services', {}).items():
service['id'] = service_id
service['organisation_id'] = doc['_id']
name = service.get('name', None)
if name:
yield name, service | [
"def",
"service_name",
"(",
"doc",
")",
":",
"for",
"service_id",
",",
"service",
"in",
"doc",
".",
"get",
"(",
"'services'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"service",
"[",
"'id'",
"]",
"=",
"service_id",
"service",
"[",
"'organisat... | View for getting service by name | [
"View",
"for",
"getting",
"service",
"by",
"name"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L336-L344 |
openpermissions/perch | perch/views.py | active_repositories | def active_repositories(doc):
"""View for getting active repositories"""
if doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('state') != 'deactivated':
repo['id'] = repository_id
repo['organisation_... | python | def active_repositories(doc):
"""View for getting active repositories"""
if doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('state') != 'deactivated':
repo['id'] = repository_id
repo['organisation_... | [
"def",
"active_repositories",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"repository_id",
",",
"repo",
"in",
"doc",
".",
"get",
"(",
"'repositories'",
",",
"{",
"}",
")",
".",
"items",
"(",
... | View for getting active repositories | [
"View",
"for",
"getting",
"active",
"repositories"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L362-L370 |
openpermissions/perch | perch/views.py | repositories | def repositories(doc):
"""View for getting repositories"""
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
yield repository_id, repo | python | def repositories(doc):
"""View for getting repositories"""
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
yield repository_id, repo | [
"def",
"repositories",
"(",
"doc",
")",
":",
"for",
"repository_id",
",",
"repo",
"in",
"doc",
".",
"get",
"(",
"'repositories'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"repo",
"[",
"'id'",
"]",
"=",
"repository_id",
"repo",
"[",
"'organisa... | View for getting repositories | [
"View",
"for",
"getting",
"repositories"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L374-L380 |
openpermissions/perch | perch/views.py | repository_name | def repository_name(doc):
"""View for checking repository name is unique"""
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
name = repo.get('name', None)
if name:
yield name, repository_i... | python | def repository_name(doc):
"""View for checking repository name is unique"""
for repository_id, repo in doc.get('repositories', {}).items():
repo['id'] = repository_id
repo['organisation_id'] = doc['_id']
name = repo.get('name', None)
if name:
yield name, repository_i... | [
"def",
"repository_name",
"(",
"doc",
")",
":",
"for",
"repository_id",
",",
"repo",
"in",
"doc",
".",
"get",
"(",
"'repositories'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"repo",
"[",
"'id'",
"]",
"=",
"repository_id",
"repo",
"[",
"'organ... | View for checking repository name is unique | [
"View",
"for",
"checking",
"repository",
"name",
"is",
"unique"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L384-L392 |
openpermissions/perch | perch/views.py | service_and_repository | def service_and_repository(doc):
"""
View for looking up services and repositories by their ID
Used in the auth service
"""
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('st... | python | def service_and_repository(doc):
"""
View for looking up services and repositories by their ID
Used in the auth service
"""
if doc.get('type') == 'organisation' and doc.get('state') != 'deactivated':
for repository_id, repo in doc.get('repositories', {}).items():
if repo.get('st... | [
"def",
"service_and_repository",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'organisation'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"for",
"repository_id",
",",
"repo",
"in",
"doc",
".",
... | View for looking up services and repositories by their ID
Used in the auth service | [
"View",
"for",
"looking",
"up",
"services",
"and",
"repositories",
"by",
"their",
"ID"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L396-L415 |
openpermissions/perch | perch/views.py | View.create_design_doc | def create_design_doc(self):
"""Create a design document from a Python map function"""
source = [x for x in inspect.getsourcelines(self.func)[0]
if not x.startswith('@')]
doc = {
'_id': '_design/{}'.format(self.name),
'language': 'python',
'... | python | def create_design_doc(self):
"""Create a design document from a Python map function"""
source = [x for x in inspect.getsourcelines(self.func)[0]
if not x.startswith('@')]
doc = {
'_id': '_design/{}'.format(self.name),
'language': 'python',
'... | [
"def",
"create_design_doc",
"(",
"self",
")",
":",
"source",
"=",
"[",
"x",
"for",
"x",
"in",
"inspect",
".",
"getsourcelines",
"(",
"self",
".",
"func",
")",
"[",
"0",
"]",
"if",
"not",
"x",
".",
"startswith",
"(",
"'@'",
")",
"]",
"doc",
"=",
"... | Create a design document from a Python map function | [
"Create",
"a",
"design",
"document",
"from",
"a",
"Python",
"map",
"function"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L50-L65 |
openpermissions/perch | perch/views.py | View.get | def get(self, **kwargs):
"""
Queries database for results of view
:return:
"""
db_url = ':'.join([options.url_registry_db, str(options.db_port)])
db = couch.AsyncCouch(db_name=self.db_name, couch_url=db_url)
result = yield db.view(
design_doc_name=sel... | python | def get(self, **kwargs):
"""
Queries database for results of view
:return:
"""
db_url = ':'.join([options.url_registry_db, str(options.db_port)])
db = couch.AsyncCouch(db_name=self.db_name, couch_url=db_url)
result = yield db.view(
design_doc_name=sel... | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"db_url",
"=",
"':'",
".",
"join",
"(",
"[",
"options",
".",
"url_registry_db",
",",
"str",
"(",
"options",
".",
"db_port",
")",
"]",
")",
"db",
"=",
"couch",
".",
"AsyncCouch",
"(",
"... | Queries database for results of view
:return: | [
"Queries",
"database",
"for",
"results",
"of",
"view",
":",
"return",
":"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L68-L81 |
openpermissions/perch | perch/views.py | View.first | def first(self, **kwargs):
"""
Queries database for first result of view
:return:
"""
result = yield self.get(**kwargs)
if not result['rows']:
raise exceptions.NotFound()
raise Return(result['rows'][0]) | python | def first(self, **kwargs):
"""
Queries database for first result of view
:return:
"""
result = yield self.get(**kwargs)
if not result['rows']:
raise exceptions.NotFound()
raise Return(result['rows'][0]) | [
"def",
"first",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"yield",
"self",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"result",
"[",
"'rows'",
"]",
":",
"raise",
"exceptions",
".",
"NotFound",
"(",
")",
"raise",
"... | Queries database for first result of view
:return: | [
"Queries",
"database",
"for",
"first",
"result",
"of",
"view",
":",
"return",
":"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L84-L94 |
openpermissions/perch | perch/views.py | View.values | def values(self, **kwargs):
"""Get the view's values"""
result = yield self.get(**kwargs)
if not result['rows']:
raise Return([])
raise Return([x['value'] for x in result['rows']]) | python | def values(self, **kwargs):
"""Get the view's values"""
result = yield self.get(**kwargs)
if not result['rows']:
raise Return([])
raise Return([x['value'] for x in result['rows']]) | [
"def",
"values",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"yield",
"self",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"result",
"[",
"'rows'",
"]",
":",
"raise",
"Return",
"(",
"[",
"]",
")",
"raise",
"Return",
... | Get the view's values | [
"Get",
"the",
"view",
"s",
"values"
] | train | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/views.py#L97-L104 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | getScriptArgumentParser | def getScriptArgumentParser(args=sys.argv):
"""Return ArgumentParser object
Kwargs:
args (list): list of arguments that will be parsed. The default
is the sys.argv list, and should be correct for most
use cases.
components (lis... | python | def getScriptArgumentParser(args=sys.argv):
"""Return ArgumentParser object
Kwargs:
args (list): list of arguments that will be parsed. The default
is the sys.argv list, and should be correct for most
use cases.
components (lis... | [
"def",
"getScriptArgumentParser",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"# Description",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
")",
"# source",
"parser",
".",
"add_argument",
"(",
"'config_file'",
","... | Return ArgumentParser object
Kwargs:
args (list): list of arguments that will be parsed. The default
is the sys.argv list, and should be correct for most
use cases.
components (list)
Returns:
ArgumentParser obje... | [
"Return",
"ArgumentParser",
"object",
"Kwargs",
":",
"args",
"(",
"list",
")",
":",
"list",
"of",
"arguments",
"that",
"will",
"be",
"parsed",
".",
"The",
"default",
"is",
"the",
"sys",
".",
"argv",
"list",
"and",
"should",
"be",
"correct",
"for",
"most"... | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L38-L70 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | cache.configure_zca | def configure_zca(cls, cache_config):
"""Configure runtime Zope Component Architecture registry
We need a 3 step process to make sure dependencies are met
1. load static package-based ZCML files....standard stuff here.
2. Register the config into the registry (i.e. make it avail... | python | def configure_zca(cls, cache_config):
"""Configure runtime Zope Component Architecture registry
We need a 3 step process to make sure dependencies are met
1. load static package-based ZCML files....standard stuff here.
2. Register the config into the registry (i.e. make it avail... | [
"def",
"configure_zca",
"(",
"cls",
",",
"cache_config",
")",
":",
"# step 1",
"packages",
"=",
"[",
"sparc",
".",
"apps",
".",
"cache",
"]",
"Configure",
"(",
"packages",
")",
"configure_vocabulary_registry",
"(",
")",
"#step 2",
"config",
"=",
"ElementTree",... | Configure runtime Zope Component Architecture registry
We need a 3 step process to make sure dependencies are met
1. load static package-based ZCML files....standard stuff here.
2. Register the config into the registry (i.e. make it available for
lookup)
3. Manually r... | [
"Configure",
"runtime",
"Zope",
"Component",
"Architecture",
"registry",
"We",
"need",
"a",
"3",
"step",
"process",
"to",
"make",
"sure",
"dependencies",
"are",
"met",
"1",
".",
"load",
"static",
"package",
"-",
"based",
"ZCML",
"files",
"....",
"standard",
... | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L75-L103 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | cache.poller_configurations | def poller_configurations(self):
"""Returns sequence of poller configurations
sequence entry data structure:
{
'cacheablesource': cacheablesource_element,
'cachearea': cachearea_element
}
Returns: sequence of data structure fo... | python | def poller_configurations(self):
"""Returns sequence of poller configurations
sequence entry data structure:
{
'cacheablesource': cacheablesource_element,
'cachearea': cachearea_element
}
Returns: sequence of data structure fo... | [
"def",
"poller_configurations",
"(",
"self",
")",
":",
"configs",
"=",
"[",
"]",
"for",
"cacheablesource",
"in",
"self",
".",
"config",
".",
"findall",
"(",
"'cacheablesource'",
")",
":",
"for",
"cachearea",
"in",
"self",
".",
"config",
".",
"findall",
"("... | Returns sequence of poller configurations
sequence entry data structure:
{
'cacheablesource': cacheablesource_element,
'cachearea': cachearea_element
}
Returns: sequence of data structure for all poller configurations | [
"Returns",
"sequence",
"of",
"poller",
"configurations",
"sequence",
"entry",
"data",
"structure",
":",
"{",
"cacheablesource",
":",
"cacheablesource_element",
"cachearea",
":",
"cachearea_element",
"}",
"Returns",
":",
"sequence",
"of",
"data",
"structure",
"for",
... | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L117-L138 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | cache.create_poller | def create_poller(self, **kwargs):
"""Returns poller data structure
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
Returns: (ICachableSource, ICacheArea, poll)
"""
cache... | python | def create_poller(self, **kwargs):
"""Returns poller data structure
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
Returns: (ICachableSource, ICacheArea, poll)
"""
cache... | [
"def",
"create_poller",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"cacheablesource",
"=",
"createObject",
"(",
"kwargs",
"[",
"'cacheablesource'",
"]",
".",
"attrib",
"[",
"'factory'",
"]",
",",
"kwargs",
"[",
"'cacheablesource'",
"]",
")",
"cachearea"... | Returns poller data structure
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
Returns: (ICachableSource, ICacheArea, poll) | [
"Returns",
"poller",
"data",
"structure",
"Kwargs",
":",
"cacheablesource",
":",
"Elemtree",
".",
"element",
"object",
"of",
"cacheablesource",
"cachearea",
":",
"Elemtree",
".",
"element",
"object",
"of",
"cachearea",
"Returns",
":",
"(",
"ICachableSource",
"ICac... | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L141-L161 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | cache.poll | def poll(self, **kwargs):
"""Continously poll a cachablesource/cachearea combination
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
exit_: threading.Event listener for app exit call message
... | python | def poll(self, **kwargs):
"""Continously poll a cachablesource/cachearea combination
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
exit_: threading.Event listener for app exit call message
... | [
"def",
"poll",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"source",
",",
"area",
",",
"delta",
"=",
"self",
".",
"create_poller",
"(",
"*",
"*",
"kwargs",
")",
"area",
".",
"initialize",
"(",
")",
"while",
"True",
":",
"try",
":",
"count",
"... | Continously poll a cachablesource/cachearea combination
Kwargs:
cacheablesource: Elemtree.element object of cacheablesource
cachearea: Elemtree.element object of cachearea
exit_: threading.Event listener for app exit call message | [
"Continously",
"poll",
"a",
"cachablesource",
"/",
"cachearea",
"combination",
"Kwargs",
":",
"cacheablesource",
":",
"Elemtree",
".",
"element",
"object",
"of",
"cacheablesource",
"cachearea",
":",
"Elemtree",
".",
"element",
"object",
"of",
"cachearea",
"exit_",
... | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L163-L201 |
davisd50/sparc.apps.cache | sparc/apps/cache/cache.py | cache.go | def go(self, poller_configurations):
"""Create threaded pollers and start configured polling cycles
"""
try:
notify(
CachableSourcePollersAboutToStartEvent(poller_configurations))
logger.info("Starting pollers")
exit_ = threading.Event()
... | python | def go(self, poller_configurations):
"""Create threaded pollers and start configured polling cycles
"""
try:
notify(
CachableSourcePollersAboutToStartEvent(poller_configurations))
logger.info("Starting pollers")
exit_ = threading.Event()
... | [
"def",
"go",
"(",
"self",
",",
"poller_configurations",
")",
":",
"try",
":",
"notify",
"(",
"CachableSourcePollersAboutToStartEvent",
"(",
"poller_configurations",
")",
")",
"logger",
".",
"info",
"(",
"\"Starting pollers\"",
")",
"exit_",
"=",
"threading",
".",
... | Create threaded pollers and start configured polling cycles | [
"Create",
"threaded",
"pollers",
"and",
"start",
"configured",
"polling",
"cycles"
] | train | https://github.com/davisd50/sparc.apps.cache/blob/793b0f18255230809c30dc27c2bb1bb04b3f194d/sparc/apps/cache/cache.py#L203-L221 |
EventTeam/beliefs | src/beliefs/cells/colors.py | RGBColorCell.from_name | def from_name(clz, name):
"""
Instantiates the object from a known name
"""
if isinstance(name, list) and "green" in name:
name = "teal"
assert name in COLOR_NAMES, 'Unknown color name'
r, b, g = COLOR_NAMES[name]
return clz(r, b, g) | python | def from_name(clz, name):
"""
Instantiates the object from a known name
"""
if isinstance(name, list) and "green" in name:
name = "teal"
assert name in COLOR_NAMES, 'Unknown color name'
r, b, g = COLOR_NAMES[name]
return clz(r, b, g) | [
"def",
"from_name",
"(",
"clz",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"list",
")",
"and",
"\"green\"",
"in",
"name",
":",
"name",
"=",
"\"teal\"",
"assert",
"name",
"in",
"COLOR_NAMES",
",",
"'Unknown color name'",
"r",
",",
"b",
... | Instantiates the object from a known name | [
"Instantiates",
"the",
"object",
"from",
"a",
"known",
"name"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/colors.py#L27-L35 |
EventTeam/beliefs | src/beliefs/cells/colors.py | RGBColorCell.to_html | def to_html(self):
""" Converts to Hex """
out = "#"
if self.r == 0:
out += "00"
else:
out += hex(self.r)[2:]
if self.b == 0:
out += "00"
else:
out += hex(self.b)[2:]
if self.g == 0:
out += "00"
e... | python | def to_html(self):
""" Converts to Hex """
out = "#"
if self.r == 0:
out += "00"
else:
out += hex(self.r)[2:]
if self.b == 0:
out += "00"
else:
out += hex(self.b)[2:]
if self.g == 0:
out += "00"
e... | [
"def",
"to_html",
"(",
"self",
")",
":",
"out",
"=",
"\"#\"",
"if",
"self",
".",
"r",
"==",
"0",
":",
"out",
"+=",
"\"00\"",
"else",
":",
"out",
"+=",
"hex",
"(",
"self",
".",
"r",
")",
"[",
"2",
":",
"]",
"if",
"self",
".",
"b",
"==",
"0",... | Converts to Hex | [
"Converts",
"to",
"Hex"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/colors.py#L38-L53 |
EventTeam/beliefs | src/beliefs/cells/colors.py | RGBColorCell.membership_score | def membership_score(self, element):
""" Fuzzy set gradable membership score
See http://code.google.com/p/python-colormath/wiki/ColorDifferences
"""
other = self.coerce(element)
if self.value and other.value:
return 1 - (self.value.delta_e(other.value, mode='cmc', pl=... | python | def membership_score(self, element):
""" Fuzzy set gradable membership score
See http://code.google.com/p/python-colormath/wiki/ColorDifferences
"""
other = self.coerce(element)
if self.value and other.value:
return 1 - (self.value.delta_e(other.value, mode='cmc', pl=... | [
"def",
"membership_score",
"(",
"self",
",",
"element",
")",
":",
"other",
"=",
"self",
".",
"coerce",
"(",
"element",
")",
"if",
"self",
".",
"value",
"and",
"other",
".",
"value",
":",
"return",
"1",
"-",
"(",
"self",
".",
"value",
".",
"delta_e",
... | Fuzzy set gradable membership score
See http://code.google.com/p/python-colormath/wiki/ColorDifferences | [
"Fuzzy",
"set",
"gradable",
"membership",
"score",
"See",
"http",
":",
"//",
"code",
".",
"google",
".",
"com",
"/",
"p",
"/",
"python",
"-",
"colormath",
"/",
"wiki",
"/",
"ColorDifferences"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/colors.py#L70-L78 |
EventTeam/beliefs | src/beliefs/cells/colors.py | RGBColorCell.merge | def merge(self, other):
"""
Merges the values
"""
print "MERGING", self, other
other = self.coerce(other)
if self.is_contradictory(other):
raise Contradiction("Cannot merge %s and %s" % (self, other))
elif self.value is None and not other.value is None... | python | def merge(self, other):
"""
Merges the values
"""
print "MERGING", self, other
other = self.coerce(other)
if self.is_contradictory(other):
raise Contradiction("Cannot merge %s and %s" % (self, other))
elif self.value is None and not other.value is None... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"print",
"\"MERGING\"",
",",
"self",
",",
"other",
"other",
"=",
"self",
".",
"coerce",
"(",
"other",
")",
"if",
"self",
".",
"is_contradictory",
"(",
"other",
")",
":",
"raise",
"Contradiction",
"("... | Merges the values | [
"Merges",
"the",
"values"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/colors.py#L80-L93 |
coghost/izen | izen/amq.py | push_to_topic | def push_to_topic(dst, dat, qos=0, retain=False, cfgs=None):
"""
- 发送数据 dat 到目的地 dst
:param cfgs:
:type cfgs:
:param dst:
:type dst:
:param dat:
:type dat:
:param qos:
:type qos:
:param retain:
:type retain:
"""
cfg_amqt = {
'hostname': cfgs['hostname'],
... | python | def push_to_topic(dst, dat, qos=0, retain=False, cfgs=None):
"""
- 发送数据 dat 到目的地 dst
:param cfgs:
:type cfgs:
:param dst:
:type dst:
:param dat:
:type dat:
:param qos:
:type qos:
:param retain:
:type retain:
"""
cfg_amqt = {
'hostname': cfgs['hostname'],
... | [
"def",
"push_to_topic",
"(",
"dst",
",",
"dat",
",",
"qos",
"=",
"0",
",",
"retain",
"=",
"False",
",",
"cfgs",
"=",
"None",
")",
":",
"cfg_amqt",
"=",
"{",
"'hostname'",
":",
"cfgs",
"[",
"'hostname'",
"]",
",",
"'port'",
":",
"cfgs",
"[",
"'port'... | - 发送数据 dat 到目的地 dst
:param cfgs:
:type cfgs:
:param dst:
:type dst:
:param dat:
:type dat:
:param qos:
:type qos:
:param retain:
:type retain: | [
"-",
"发送数据",
"dat",
"到目的地",
"dst"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/amq.py#L146-L179 |
coghost/izen | izen/amq.py | _on_connect | def _on_connect(client, userdata, flags, rc):
"""默认 topic 连接处理方法"""
log.debug('[MQTT] Connected with result code ' + str(rc))
client.subscribe('test_topic', qos=2) | python | def _on_connect(client, userdata, flags, rc):
"""默认 topic 连接处理方法"""
log.debug('[MQTT] Connected with result code ' + str(rc))
client.subscribe('test_topic', qos=2) | [
"def",
"_on_connect",
"(",
"client",
",",
"userdata",
",",
"flags",
",",
"rc",
")",
":",
"log",
".",
"debug",
"(",
"'[MQTT] Connected with result code '",
"+",
"str",
"(",
"rc",
")",
")",
"client",
".",
"subscribe",
"(",
"'test_topic'",
",",
"qos",
"=",
... | 默认 topic 连接处理方法 | [
"默认",
"topic",
"连接处理方法"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/amq.py#L201-L204 |
coghost/izen | izen/amq.py | Publisher.run | def run(self, dat=None):
"""
发布消息
- 样例:
.. code:: python
t = {
'hostname': '192.168.1.2',
'port': 1883,
'username': 'admin',
'password': 'admin',
}
Publisher(t).run({'payload': json... | python | def run(self, dat=None):
"""
发布消息
- 样例:
.. code:: python
t = {
'hostname': '192.168.1.2',
'port': 1883,
'username': 'admin',
'password': 'admin',
}
Publisher(t).run({'payload': json... | [
"def",
"run",
"(",
"self",
",",
"dat",
"=",
"None",
")",
":",
"conf",
"=",
"self",
".",
"conf",
"dat",
"=",
"dat",
"if",
"dat",
"else",
"{",
"}",
"publish",
".",
"single",
"(",
"topic",
"=",
"dat",
".",
"get",
"(",
"'topic'",
",",
"'test_topic'",... | 发布消息
- 样例:
.. code:: python
t = {
'hostname': '192.168.1.2',
'port': 1883,
'username': 'admin',
'password': 'admin',
}
Publisher(t).run({'payload': json.dumps(t)}) if pub else TopicConsumer(t).run()
... | [
"发布消息"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/amq.py#L71-L100 |
rickmak/pyramid_rest_route | pyramid_rest_route/route.py | allowed_extension | def allowed_extension(*allowed):
'''
refs: http://zhuoqiang.me/a/restful-pyramid
Custom predict checking if the the file extension
of the request URI is in the allowed set.
'''
def predicate(info, request):
log.debug(request.path)
ext = os.path.splitext(request.path)[1]
r... | python | def allowed_extension(*allowed):
'''
refs: http://zhuoqiang.me/a/restful-pyramid
Custom predict checking if the the file extension
of the request URI is in the allowed set.
'''
def predicate(info, request):
log.debug(request.path)
ext = os.path.splitext(request.path)[1]
r... | [
"def",
"allowed_extension",
"(",
"*",
"allowed",
")",
":",
"def",
"predicate",
"(",
"info",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"request",
".",
"path",
")",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"request",
".",
"path",
... | refs: http://zhuoqiang.me/a/restful-pyramid
Custom predict checking if the the file extension
of the request URI is in the allowed set. | [
"refs",
":",
"http",
":",
"//",
"zhuoqiang",
".",
"me",
"/",
"a",
"/",
"restful",
"-",
"pyramid",
"Custom",
"predict",
"checking",
"if",
"the",
"the",
"file",
"extension",
"of",
"the",
"request",
"URI",
"is",
"in",
"the",
"allowed",
"set",
"."
] | train | https://github.com/rickmak/pyramid_rest_route/blob/b497704e23916989ef690cfb1c729fa94bd2266d/pyramid_rest_route/route.py#L22-L35 |
dustinmm80/healthy | healthy.py | calculate_health | def calculate_health(package_name, package_version=None, verbose=False, no_output=False):
"""
Calculates the health of a package, based on several factors
:param package_name: name of package on pypi.python.org
:param package_version: version number of package to check, optional - defaults to latest ve... | python | def calculate_health(package_name, package_version=None, verbose=False, no_output=False):
"""
Calculates the health of a package, based on several factors
:param package_name: name of package on pypi.python.org
:param package_version: version number of package to check, optional - defaults to latest ve... | [
"def",
"calculate_health",
"(",
"package_name",
",",
"package_version",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"no_output",
"=",
"False",
")",
":",
"total_score",
"=",
"0",
"reasons",
"=",
"[",
"]",
"package_releases",
"=",
"CLIENT",
".",
"package_r... | Calculates the health of a package, based on several factors
:param package_name: name of package on pypi.python.org
:param package_version: version number of package to check, optional - defaults to latest version
:param verbose: flag to print out reasons
:param no_output: print no output
:param l... | [
"Calculates",
"the",
"health",
"of",
"a",
"package",
"based",
"on",
"several",
"factors"
] | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L34-L104 |
dustinmm80/healthy | healthy.py | get_health_color | def get_health_color(score):
"""
Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal
"""
color = TERMINAL.green
if score <= 80:
color = TERMINAL.yellow
elif score <= 60:
color = TE... | python | def get_health_color(score):
"""
Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal
"""
color = TERMINAL.green
if score <= 80:
color = TERMINAL.yellow
elif score <= 60:
color = TE... | [
"def",
"get_health_color",
"(",
"score",
")",
":",
"color",
"=",
"TERMINAL",
".",
"green",
"if",
"score",
"<=",
"80",
":",
"color",
"=",
"TERMINAL",
".",
"yellow",
"elif",
"score",
"<=",
"60",
":",
"color",
"=",
"TERMINAL",
".",
"orange",
"elif",
"scor... | Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal | [
"Returns",
"a",
"color",
"based",
"on",
"the",
"health",
"score",
":",
"param",
"score",
":",
"integer",
"from",
"0",
"-",
"100",
"representing",
"health",
":",
"return",
":",
"string",
"of",
"color",
"to",
"apply",
"in",
"terminal"
] | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L119-L134 |
dustinmm80/healthy | healthy.py | main | def main():
"""
Parses user input for a package name
:return:
"""
parser = argparse.ArgumentParser('Determines the health of a package')
parser.add_argument(
'package_name',
help='Name of package listed on pypi.python.org',
)
parser.add_argument(
'package_versio... | python | def main():
"""
Parses user input for a package name
:return:
"""
parser = argparse.ArgumentParser('Determines the health of a package')
parser.add_argument(
'package_name',
help='Name of package listed on pypi.python.org',
)
parser.add_argument(
'package_versio... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"'Determines the health of a package'",
")",
"parser",
".",
"add_argument",
"(",
"'package_name'",
",",
"help",
"=",
"'Name of package listed on pypi.python.org'",
",",
")",
"parser",... | Parses user input for a package name
:return: | [
"Parses",
"user",
"input",
"for",
"a",
"package",
"name",
":",
"return",
":"
] | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L136-L167 |
Wessie/hurler | hurler/filters.py | filter | def filter(filter_creator):
"""
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
"""
filter_func = [None]
def fun... | python | def filter(filter_creator):
"""
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
"""
filter_func = [None]
def fun... | [
"def",
"filter",
"(",
"filter_creator",
")",
":",
"filter_func",
"=",
"[",
"None",
"]",
"def",
"function_getter",
"(",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"Filter",
")",
":",
"function",
".",
"add_filter",
"(",
"filter",
")",
... | Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution. | [
"Creates",
"a",
"decorator",
"that",
"can",
"be",
"used",
"as",
"a",
"filter",
"."
] | train | https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L75-L104 |
Wessie/hurler | hurler/filters.py | filter_simple | def filter_simple(filter):
"""
A simpler version of :func:`filter`. This instead assumes the decorated
function is already a valid filter function, and uses it directly.
"""
def function_getter(function):
if isinstance(function, Filter):
function.add_filter(filter)
r... | python | def filter_simple(filter):
"""
A simpler version of :func:`filter`. This instead assumes the decorated
function is already a valid filter function, and uses it directly.
"""
def function_getter(function):
if isinstance(function, Filter):
function.add_filter(filter)
r... | [
"def",
"filter_simple",
"(",
"filter",
")",
":",
"def",
"function_getter",
"(",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"Filter",
")",
":",
"function",
".",
"add_filter",
"(",
"filter",
")",
"return",
"function",
"else",
":",
"retur... | A simpler version of :func:`filter`. This instead assumes the decorated
function is already a valid filter function, and uses it directly. | [
"A",
"simpler",
"version",
"of",
":",
"func",
":",
"filter",
".",
"This",
"instead",
"assumes",
"the",
"decorated",
"function",
"is",
"already",
"a",
"valid",
"filter",
"function",
"and",
"uses",
"it",
"directly",
"."
] | train | https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L107-L123 |
Wessie/hurler | hurler/filters.py | Filter.check_filter | def check_filter(self, args, kwargs):
"""
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippe... | python | def check_filter(self, args, kwargs):
"""
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippe... | [
"def",
"check_filter",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"for",
"f",
"in",
"self",
".",
"_filters",
":",
"if",
"not",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"False",
"return",
"True"
] | Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippet:
`all(f(*args, **kwargs) for f in self.filte... | [
"Calls",
"all",
"filters",
"in",
"the",
":",
"attr",
":",
"_filters",
"list",
"and",
"if",
"all",
"of",
"them",
"return",
":",
"const",
":",
"True",
"will",
"return",
":",
"const",
":",
"True",
".",
"If",
"any",
"of",
"the",
"filters",
"return",
":",... | train | https://github.com/Wessie/hurler/blob/5719000237e24df9f24fb8229f1153ebfa684972/hurler/filters.py#L48-L61 |
fred49/linshare-api | linshareapi/user/core.py | GenericClass.delete | def delete(self, uuid):
"""TODO"""
url = "{base}/{uuid}".format(
base=self.local_base_url,
uuid=uuid
)
return self.core.delete(url) | python | def delete(self, uuid):
"""TODO"""
url = "{base}/{uuid}".format(
base=self.local_base_url,
uuid=uuid
)
return self.core.delete(url) | [
"def",
"delete",
"(",
"self",
",",
"uuid",
")",
":",
"url",
"=",
"\"{base}/{uuid}\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"local_base_url",
",",
"uuid",
"=",
"uuid",
")",
"return",
"self",
".",
"core",
".",
"delete",
"(",
"url",
")"
] | TODO | [
"TODO"
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/core.py#L88-L94 |
fred49/linshare-api | linshareapi/user/core.py | GenericClass.update | def update(self, data):
"""TODO"""
self.debug(data)
url = "{base}/{uuid}".format(
base=self.local_base_url,
uuid=data.get('uuid')
)
return self.core.update(url, data) | python | def update(self, data):
"""TODO"""
self.debug(data)
url = "{base}/{uuid}".format(
base=self.local_base_url,
uuid=data.get('uuid')
)
return self.core.update(url, data) | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"debug",
"(",
"data",
")",
"url",
"=",
"\"{base}/{uuid}\"",
".",
"format",
"(",
"base",
"=",
"self",
".",
"local_base_url",
",",
"uuid",
"=",
"data",
".",
"get",
"(",
"'uuid'",
")",
... | TODO | [
"TODO"
] | train | https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/core.py#L108-L115 |
awacha/credolib | credolib/interpretation.py | guinieranalysis | def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix='', dist=None,
plotguinier=True, graph_extension='.png', dmax=None, dmax_from_shanum=False):
"""Perform Guinier analysis on the samples.
Inputs:
samplenames: list of sample names
qrange... | python | def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix='', dist=None,
plotguinier=True, graph_extension='.png', dmax=None, dmax_from_shanum=False):
"""Perform Guinier analysis on the samples.
Inputs:
samplenames: list of sample names
qrange... | [
"def",
"guinieranalysis",
"(",
"samplenames",
",",
"qranges",
"=",
"None",
",",
"qmax_from_shanum",
"=",
"True",
",",
"prfunctions_postfix",
"=",
"''",
",",
"dist",
"=",
"None",
",",
"plotguinier",
"=",
"True",
",",
"graph_extension",
"=",
"'.png'",
",",
"dm... | Perform Guinier analysis on the samples.
Inputs:
samplenames: list of sample names
qranges: dictionary of q ranges for each sample. The keys are sample names. The special '__default__' key
corresponds to all samples which do not have a key in the dict.
qmax_from_shanum: use the ... | [
"Perform",
"Guinier",
"analysis",
"on",
"the",
"samples",
"."
] | train | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/interpretation.py#L16-L161 |
ONSdigital/sdx-common | sdx/common/log_levels.py | set_level | def set_level(logger=None, log_level=None):
'''Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None
'''
log_level = logging.getL... | python | def set_level(logger=None, log_level=None):
'''Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None
'''
log_level = logging.getL... | [
"def",
"set_level",
"(",
"logger",
"=",
"None",
",",
"log_level",
"=",
"None",
")",
":",
"log_level",
"=",
"logging",
".",
"getLevelName",
"(",
"os",
".",
"getenv",
"(",
"'VERBOSITY'",
",",
"'WARNING'",
")",
")",
"logging",
".",
"getLogger",
"(",
"logger... | Set logging levels using logger names.
:param logger: Name of the logger
:type logger: String
:param log_level: A string or integer corresponding to a Python logging level
:type log_level: String
:rtype: None | [
"Set",
"logging",
"levels",
"using",
"logger",
"names",
"."
] | train | https://github.com/ONSdigital/sdx-common/blob/815f6a116d41fddae182943d821dc5f582a9af69/sdx/common/log_levels.py#L5-L18 |
abe-winter/pg13-py | pg13/sqparse2.py | bin_priority | def bin_priority(op,left,right):
"I don't know how to handle order of operations in the LR grammar, so here it is"
# note: recursion limits protect this from infinite looping. I'm serious. (i.e. it will crash rather than hanging)
if isinstance(left,BinX) and left.op < op: return bin_priority(left.op,left.left,bin... | python | def bin_priority(op,left,right):
"I don't know how to handle order of operations in the LR grammar, so here it is"
# note: recursion limits protect this from infinite looping. I'm serious. (i.e. it will crash rather than hanging)
if isinstance(left,BinX) and left.op < op: return bin_priority(left.op,left.left,bin... | [
"def",
"bin_priority",
"(",
"op",
",",
"left",
",",
"right",
")",
":",
"# note: recursion limits protect this from infinite looping. I'm serious. (i.e. it will crash rather than hanging)",
"if",
"isinstance",
"(",
"left",
",",
"BinX",
")",
"and",
"left",
".",
"op",
"<",
... | I don't know how to handle order of operations in the LR grammar, so here it is | [
"I",
"don",
"t",
"know",
"how",
"to",
"handle",
"order",
"of",
"operations",
"in",
"the",
"LR",
"grammar",
"so",
"here",
"it",
"is"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L116-L122 |
abe-winter/pg13-py | pg13/sqparse2.py | un_priority | def un_priority(op,val):
"unary expression order-of-operations helper"
if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right)
else: return UnX(op,val) | python | def un_priority(op,val):
"unary expression order-of-operations helper"
if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right)
else: return UnX(op,val) | [
"def",
"un_priority",
"(",
"op",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"BinX",
")",
"and",
"val",
".",
"op",
"<",
"op",
":",
"return",
"bin_priority",
"(",
"val",
".",
"op",
",",
"UnX",
"(",
"op",
",",
"val",
".",
"left",
"... | unary expression order-of-operations helper | [
"unary",
"expression",
"order",
"-",
"of",
"-",
"operations",
"helper"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L123-L126 |
abe-winter/pg13-py | pg13/sqparse2.py | lex | def lex(string):
"this is only used by tests"
safe_lexer = LEXER.clone() # reentrant? I can't tell, I hate implicit globals. do a threading test
safe_lexer.input(string)
a = []
while 1:
t = safe_lexer.token()
if t: a.append(t)
else: break
return a | python | def lex(string):
"this is only used by tests"
safe_lexer = LEXER.clone() # reentrant? I can't tell, I hate implicit globals. do a threading test
safe_lexer.input(string)
a = []
while 1:
t = safe_lexer.token()
if t: a.append(t)
else: break
return a | [
"def",
"lex",
"(",
"string",
")",
":",
"safe_lexer",
"=",
"LEXER",
".",
"clone",
"(",
")",
"# reentrant? I can't tell, I hate implicit globals. do a threading test",
"safe_lexer",
".",
"input",
"(",
"string",
")",
"a",
"=",
"[",
"]",
"while",
"1",
":",
"t",
"=... | this is only used by tests | [
"this",
"is",
"only",
"used",
"by",
"tests"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L352-L361 |
abe-winter/pg13-py | pg13/sqparse2.py | parse | def parse(string):
"return a BaseX tree for the string"
print string
if string.strip().lower().startswith('create index'): return IndexX(string)
return YACC.parse(string, lexer=LEXER.clone()) | python | def parse(string):
"return a BaseX tree for the string"
print string
if string.strip().lower().startswith('create index'): return IndexX(string)
return YACC.parse(string, lexer=LEXER.clone()) | [
"def",
"parse",
"(",
"string",
")",
":",
"print",
"string",
"if",
"string",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'create index'",
")",
":",
"return",
"IndexX",
"(",
"string",
")",
"return",
"YACC",
".",
"parse",
"(... | return a BaseX tree for the string | [
"return",
"a",
"BaseX",
"tree",
"for",
"the",
"string"
] | train | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L364-L368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.