repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
hvac/hvac | hvac/v1/__init__.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/v1/__init__.py#L1555-L1567 | def delete_kubernetes_role(self, role, mount_point='kubernetes'):
"""DELETE /auth/<mount_point>/role/:role
:type role: Name of the role.
:param role: str.
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_po... | [
"def",
"delete_kubernetes_role",
"(",
"self",
",",
"role",
",",
"mount_point",
"=",
"'kubernetes'",
")",
":",
"url",
"=",
"'v1/auth/{0}/role/{1}'",
".",
"format",
"(",
"mount_point",
",",
"role",
")",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"u... | DELETE /auth/<mount_point>/role/:role
:type role: Name of the role.
:param role: str.
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_point: str.
:return: Will be an empty body with a 204 status code upon ... | [
"DELETE",
"/",
"auth",
"/",
"<mount_point",
">",
"/",
"role",
"/",
":",
"role"
] | python | train | 41.923077 |
jjgomera/iapws | iapws/iapws97.py | https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L323-L366 | def _TSat_P(P):
"""Define the saturated line, T=f(P)
Parameters
----------
P : float
Pressure, [MPa]
Returns
-------
T : float
Temperature, [K]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0.00061121 ≤ P ≤ 22.064
Refe... | [
"def",
"_TSat_P",
"(",
"P",
")",
":",
"# Check input parameters",
"if",
"P",
"<",
"611.212677",
"/",
"1e6",
"or",
"P",
">",
"22.064",
":",
"raise",
"NotImplementedError",
"(",
"\"Incoming out of bound\"",
")",
"n",
"=",
"[",
"0",
",",
"0.11670521452767E+04",
... | Define the saturated line, T=f(P)
Parameters
----------
P : float
Pressure, [MPa]
Returns
-------
T : float
Temperature, [K]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 0.00061121 ≤ P ≤ 22.064
References
----------
... | [
"Define",
"the",
"saturated",
"line",
"T",
"=",
"f",
"(",
"P",
")"
] | python | train | 26.613636 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L1771-L1796 | def _get_team_results(self, team_result_html):
"""
Extract the winning or losing team's name and abbreviation.
Depending on which team's data field is passed (either the winner or
loser), return the name and abbreviation of that team to denote which
team won and which lost the g... | [
"def",
"_get_team_results",
"(",
"self",
",",
"team_result_html",
")",
":",
"link",
"=",
"[",
"i",
"for",
"i",
"in",
"team_result_html",
"(",
"'td a'",
")",
".",
"items",
"(",
")",
"]",
"# If there are no links, the boxscore is likely misformed and can't be",
"# par... | Extract the winning or losing team's name and abbreviation.
Depending on which team's data field is passed (either the winner or
loser), return the name and abbreviation of that team to denote which
team won and which lost the game.
Parameters
----------
team_result_htm... | [
"Extract",
"the",
"winning",
"or",
"losing",
"team",
"s",
"name",
"and",
"abbreviation",
"."
] | python | train | 37.653846 |
PredixDev/predixpy | predix/admin/app.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L85-L109 | def create_client(self, client_id=None, client_secret=None, uaa=None):
"""
Create a client and add it to the manifest.
:param client_id: The client id used to authenticate as a client
in UAA.
:param client_secret: The secret password used by a client to
authenti... | [
"def",
"create_client",
"(",
"self",
",",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"uaa",
"=",
"None",
")",
":",
"if",
"not",
"uaa",
":",
"uaa",
"=",
"predix",
".",
"admin",
".",
"uaa",
".",
"UserAccountAuthentication",
"(",
")... | Create a client and add it to the manifest.
:param client_id: The client id used to authenticate as a client
in UAA.
:param client_secret: The secret password used by a client to
authenticate and generate a UAA token.
:param uaa: The UAA to create client with | [
"Create",
"a",
"client",
"and",
"add",
"it",
"to",
"the",
"manifest",
"."
] | python | train | 32.72 |
spotify/luigi | luigi/scheduler.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/scheduler.py#L179-L188 | def add_failure(self):
"""
Add a failure event with the current timestamp.
"""
failure_time = time.time()
if not self.first_failure_time:
self.first_failure_time = failure_time
self.failures.append(failure_time) | [
"def",
"add_failure",
"(",
"self",
")",
":",
"failure_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"not",
"self",
".",
"first_failure_time",
":",
"self",
".",
"first_failure_time",
"=",
"failure_time",
"self",
".",
"failures",
".",
"append",
"(",
"fail... | Add a failure event with the current timestamp. | [
"Add",
"a",
"failure",
"event",
"with",
"the",
"current",
"timestamp",
"."
] | python | train | 26.4 |
heuer/segno | segno/encoder.py | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L718-L733 | def apply_mask(matrix, mask_pattern, matrix_size, is_encoding_region):
"""\
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matr... | [
"def",
"apply_mask",
"(",
"matrix",
",",
"mask_pattern",
",",
"matrix_size",
",",
"is_encoding_region",
")",
":",
"for",
"i",
"in",
"range",
"(",
"matrix_size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"matrix_size",
")",
":",
"if",
"is_encoding_region",
... | \
Applies the provided mask pattern on the `matrix`.
ISO/IEC 18004:2015(E) -- 7.8.2 Data mask patterns (page 50)
:param tuple matrix: A tuple of bytearrays
:param mask_pattern: A mask pattern (a function)
:param int matrix_size: width or height of the matrix
:param is_encoding_region: A functi... | [
"\\",
"Applies",
"the",
"provided",
"mask",
"pattern",
"on",
"the",
"matrix",
"."
] | python | train | 40.5 |
peterbe/hashin | hashin.py | https://github.com/peterbe/hashin/blob/c3efcba050961257622c475114c087efe675c58a/hashin.py#L464-L484 | def expand_python_version(version):
"""
Expand Python versions to all identifiers used on PyPI.
>>> expand_python_version('3.5')
['3.5', 'py3', 'py2.py3', 'cp35']
"""
if not re.match(r"^\d\.\d$", version):
return [version]
major, minor = version.split(".")
patterns = [
... | [
"def",
"expand_python_version",
"(",
"version",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r\"^\\d\\.\\d$\"",
",",
"version",
")",
":",
"return",
"[",
"version",
"]",
"major",
",",
"minor",
"=",
"version",
".",
"split",
"(",
"\".\"",
")",
"patterns... | Expand Python versions to all identifiers used on PyPI.
>>> expand_python_version('3.5')
['3.5', 'py3', 'py2.py3', 'cp35'] | [
"Expand",
"Python",
"versions",
"to",
"all",
"identifiers",
"used",
"on",
"PyPI",
"."
] | python | train | 26.095238 |
mzucker/noteshrink | noteshrink.py | https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L116-L137 | def rgb_to_sv(rgb):
'''Convert an RGB image or array of RGB colors to saturation and
value, returning each one as a separate 32-bit floating point array or
value.
'''
if not isinstance(rgb, np.ndarray):
rgb = np.array(rgb)
axis = len(rgb.shape)-1
cmax = rgb.max(axis=axis).astype(np.float... | [
"def",
"rgb_to_sv",
"(",
"rgb",
")",
":",
"if",
"not",
"isinstance",
"(",
"rgb",
",",
"np",
".",
"ndarray",
")",
":",
"rgb",
"=",
"np",
".",
"array",
"(",
"rgb",
")",
"axis",
"=",
"len",
"(",
"rgb",
".",
"shape",
")",
"-",
"1",
"cmax",
"=",
"... | Convert an RGB image or array of RGB colors to saturation and
value, returning each one as a separate 32-bit floating point array or
value. | [
"Convert",
"an",
"RGB",
"image",
"or",
"array",
"of",
"RGB",
"colors",
"to",
"saturation",
"and",
"value",
"returning",
"each",
"one",
"as",
"a",
"separate",
"32",
"-",
"bit",
"floating",
"point",
"array",
"or",
"value",
"."
] | python | train | 25 |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/checks/libs/thread_pool.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/libs/thread_pool.py#L170-L183 | def imap_async(self, func, iterable, chunksize=None, callback=None):
"""A variant of the imap() method which returns an ApplyResult
object that provides an iterator (next method(timeout)
available).
If callback is specified then it should be a callable which
accepts a single arg... | [
"def",
"imap_async",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"apply_result",
"=",
"ApplyResult",
"(",
"callback",
"=",
"callback",
")",
"collector",
"=",
"OrderedResultCollector",
"(",... | A variant of the imap() method which returns an ApplyResult
object that provides an iterator (next method(timeout)
available).
If callback is specified then it should be a callable which
accepts a single argument. When the resulting iterator becomes
ready, callback is applied to... | [
"A",
"variant",
"of",
"the",
"imap",
"()",
"method",
"which",
"returns",
"an",
"ApplyResult",
"object",
"that",
"provides",
"an",
"iterator",
"(",
"next",
"method",
"(",
"timeout",
")",
"available",
")",
"."
] | python | train | 54.928571 |
aiortc/aiortc | aiortc/utils.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/utils.py#L20-L26 | def uint16_gt(a: int, b: int) -> bool:
"""
Return a > b.
"""
half_mod = 0x8000
return (((a < b) and ((b - a) > half_mod)) or
((a > b) and ((a - b) < half_mod))) | [
"def",
"uint16_gt",
"(",
"a",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"bool",
":",
"half_mod",
"=",
"0x8000",
"return",
"(",
"(",
"(",
"a",
"<",
"b",
")",
"and",
"(",
"(",
"b",
"-",
"a",
")",
">",
"half_mod",
")",
")",
"or",
"(",
"(",
... | Return a > b. | [
"Return",
"a",
">",
"b",
"."
] | python | train | 26.571429 |
closeio/quotequail | quotequail/_html.py | https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_html.py#L220-L237 | def render_html_tree(tree):
"""
Renders the given HTML tree, and strips any wrapping that was applied in
get_html_tree().
You should avoid further processing of the given tree after calling this
method because we modify namespaced tags here.
"""
# Restore any tag names that were changed in... | [
"def",
"render_html_tree",
"(",
"tree",
")",
":",
"# Restore any tag names that were changed in get_html_tree()",
"for",
"el",
"in",
"tree",
".",
"iter",
"(",
")",
":",
"if",
"'__tag_name'",
"in",
"el",
".",
"attrib",
":",
"actual_tag_name",
"=",
"el",
".",
"att... | Renders the given HTML tree, and strips any wrapping that was applied in
get_html_tree().
You should avoid further processing of the given tree after calling this
method because we modify namespaced tags here. | [
"Renders",
"the",
"given",
"HTML",
"tree",
"and",
"strips",
"any",
"wrapping",
"that",
"was",
"applied",
"in",
"get_html_tree",
"()",
"."
] | python | train | 32.277778 |
Clinical-Genomics/scout | scout/utils/acmg.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/utils/acmg.py#L2-L55 | def is_pathogenic(pvs, ps_terms, pm_terms, pp_terms):
"""Check if the criterias for Pathogenic is fullfilled
The following are descriptions of Pathogenic clasification from ACMG paper:
Pathogenic
(i) 1 Very strong (PVS1) AND
(a) ≥1 Strong (PS1–PS4) OR
(b) ≥2 Moderate (PM1–PM6) OR
... | [
"def",
"is_pathogenic",
"(",
"pvs",
",",
"ps_terms",
",",
"pm_terms",
",",
"pp_terms",
")",
":",
"if",
"pvs",
":",
"# Pathogenic (i)(a):",
"if",
"ps_terms",
":",
"return",
"True",
"if",
"pm_terms",
":",
"# Pathogenic (i)(c):",
"if",
"pp_terms",
":",
"return",
... | Check if the criterias for Pathogenic is fullfilled
The following are descriptions of Pathogenic clasification from ACMG paper:
Pathogenic
(i) 1 Very strong (PVS1) AND
(a) ≥1 Strong (PS1–PS4) OR
(b) ≥2 Moderate (PM1–PM6) OR
(c) 1 Moderate (PM1–PM6) and 1 supporting (PP1–PP5) OR
... | [
"Check",
"if",
"the",
"criterias",
"for",
"Pathogenic",
"is",
"fullfilled"
] | python | test | 30.851852 |
praekeltfoundation/molo | molo/core/templatetags/core_tags.py | https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/templatetags/core_tags.py#L676-L691 | def handle_markdown(value):
md = markdown(
value,
extensions=[
'markdown.extensions.fenced_code',
'codehilite',
]
)
""" For some unknown reason markdown wraps the value in <p> tags.
Currently there doesn't seem to be an extension to turn this off.
... | [
"def",
"handle_markdown",
"(",
"value",
")",
":",
"md",
"=",
"markdown",
"(",
"value",
",",
"extensions",
"=",
"[",
"'markdown.extensions.fenced_code'",
",",
"'codehilite'",
",",
"]",
")",
"open_tag",
"=",
"'<p>'",
"close_tag",
"=",
"'</p>'",
"if",
"md",
"."... | For some unknown reason markdown wraps the value in <p> tags.
Currently there doesn't seem to be an extension to turn this off. | [
"For",
"some",
"unknown",
"reason",
"markdown",
"wraps",
"the",
"value",
"in",
"<p",
">",
"tags",
".",
"Currently",
"there",
"doesn",
"t",
"seem",
"to",
"be",
"an",
"extension",
"to",
"turn",
"this",
"off",
"."
] | python | train | 30.1875 |
aliyun/aliyun-odps-python-sdk | odps/ml/expr/mixin.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/expr/mixin.py#L190-L207 | def continuous(self, *args):
"""
Set fields to be continuous.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=DISCRETE, f2=DISCRETE
>>> # Now we want to set ``f1`` and ``f2`` into continuou... | [
"def",
"continuous",
"(",
"self",
",",
"*",
"args",
")",
":",
"new_df",
"=",
"copy_df",
"(",
"self",
")",
"fields",
"=",
"_render_field_set",
"(",
"args",
")",
"self",
".",
"_assert_ml_fields_valid",
"(",
"*",
"fields",
")",
"new_df",
".",
"_perform_operat... | Set fields to be continuous.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=DISCRETE, f2=DISCRETE
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.continuous('f1 f2') | [
"Set",
"fields",
"to",
"be",
"continuous",
"."
] | python | train | 34.055556 |
underworldcode/stripy | stripy-src/stripy/__init__.py | https://github.com/underworldcode/stripy/blob/d4c3480c3e58c88489ded695eadbe7cd5bf94b48/stripy-src/stripy/__init__.py#L25-L72 | def weighted_average_to_nodes(x1, x2, data, interpolator ):
""" Weighted average of scattered data to the nodal points
of a triangulation using the barycentric coordinates as
weightings.
Parameters
----------
x1, x2 : 1D arrays arrays of x,y or lon, lat (radians)
data : 1D array of data... | [
"def",
"weighted_average_to_nodes",
"(",
"x1",
",",
"x2",
",",
"data",
",",
"interpolator",
")",
":",
"import",
"numpy",
"as",
"np",
"gridded_data",
"=",
"np",
".",
"zeros",
"(",
"interpolator",
".",
"npoints",
")",
"norm",
"=",
"np",
".",
"zeros",
"(",
... | Weighted average of scattered data to the nodal points
of a triangulation using the barycentric coordinates as
weightings.
Parameters
----------
x1, x2 : 1D arrays arrays of x,y or lon, lat (radians)
data : 1D array of data to be lumped to the node locations
interpolator : a stripy.Tri... | [
"Weighted",
"average",
"of",
"scattered",
"data",
"to",
"the",
"nodal",
"points",
"of",
"a",
"triangulation",
"using",
"the",
"barycentric",
"coordinates",
"as",
"weightings",
"."
] | python | train | 31.25 |
Qiskit/qiskit-terra | qiskit/pulse/channels/qubit.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/channels/qubit.py#L57-L62 | def drive(self) -> DriveChannel:
"""Return the primary drive channel of this qubit."""
if self._drives:
return self._drives[0]
else:
raise PulseError("No drive channels in q[%d]" % self._index) | [
"def",
"drive",
"(",
"self",
")",
"->",
"DriveChannel",
":",
"if",
"self",
".",
"_drives",
":",
"return",
"self",
".",
"_drives",
"[",
"0",
"]",
"else",
":",
"raise",
"PulseError",
"(",
"\"No drive channels in q[%d]\"",
"%",
"self",
".",
"_index",
")"
] | Return the primary drive channel of this qubit. | [
"Return",
"the",
"primary",
"drive",
"channel",
"of",
"this",
"qubit",
"."
] | python | test | 39.333333 |
hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2689-L2727 | def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
... | [
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'... | Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
... | [
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] | python | train | 38.25641 |
mvn23/pyotgw | pyotgw/pyotgw.py | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L528-L548 | async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler i... | [
"async",
"def",
"add_alternative",
"(",
"self",
",",
"alt",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_ADD_ALT",
"alt",
"=",
"int",
"(",
"alt",
")",
"if",
"alt",
"<",
"1",
"or",
"alt",
">",
"255",
":",
"return",
"None"... | Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler in a Read-Data request message with the
data-value set to zero. The table of alte... | [
"Add",
"the",
"specified",
"Data",
"-",
"ID",
"to",
"the",
"list",
"of",
"alternative",
"commands",
"to",
"send",
"to",
"the",
"boiler",
"instead",
"of",
"a",
"Data",
"-",
"ID",
"that",
"is",
"known",
"to",
"be",
"unsupported",
"by",
"the",
"boiler",
"... | python | train | 43.190476 |
pycontribs/pyrax | pyrax/cloudblockstorage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudblockstorage.py#L78-L95 | def delete(self):
"""
Adds a check to make sure that the snapshot is able to be deleted.
"""
if self.status not in ("available", "error"):
raise exc.SnapshotNotAvailable("Snapshot must be in 'available' "
"or 'error' status before deleting. Current status:... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"not",
"in",
"(",
"\"available\"",
",",
"\"error\"",
")",
":",
"raise",
"exc",
".",
"SnapshotNotAvailable",
"(",
"\"Snapshot must be in 'available' \"",
"\"or 'error' status before deleting. Current ... | Adds a check to make sure that the snapshot is able to be deleted. | [
"Adds",
"a",
"check",
"to",
"make",
"sure",
"that",
"the",
"snapshot",
"is",
"able",
"to",
"be",
"deleted",
"."
] | python | train | 51 |
WhyNotHugo/python-barcode | barcode/ean.py | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/ean.py#L82-L96 | def build(self):
"""Builds the barcode pattern from `self.ean`.
:returns: The pattern as string
:rtype: String
"""
code = _ean.EDGE[:]
pattern = _ean.LEFT_PATTERN[int(self.ean[0])]
for i, number in enumerate(self.ean[1:7]):
code += _ean.CODES[pattern[... | [
"def",
"build",
"(",
"self",
")",
":",
"code",
"=",
"_ean",
".",
"EDGE",
"[",
":",
"]",
"pattern",
"=",
"_ean",
".",
"LEFT_PATTERN",
"[",
"int",
"(",
"self",
".",
"ean",
"[",
"0",
"]",
")",
"]",
"for",
"i",
",",
"number",
"in",
"enumerate",
"("... | Builds the barcode pattern from `self.ean`.
:returns: The pattern as string
:rtype: String | [
"Builds",
"the",
"barcode",
"pattern",
"from",
"self",
".",
"ean",
"."
] | python | train | 32.2 |
wakatime/wakatime | wakatime/packages/configparser/__init__.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/configparser/__init__.py#L896-L908 | def has_option(self, section, option):
"""Check for the existence of a given option in a given section.
If the specified `section' is None or an empty string, DEFAULT is
assumed. If the specified `section' does not exist, returns False."""
if not section or section == self.default_sectio... | [
"def",
"has_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"not",
"section",
"or",
"section",
"==",
"self",
".",
"default_section",
":",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"return",
"option",
"in",
"self"... | Check for the existence of a given option in a given section.
If the specified `section' is None or an empty string, DEFAULT is
assumed. If the specified `section' does not exist, returns False. | [
"Check",
"for",
"the",
"existence",
"of",
"a",
"given",
"option",
"in",
"a",
"given",
"section",
".",
"If",
"the",
"specified",
"section",
"is",
"None",
"or",
"an",
"empty",
"string",
"DEFAULT",
"is",
"assumed",
".",
"If",
"the",
"specified",
"section",
... | python | train | 48.615385 |
brandon-rhodes/python-adventure | adventure/game.py | https://github.com/brandon-rhodes/python-adventure/blob/e503b68e394fbccb05fe381901c7009fb1bda3d9/adventure/game.py#L118-L132 | def start(self):
"""Start the game."""
# For old-fashioned players, accept five-letter truncations like
# "inven" instead of insisting on full words like "inventory".
for key, value in list(self.vocabulary.items()):
if isinstance(key, str) and len(key) > 5:
... | [
"def",
"start",
"(",
"self",
")",
":",
"# For old-fashioned players, accept five-letter truncations like",
"# \"inven\" instead of insisting on full words like \"inventory\".",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"vocabulary",
".",
"items",
"(",
")",... | Start the game. | [
"Start",
"the",
"game",
"."
] | python | train | 33.533333 |
google/grr | grr/server/grr_response_server/aff4_objects/cronjobs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/cronjobs.py#L392-L408 | def IsRunning(self):
"""Returns True if there's a currently running iteration of this job."""
current_urn = self.Get(self.Schema.CURRENT_FLOW_URN)
if not current_urn:
return False
try:
current_flow = aff4.FACTORY.Open(
urn=current_urn, aff4_type=flow.GRRFlow, token=self.token, mod... | [
"def",
"IsRunning",
"(",
"self",
")",
":",
"current_urn",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"CURRENT_FLOW_URN",
")",
"if",
"not",
"current_urn",
":",
"return",
"False",
"try",
":",
"current_flow",
"=",
"aff4",
".",
"FACTORY",
".",... | Returns True if there's a currently running iteration of this job. | [
"Returns",
"True",
"if",
"there",
"s",
"a",
"currently",
"running",
"iteration",
"of",
"this",
"job",
"."
] | python | train | 36.941176 |
projectatomic/atomic-reactor | atomic_reactor/outer.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/outer.py#L76-L99 | def _load_results(self, container_id):
"""
load results from recent build
:return: BuildResults
"""
if self.temp_dir:
dt = DockerTasker()
# FIXME: load results only when requested
# results_path = os.path.join(self.temp_dir, RESULTS_JSON)
... | [
"def",
"_load_results",
"(",
"self",
",",
"container_id",
")",
":",
"if",
"self",
".",
"temp_dir",
":",
"dt",
"=",
"DockerTasker",
"(",
")",
"# FIXME: load results only when requested",
"# results_path = os.path.join(self.temp_dir, RESULTS_JSON)",
"# df_path = os.path.join(se... | load results from recent build
:return: BuildResults | [
"load",
"results",
"from",
"recent",
"build"
] | python | train | 45.083333 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1571-L1594 | def national_significant_number(numobj):
"""Gets the national significant number of a phone number.
Note that a national significant number doesn't contain a national prefix
or any formatting.
Arguments:
numobj -- The PhoneNumber object for which the national significant number
is ne... | [
"def",
"national_significant_number",
"(",
"numobj",
")",
":",
"# If leading zero(s) have been set, we prefix this now. Note this is not a",
"# national prefix.",
"national_number",
"=",
"U_EMPTY_STRING",
"if",
"numobj",
".",
"italian_leading_zero",
":",
"num_zeros",
"=",
"numobj... | Gets the national significant number of a phone number.
Note that a national significant number doesn't contain a national prefix
or any formatting.
Arguments:
numobj -- The PhoneNumber object for which the national significant number
is needed.
Returns the national significant numb... | [
"Gets",
"the",
"national",
"significant",
"number",
"of",
"a",
"phone",
"number",
"."
] | python | train | 34.625 |
DreamLab/VmShepherd | src/vmshepherd/iaas/openstack_driver.py | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/openstack_driver.py#L150-L157 | async def get_vm(self, vm_id):
'''
Get VM
:arg vm_id: string
:returns vm: object
'''
result = await self.nova.servers.get(vm_id)
return self._map_vm_structure(result["server"]) | [
"async",
"def",
"get_vm",
"(",
"self",
",",
"vm_id",
")",
":",
"result",
"=",
"await",
"self",
".",
"nova",
".",
"servers",
".",
"get",
"(",
"vm_id",
")",
"return",
"self",
".",
"_map_vm_structure",
"(",
"result",
"[",
"\"server\"",
"]",
")"
] | Get VM
:arg vm_id: string
:returns vm: object | [
"Get",
"VM",
":",
"arg",
"vm_id",
":",
"string",
":",
"returns",
"vm",
":",
"object"
] | python | train | 28.125 |
AndresMWeber/Nomenclate | nomenclate/core/tools.py | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/tools.py#L124-L137 | def flatten(it):
""" Flattens any iterable
From:
http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator
:param it: Iterator, iterator to flatten
:return: Generator, A generator of the flattened values
"""
for x in it:
if... | [
"def",
"flatten",
"(",
"it",
")",
":",
"for",
"x",
"in",
"it",
":",
"if",
"isinstance",
"(",
"x",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"for",
"y",
"in",
"flatten",
"(",
"x",
")",
... | Flattens any iterable
From:
http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator
:param it: Iterator, iterator to flatten
:return: Generator, A generator of the flattened values | [
"Flattens",
"any",
"iterable",
"From",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"11503065",
"/",
"python",
"-",
"function",
"-",
"to",
"-",
"flatten",
"-",
"generator",
"-",
"containing",
"-",
"another",
"-",
"generator"
... | python | train | 33 |
v1k45/python-qBittorrent | qbittorrent/client.py | https://github.com/v1k45/python-qBittorrent/blob/04f9482a022dcc78c56b0b9acb9ca455f855ae24/qbittorrent/client.py#L423-L430 | def delete(self, infohash_list):
"""
Delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self._process_infohash_list(infohash_list)
return self._post('command/delete', data=data) | [
"def",
"delete",
"(",
"self",
",",
"infohash_list",
")",
":",
"data",
"=",
"self",
".",
"_process_infohash_list",
"(",
"infohash_list",
")",
"return",
"self",
".",
"_post",
"(",
"'command/delete'",
",",
"data",
"=",
"data",
")"
] | Delete torrents.
:param infohash_list: Single or list() of infohashes. | [
"Delete",
"torrents",
"."
] | python | train | 31.25 |
log2timeline/plaso | plaso/cli/storage_media_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/storage_media_tool.py#L1092-L1118 | def AddVSSProcessingOptions(self, argument_group):
"""Adds the VSS processing options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_group.add_argument(
'--no_vss', '--no-vss', dest='no_vss', action='store_true',
defaul... | [
"def",
"AddVSSProcessingOptions",
"(",
"self",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--no_vss'",
",",
"'--no-vss'",
",",
"dest",
"=",
"'no_vss'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"h... | Adds the VSS processing options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group. | [
"Adds",
"the",
"VSS",
"processing",
"options",
"to",
"the",
"argument",
"group",
"."
] | python | train | 46.555556 |
AnalogJ/lexicon | lexicon/providers/subreg.py | https://github.com/AnalogJ/lexicon/blob/9330b871988753cad44fe2876a217b4c67b1fa0e/lexicon/providers/subreg.py#L251-L255 | def _request_login(self, login, password):
"""Sends Login request"""
return self._request_internal("Login",
login=login,
password=password) | [
"def",
"_request_login",
"(",
"self",
",",
"login",
",",
"password",
")",
":",
"return",
"self",
".",
"_request_internal",
"(",
"\"Login\"",
",",
"login",
"=",
"login",
",",
"password",
"=",
"password",
")"
] | Sends Login request | [
"Sends",
"Login",
"request"
] | python | train | 45.4 |
Jajcus/pyxmpp2 | pyxmpp2/streambase.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L444-L449 | def _send_stream_features(self):
"""Send stream <features/>.
[receiving entity only]"""
self.features = self._make_stream_features()
self._write_element(self.features) | [
"def",
"_send_stream_features",
"(",
"self",
")",
":",
"self",
".",
"features",
"=",
"self",
".",
"_make_stream_features",
"(",
")",
"self",
".",
"_write_element",
"(",
"self",
".",
"features",
")"
] | Send stream <features/>.
[receiving entity only] | [
"Send",
"stream",
"<features",
"/",
">",
"."
] | python | valid | 32.5 |
ungarj/mapchete | mapchete/config.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L507-L521 | def bounds_at_zoom(self, zoom=None):
"""
Return process bounds for zoom level.
Parameters
----------
zoom : integer or list
Returns
-------
process bounds : tuple
left, bottom, right, top
"""
return () if self.area_at_zoom(zoo... | [
"def",
"bounds_at_zoom",
"(",
"self",
",",
"zoom",
"=",
"None",
")",
":",
"return",
"(",
")",
"if",
"self",
".",
"area_at_zoom",
"(",
"zoom",
")",
".",
"is_empty",
"else",
"Bounds",
"(",
"*",
"self",
".",
"area_at_zoom",
"(",
"zoom",
")",
".",
"bound... | Return process bounds for zoom level.
Parameters
----------
zoom : integer or list
Returns
-------
process bounds : tuple
left, bottom, right, top | [
"Return",
"process",
"bounds",
"for",
"zoom",
"level",
"."
] | python | valid | 25 |
raiden-network/raiden-contracts | raiden_contracts/utils/signature.py | https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/utils/signature.py#L25-L32 | def private_key_to_address(private_key: Union[str, bytes]) -> ChecksumAddress:
""" Converts a private key to an Ethereum address. """
if isinstance(private_key, str):
private_key_bytes = to_bytes(hexstr=private_key)
else:
private_key_bytes = private_key
pk = PrivateKey(private_key_bytes)... | [
"def",
"private_key_to_address",
"(",
"private_key",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"ChecksumAddress",
":",
"if",
"isinstance",
"(",
"private_key",
",",
"str",
")",
":",
"private_key_bytes",
"=",
"to_bytes",
"(",
"hexstr",
"=",
"priv... | Converts a private key to an Ethereum address. | [
"Converts",
"a",
"private",
"key",
"to",
"an",
"Ethereum",
"address",
"."
] | python | train | 45.125 |
skoczen/will | will/plugins/help/help.py | https://github.com/skoczen/will/blob/778a6a78571e3ae4656b307f9e5d4d184b25627d/will/plugins/help/help.py#L8-L31 | def help(self, message, plugin=None):
"""help: the normal help you're reading."""
# help_data = self.load("help_files")
selected_modules = help_modules = self.load("help_modules")
self.say("Sure thing, %s." % message.sender.handle)
help_text = "Here's what I know how to do:"
... | [
"def",
"help",
"(",
"self",
",",
"message",
",",
"plugin",
"=",
"None",
")",
":",
"# help_data = self.load(\"help_files\")",
"selected_modules",
"=",
"help_modules",
"=",
"self",
".",
"load",
"(",
"\"help_modules\"",
")",
"self",
".",
"say",
"(",
"\"Sure thing, ... | help: the normal help you're reading. | [
"help",
":",
"the",
"normal",
"help",
"you",
"re",
"reading",
"."
] | python | train | 42.083333 |
chaoss/grimoirelab-perceval | perceval/backends/core/phabricator.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/phabricator.py#L227-L232 | def _init_client(self, from_archive=False):
"""Init client"""
return ConduitClient(self.url, self.api_token,
self.max_retries, self.sleep_time,
self.archive, from_archive) | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"ConduitClient",
"(",
"self",
".",
"url",
",",
"self",
".",
"api_token",
",",
"self",
".",
"max_retries",
",",
"self",
".",
"sleep_time",
",",
"self",
".",
"archiv... | Init client | [
"Init",
"client"
] | python | test | 40.166667 |
bokeh/bokeh | bokeh/core/property/container.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/container.py#L124-L134 | def wrap(cls, value):
''' Some property types need to wrap their values in special containers, etc.
'''
if isinstance(value, list):
if isinstance(value, PropertyValueList):
return value
else:
return PropertyValueList(value)
else:
... | [
"def",
"wrap",
"(",
"cls",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PropertyValueList",
")",
":",
"return",
"value",
"else",
":",
"return",
"PropertyValueList",
"(",
"value",... | Some property types need to wrap their values in special containers, etc. | [
"Some",
"property",
"types",
"need",
"to",
"wrap",
"their",
"values",
"in",
"special",
"containers",
"etc",
"."
] | python | train | 30.272727 |
gem/oq-engine | openquake/hazardlib/gsim/si_midorikawa_1999.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/si_midorikawa_1999.py#L238-L251 | def _get_stddevs(self, stddev_types, rrup):
"""
Return standard deviations as defined in equation 3.5.5-2 page 151
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
std = np.zeros_like(rrup)
std[rru... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"stddev_types",
",",
"rrup",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_types",
")",
"std",
"=",
"np",
".",
"zeros_like",
... | Return standard deviations as defined in equation 3.5.5-2 page 151 | [
"Return",
"standard",
"deviations",
"as",
"defined",
"in",
"equation",
"3",
".",
"5",
".",
"5",
"-",
"2",
"page",
"151"
] | python | train | 42.357143 |
sdispater/orator | orator/orm/relations/belongs_to.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to.py#L77-L85 | def add_eager_constraints(self, models):
"""
Set the constraints for an eager load of the relation.
:type models: list
"""
key = "%s.%s" % (self._related.get_table(), self._other_key)
self._query.where_in(key, self._get_eager_model_keys(models)) | [
"def",
"add_eager_constraints",
"(",
"self",
",",
"models",
")",
":",
"key",
"=",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"_related",
".",
"get_table",
"(",
")",
",",
"self",
".",
"_other_key",
")",
"self",
".",
"_query",
".",
"where_in",
"(",
"key",
",",
... | Set the constraints for an eager load of the relation.
:type models: list | [
"Set",
"the",
"constraints",
"for",
"an",
"eager",
"load",
"of",
"the",
"relation",
"."
] | python | train | 31.888889 |
pkkid/python-plexapi | plexapi/utils.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L322-L346 | def getMyPlexAccount(opts=None): # pragma: no cover
""" Helper function tries to get a MyPlex Account instance by checking
the the following locations for a username and password. This is
useful to create user-friendly command line tools.
1. command-line options (opts).
2. environme... | [
"def",
"getMyPlexAccount",
"(",
"opts",
"=",
"None",
")",
":",
"# pragma: no cover",
"from",
"plexapi",
"import",
"CONFIG",
"from",
"plexapi",
".",
"myplex",
"import",
"MyPlexAccount",
"# 1. Check command-line options",
"if",
"opts",
"and",
"opts",
".",
"username",
... | Helper function tries to get a MyPlex Account instance by checking
the the following locations for a username and password. This is
useful to create user-friendly command line tools.
1. command-line options (opts).
2. environment variables and config.ini
3. Prompt on the command ... | [
"Helper",
"function",
"tries",
"to",
"get",
"a",
"MyPlex",
"Account",
"instance",
"by",
"checking",
"the",
"the",
"following",
"locations",
"for",
"a",
"username",
"and",
"password",
".",
"This",
"is",
"useful",
"to",
"create",
"user",
"-",
"friendly",
"comm... | python | train | 51.88 |
gbowerman/azurerm | docs/py2md.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/docs/py2md.py#L7-L30 | def extract_code(end_mark, current_str, str_array, line_num):
'''Extract a multi-line string from a string array, up to a specified end marker.
Args:
end_mark (str): The end mark string to match for.
current_str (str): The first line of the string array.
str_array (list)... | [
"def",
"extract_code",
"(",
"end_mark",
",",
"current_str",
",",
"str_array",
",",
"line_num",
")",
":",
"if",
"end_mark",
"not",
"in",
"current_str",
":",
"reached_end",
"=",
"False",
"line_num",
"+=",
"1",
"while",
"reached_end",
"is",
"False",
":",
"next_... | Extract a multi-line string from a string array, up to a specified end marker.
Args:
end_mark (str): The end mark string to match for.
current_str (str): The first line of the string array.
str_array (list): An array of strings (lines).
line_num (int): The curren... | [
"Extract",
"a",
"multi",
"-",
"line",
"string",
"from",
"a",
"string",
"array",
"up",
"to",
"a",
"specified",
"end",
"marker",
"."
] | python | train | 37.625 |
SmokinCaterpillar/pypet | pypet/storageservice.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L4935-L5023 | def _prm_read_table(self, table_or_group, full_name):
"""Reads a non-nested PyTables table column by column and created a new ObjectTable for
the loaded data.
:param table_or_group:
PyTables table to read from or a group containing subtables.
:param full_name:
... | [
"def",
"_prm_read_table",
"(",
"self",
",",
"table_or_group",
",",
"full_name",
")",
":",
"try",
":",
"result_table",
"=",
"None",
"if",
"self",
".",
"_all_get_from_attrs",
"(",
"table_or_group",
",",
"HDF5StorageService",
".",
"SPLIT_TABLE",
")",
":",
"table_na... | Reads a non-nested PyTables table column by column and created a new ObjectTable for
the loaded data.
:param table_or_group:
PyTables table to read from or a group containing subtables.
:param full_name:
Full name of the parameter or result whose data is to be loaded
... | [
"Reads",
"a",
"non",
"-",
"nested",
"PyTables",
"table",
"column",
"by",
"column",
"and",
"created",
"a",
"new",
"ObjectTable",
"for",
"the",
"loaded",
"data",
"."
] | python | test | 40.382022 |
GoogleCloudPlatform/google-cloud-datastore | python/demos/todos/todos.py | https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/python/demos/todos/todos.py#L173-L181 | def save(self):
"""Update or insert a Todo item."""
req = datastore.CommitRequest()
req.mode = datastore.CommitRequest.NON_TRANSACTIONAL
req.mutations.add().upsert.CopyFrom(self.to_proto())
resp = datastore.commit(req)
if not self.id:
self.id = resp.mutation_results[0].key.path[-1].id
... | [
"def",
"save",
"(",
"self",
")",
":",
"req",
"=",
"datastore",
".",
"CommitRequest",
"(",
")",
"req",
".",
"mode",
"=",
"datastore",
".",
"CommitRequest",
".",
"NON_TRANSACTIONAL",
"req",
".",
"mutations",
".",
"add",
"(",
")",
".",
"upsert",
".",
"Cop... | Update or insert a Todo item. | [
"Update",
"or",
"insert",
"a",
"Todo",
"item",
"."
] | python | train | 35.888889 |
Kortemme-Lab/klab | klab/stats/dataframe.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L372-L425 | def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None):
'''Returns summary analysis from the dataframe as a DataTable object.
DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful fo... | [
"def",
"tabulate",
"(",
"self",
",",
"restricted_predicted_column_indices",
"=",
"[",
"]",
",",
"restricted_predicted_column_names",
"=",
"[",
"]",
",",
"dataset_name",
"=",
"None",
")",
":",
"self",
".",
"_analyze",
"(",
")",
"data_series",
"=",
"self",
".",
... | Returns summary analysis from the dataframe as a DataTable object.
DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses.
DataTables can be printed to terminal as a tabular string using their representation functio... | [
"Returns",
"summary",
"analysis",
"from",
"the",
"dataframe",
"as",
"a",
"DataTable",
"object",
".",
"DataTables",
"are",
"wrapped",
"pandas",
"dataframes",
"which",
"can",
"be",
"combined",
"if",
"the",
"have",
"the",
"same",
"width",
".",
"This",
"is",
"us... | python | train | 61.962963 |
Autodesk/aomi | aomi/render.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/render.py#L161-L200 | def aws(client, path, opt):
"""Renders a shell environment snippet with AWS information"""
try:
creds = client.read(path)
except (hvac.exceptions.InternalServerError) as vault_exception:
# this is how old vault behaves
if vault_exception.errors[0].find('unsupported path') > 0:
... | [
"def",
"aws",
"(",
"client",
",",
"path",
",",
"opt",
")",
":",
"try",
":",
"creds",
"=",
"client",
".",
"read",
"(",
"path",
")",
"except",
"(",
"hvac",
".",
"exceptions",
".",
"InternalServerError",
")",
"as",
"vault_exception",
":",
"# this is how old... | Renders a shell environment snippet with AWS information | [
"Renders",
"a",
"shell",
"environment",
"snippet",
"with",
"AWS",
"information"
] | python | train | 37.425 |
pyviz/holoviews | holoviews/core/data/multipath.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/multipath.py#L305-L332 | def split(cls, dataset, start, end, datatype, **kwargs):
"""
Splits a multi-interface Dataset into regular Datasets using
regular tabular interfaces.
"""
objs = []
if datatype is None:
for d in dataset.data[start: end]:
objs.append(dataset.clon... | [
"def",
"split",
"(",
"cls",
",",
"dataset",
",",
"start",
",",
"end",
",",
"datatype",
",",
"*",
"*",
"kwargs",
")",
":",
"objs",
"=",
"[",
"]",
"if",
"datatype",
"is",
"None",
":",
"for",
"d",
"in",
"dataset",
".",
"data",
"[",
"start",
":",
"... | Splits a multi-interface Dataset into regular Datasets using
regular tabular interfaces. | [
"Splits",
"a",
"multi",
"-",
"interface",
"Dataset",
"into",
"regular",
"Datasets",
"using",
"regular",
"tabular",
"interfaces",
"."
] | python | train | 36.107143 |
totalgood/pugnlp | src/pugnlp/util.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L732-L770 | def fuzzy_get_value(obj, approximate_key, default=None, **kwargs):
""" Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dic... | [
"def",
"fuzzy_get_value",
"(",
"obj",
",",
"approximate_key",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dict_obj",
"=",
"OrderedDict",
"(",
"obj",
")",
"try",
":",
"return",
"dict_obj",
"[",
"list",
"(",
"dict_obj",
".",
"keys",
... | Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dicts
Arguments:
obj (dict-like): object to run the get method on u... | [
"Like",
"fuzzy_get",
"but",
"assume",
"the",
"obj",
"is",
"dict",
"-",
"like",
"and",
"return",
"the",
"value",
"without",
"the",
"key"
] | python | train | 54.538462 |
bcbio/bcbio-nextgen | scripts/utils/hydra_to_vcf.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/hydra_to_vcf.py#L233-L243 | def _calculate_cluster_distance(end_iter):
"""Compute allowed distance for clustering based on end confidence intervals.
"""
out = []
sizes = []
for x in end_iter:
out.append(x)
sizes.append(x.end1 - x.start1)
sizes.append(x.end2 - x.start2)
distance = sum(sizes) // len(s... | [
"def",
"_calculate_cluster_distance",
"(",
"end_iter",
")",
":",
"out",
"=",
"[",
"]",
"sizes",
"=",
"[",
"]",
"for",
"x",
"in",
"end_iter",
":",
"out",
".",
"append",
"(",
"x",
")",
"sizes",
".",
"append",
"(",
"x",
".",
"end1",
"-",
"x",
".",
"... | Compute allowed distance for clustering based on end confidence intervals. | [
"Compute",
"allowed",
"distance",
"for",
"clustering",
"based",
"on",
"end",
"confidence",
"intervals",
"."
] | python | train | 30.909091 |
ranaroussi/pywallet | pywallet/utils/bip32.py | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L177-L188 | def create_new_address_for_user(self, user_id):
"""Create a new bitcoin address to accept payments for a User.
This is a convenience wrapper around `get_child` that helps you do
the right thing. This method always creates a public, non-prime
address that can be generated from a BIP32 pu... | [
"def",
"create_new_address_for_user",
"(",
"self",
",",
"user_id",
")",
":",
"max_id",
"=",
"0x80000000",
"if",
"user_id",
"<",
"0",
"or",
"user_id",
">",
"max_id",
":",
"raise",
"ValueError",
"(",
"\"Invalid UserID. Must be between 0 and %s\"",
"%",
"max_id",
")"... | Create a new bitcoin address to accept payments for a User.
This is a convenience wrapper around `get_child` that helps you do
the right thing. This method always creates a public, non-prime
address that can be generated from a BIP32 public key on an
insecure server. | [
"Create",
"a",
"new",
"bitcoin",
"address",
"to",
"accept",
"payments",
"for",
"a",
"User",
"."
] | python | train | 49.583333 |
gmichaeljaison/cv-utils | cv_utils/img_utils.py | https://github.com/gmichaeljaison/cv-utils/blob/a8251c870165a7428d8c468a6436aa41d0cf7c09/cv_utils/img_utils.py#L160-L174 | def add_rect(img, box, color=None, thickness=1):
"""
Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image
"""
if color is... | [
"def",
"add_rect",
"(",
"img",
",",
"box",
",",
"color",
"=",
"None",
",",
"thickness",
"=",
"1",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"COL_GRAY",
"box",
"=",
"box",
".",
"to_int",
"(",
")",
"cv",
".",
"rectangle",
"(",
"img"... | Draws a bounding box inside the image.
:param img: Input image
:param box: Box object that defines the bounding box.
:param color: Color of the box
:param thickness: Thickness of line
:return: Rectangle added image | [
"Draws",
"a",
"bounding",
"box",
"inside",
"the",
"image",
"."
] | python | train | 29.133333 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/core_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L5571-L5595 | def create_namespaced_config_map(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_config_map # noqa: E501
create a ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | [
"def",
"create_namespaced_config_map",
"(",
"self",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"retu... | create_namespaced_config_map # noqa: E501
create a ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_config_map(namespace, body, async_req=True)
>>... | [
"create_namespaced_config_map",
"#",
"noqa",
":",
"E501"
] | python | train | 61.4 |
hazelcast/hazelcast-python-client | hazelcast/proxy/transactional_set.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_set.py#L21-L29 | def remove(self, item):
"""
Transactional implementation of :func:`Set.remove(item) <hazelcast.proxy.set.Set.remove>`
:param item: (object), the specified item to be deleted.
:return: (bool), ``true`` if item is remove successfully, ``false`` otherwise.
"""
check_not_non... | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"item can't be none\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"transactional_set_remove_codec",
",",
"item",
"=",
"self",
".",
"_to_data",
"(",
"item",
")",... | Transactional implementation of :func:`Set.remove(item) <hazelcast.proxy.set.Set.remove>`
:param item: (object), the specified item to be deleted.
:return: (bool), ``true`` if item is remove successfully, ``false`` otherwise. | [
"Transactional",
"implementation",
"of",
":",
"func",
":",
"Set",
".",
"remove",
"(",
"item",
")",
"<hazelcast",
".",
"proxy",
".",
"set",
".",
"Set",
".",
"remove",
">"
] | python | train | 48.222222 |
koriakin/binflakes | binflakes/types/word.py | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/types/word.py#L321-L326 | def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger.
"""
self._check_match(other)
return self.to_sint() > other.to_sint() | [
"def",
"sgt",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_check_match",
"(",
"other",
")",
"return",
"self",
".",
"to_sint",
"(",
")",
">",
"other",
".",
"to_sint",
"(",
")"
] | Compares two equal-sized BinWords, treating them as signed
integers, and returning True if the first is bigger. | [
"Compares",
"two",
"equal",
"-",
"sized",
"BinWords",
"treating",
"them",
"as",
"signed",
"integers",
"and",
"returning",
"True",
"if",
"the",
"first",
"is",
"bigger",
"."
] | python | train | 40 |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L201-L218 | def get_authorisation_url(self, reset=False):
""" Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned.""... | [
"def",
"get_authorisation_url",
"(",
"self",
",",
"reset",
"=",
"False",
")",
":",
"if",
"reset",
":",
"self",
".",
"auth_url",
"=",
"None",
"if",
"not",
"self",
".",
"auth_url",
":",
"try",
":",
"oauth",
"=",
"OAuth2Session",
"(",
"self",
".",
"client... | Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned. | [
"Initialises",
"the",
"OAuth2",
"Process",
"by",
"asking",
"the",
"auth",
"server",
"for",
"a",
"login",
"URL",
".",
"Once",
"called",
"the",
"user",
"can",
"login",
"by",
"being",
"redirected",
"to",
"the",
"url",
"returned",
"by",
"this",
"function",
"."... | python | train | 43.611111 |
google/grr | grr/core/grr_response_core/lib/rdfvalues/standard.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/standard.py#L33-L38 | def Search(self, text):
"""Search the text for our value."""
if isinstance(text, rdfvalue.RDFString):
text = str(text)
return self._regex.search(text) | [
"def",
"Search",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"rdfvalue",
".",
"RDFString",
")",
":",
"text",
"=",
"str",
"(",
"text",
")",
"return",
"self",
".",
"_regex",
".",
"search",
"(",
"text",
")"
] | Search the text for our value. | [
"Search",
"the",
"text",
"for",
"our",
"value",
"."
] | python | train | 27.333333 |
nathforge/pydentifier | src/pydentifier/__init__.py | https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L32-L51 | def upper_underscore(string, prefix='', suffix=''):
"""
Generate an underscore-separated upper-case identifier.
Useful for constants.
Takes a string, prefix, and optional suffix.
`prefix` can be set to `''`, though be careful - without a prefix, the
function will throw `InvalidIdentifier` when... | [
"def",
"upper_underscore",
"(",
"string",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
":",
"return",
"require_valid",
"(",
"append_underscore_if_keyword",
"(",
"'_'",
".",
"join",
"(",
"word",
".",
"upper",
"(",
")",
"for",
"word",
"in",
"en... | Generate an underscore-separated upper-case identifier.
Useful for constants.
Takes a string, prefix, and optional suffix.
`prefix` can be set to `''`, though be careful - without a prefix, the
function will throw `InvalidIdentifier` when your string starts with a
number.
Example:
>>>... | [
"Generate",
"an",
"underscore",
"-",
"separated",
"upper",
"-",
"case",
"identifier",
".",
"Useful",
"for",
"constants",
"."
] | python | train | 30.55 |
unfoldingWord-dev/python-gogs-client | gogs_client/interface.py | https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L554-L565 | def remove_repo_from_team(self, auth, team_id, repo_name):
"""
Remove repo from team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str repo_name: Name of the repo to be removed from the team
:raises Netw... | [
"def",
"remove_repo_from_team",
"(",
"self",
",",
"auth",
",",
"team_id",
",",
"repo_name",
")",
":",
"url",
"=",
"\"/admin/teams/{t}/repos/{r}\"",
".",
"format",
"(",
"t",
"=",
"team_id",
",",
"r",
"=",
"repo_name",
")",
"self",
".",
"delete",
"(",
"url",... | Remove repo from team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str repo_name: Name of the repo to be removed from the team
:raises NetworkFailure: if there is an error communicating with the server
:raises ... | [
"Remove",
"repo",
"from",
"team",
"."
] | python | train | 46.25 |
swharden/SWHLab | doc/oldcode/swhlab/core/plot.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/plot.py#L209-L273 | def sweep(ABF,sweep=None,rainbow=True,alpha=None,protocol=False,color='b',
continuous=False,offsetX=0,offsetY=0,minutes=False,
decimate=None,newFigure=False):
"""
Load a particular sweep then plot it.
If sweep is None or False, just plot current dataX/dataY.
If rainbow, it'... | [
"def",
"sweep",
"(",
"ABF",
",",
"sweep",
"=",
"None",
",",
"rainbow",
"=",
"True",
",",
"alpha",
"=",
"None",
",",
"protocol",
"=",
"False",
",",
"color",
"=",
"'b'",
",",
"continuous",
"=",
"False",
",",
"offsetX",
"=",
"0",
",",
"offsetY",
"=",
... | Load a particular sweep then plot it.
If sweep is None or False, just plot current dataX/dataY.
If rainbow, it'll make it color coded prettily. | [
"Load",
"a",
"particular",
"sweep",
"then",
"plot",
"it",
".",
"If",
"sweep",
"is",
"None",
"or",
"False",
"just",
"plot",
"current",
"dataX",
"/",
"dataY",
".",
"If",
"rainbow",
"it",
"ll",
"make",
"it",
"color",
"coded",
"prettily",
"."
] | python | valid | 29.446154 |
davidchall/topas2numpy | topas2numpy/binned.py | https://github.com/davidchall/topas2numpy/blob/db751dc95c57e530f890118fed407611dbbbdcbc/topas2numpy/binned.py#L103-L157 | def _read_header(self, header_str):
"""Reads metadata from the header."""
# regular expressions
re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?'
re_uint = '\d+'
re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] '
re_binning += 'of (?P<binwidth>' + re_float + ')... | [
"def",
"_read_header",
"(",
"self",
",",
"header_str",
")",
":",
"# regular expressions",
"re_float",
"=",
"'[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?'",
"re_uint",
"=",
"'\\d+'",
"re_binning",
"=",
"'{d} in (?P<nbins>'",
"+",
"re_uint",
"+",
"') bin[ s] '",
"re_binni... | Reads metadata from the header. | [
"Reads",
"metadata",
"from",
"the",
"header",
"."
] | python | train | 34.109091 |
aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L89-L101 | def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | [
"def",
"csv_to_numpy",
"(",
"string_like",
",",
"dtype",
"=",
"None",
")",
":",
"# type: (str) -> np.array",
"stream",
"=",
"StringIO",
"(",
"string_like",
")",
"return",
"np",
".",
"genfromtxt",
"(",
"stream",
",",
"dtype",
"=",
"dtype",
",",
"delimiter",
"... | Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only be used to
... | [
"Convert",
"a",
"CSV",
"object",
"to",
"a",
"numpy",
"array",
"."
] | python | train | 48.769231 |
theislab/scanpy | scanpy/tools/_paga.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/tools/_paga.py#L350-L371 | def paga_expression_entropies(adata) -> List[float]:
"""Compute the median expression entropy for each node-group.
Parameters
----------
adata : AnnData
Annotated data matrix.
Returns
-------
Entropies of median expressions for each node.
"""
from scipy.stats import entropy... | [
"def",
"paga_expression_entropies",
"(",
"adata",
")",
"->",
"List",
"[",
"float",
"]",
":",
"from",
"scipy",
".",
"stats",
"import",
"entropy",
"groups_order",
",",
"groups_masks",
"=",
"utils",
".",
"select_groups",
"(",
"adata",
",",
"key",
"=",
"adata",
... | Compute the median expression entropy for each node-group.
Parameters
----------
adata : AnnData
Annotated data matrix.
Returns
-------
Entropies of median expressions for each node. | [
"Compute",
"the",
"median",
"expression",
"entropy",
"for",
"each",
"node",
"-",
"group",
"."
] | python | train | 32.772727 |
adafruit/Adafruit_CircuitPython_framebuf | adafruit_framebuf.py | https://github.com/adafruit/Adafruit_CircuitPython_framebuf/blob/b9f62c4b71efa963150f9c5a0284b61c7add9d02/adafruit_framebuf.py#L103-L107 | def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | [
"def",
"get_pixel",
"(",
"framebuf",
",",
"x",
",",
"y",
")",
":",
"index",
"=",
"(",
"y",
">>",
"3",
")",
"*",
"framebuf",
".",
"stride",
"+",
"x",
"offset",
"=",
"y",
"&",
"0x07",
"return",
"(",
"framebuf",
".",
"buf",
"[",
"index",
"]",
">>"... | Get the color of a given pixel | [
"Get",
"the",
"color",
"of",
"a",
"given",
"pixel"
] | python | train | 39.6 |
buriburisuri/sugartensor | sugartensor/sg_main.py | https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_main.py#L632-L640 | def sg_arg():
r"""Gets current command line options
Returns:
tf.sg_opt instance that is updated with current commandd line options.
"""
if not tf.app.flags.FLAGS.__dict__['__parsed']:
tf.app.flags.FLAGS._parse_flags()
return tf.sg_opt(tf.app.flags.FLAGS.__dict__['__flags']) | [
"def",
"sg_arg",
"(",
")",
":",
"if",
"not",
"tf",
".",
"app",
".",
"flags",
".",
"FLAGS",
".",
"__dict__",
"[",
"'__parsed'",
"]",
":",
"tf",
".",
"app",
".",
"flags",
".",
"FLAGS",
".",
"_parse_flags",
"(",
")",
"return",
"tf",
".",
"sg_opt",
"... | r"""Gets current command line options
Returns:
tf.sg_opt instance that is updated with current commandd line options. | [
"r",
"Gets",
"current",
"command",
"line",
"options"
] | python | train | 33.444444 |
rigetti/pyquil | pyquil/reference_simulator.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/reference_simulator.py#L188-L196 | def do_gate(self, gate: Gate) -> 'AbstractQuantumSimulator':
"""
Perform a gate.
:return: ``self`` to support method chaining.
"""
unitary = lifted_gate(gate=gate, n_qubits=self.n_qubits)
self.density = unitary.dot(self.density).dot(np.conj(unitary).T)
return sel... | [
"def",
"do_gate",
"(",
"self",
",",
"gate",
":",
"Gate",
")",
"->",
"'AbstractQuantumSimulator'",
":",
"unitary",
"=",
"lifted_gate",
"(",
"gate",
"=",
"gate",
",",
"n_qubits",
"=",
"self",
".",
"n_qubits",
")",
"self",
".",
"density",
"=",
"unitary",
".... | Perform a gate.
:return: ``self`` to support method chaining. | [
"Perform",
"a",
"gate",
"."
] | python | train | 34.777778 |
pallets/werkzeug | src/werkzeug/debug/tbtools.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/tbtools.py#L260-L265 | def filter_hidden_frames(self):
"""Remove the frames according to the paste spec."""
for group in self.groups:
group.filter_hidden_frames()
self.frames[:] = [frame for group in self.groups for frame in group.frames] | [
"def",
"filter_hidden_frames",
"(",
"self",
")",
":",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"group",
".",
"filter_hidden_frames",
"(",
")",
"self",
".",
"frames",
"[",
":",
"]",
"=",
"[",
"frame",
"for",
"group",
"in",
"self",
".",
"groups"... | Remove the frames according to the paste spec. | [
"Remove",
"the",
"frames",
"according",
"to",
"the",
"paste",
"spec",
"."
] | python | train | 41.166667 |
noahbenson/pimms | pimms/calculation.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L781-L790 | def plan_tr(p, *args, **kwargs):
'''
plan_tr(p, ...) yields a copy of plan p in which the afferent and efferent values of its
functions have been translated. The translation is found from merging the list of 0 or more
dictionary arguments given left-to-right followed by the keyword arguments. If the... | [
"def",
"plan_tr",
"(",
"p",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_plan",
"(",
"p",
")",
":",
"p",
"=",
"plan",
"(",
"p",
")",
"return",
"p",
".",
"tr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | plan_tr(p, ...) yields a copy of plan p in which the afferent and efferent values of its
functions have been translated. The translation is found from merging the list of 0 or more
dictionary arguments given left-to-right followed by the keyword arguments. If the plan that
is given is not a plan objec... | [
"plan_tr",
"(",
"p",
"...",
")",
"yields",
"a",
"copy",
"of",
"plan",
"p",
"in",
"which",
"the",
"afferent",
"and",
"efferent",
"values",
"of",
"its",
"functions",
"have",
"been",
"translated",
".",
"The",
"translation",
"is",
"found",
"from",
"merging",
... | python | train | 49.5 |
craffel/mir_eval | mir_eval/transcription.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/transcription.py#L263-L333 | def match_note_onsets(ref_intervals, est_intervals, onset_tolerance=0.05,
strict=False):
"""Compute a maximum matching between reference and estimated notes,
only taking note onsets into account.
Given two note sequences represented by ``ref_intervals`` and
``est_intervals`` (see ... | [
"def",
"match_note_onsets",
"(",
"ref_intervals",
",",
"est_intervals",
",",
"onset_tolerance",
"=",
"0.05",
",",
"strict",
"=",
"False",
")",
":",
"# set the comparison function",
"if",
"strict",
":",
"cmp_func",
"=",
"np",
".",
"less",
"else",
":",
"cmp_func",... | Compute a maximum matching between reference and estimated notes,
only taking note onsets into account.
Given two note sequences represented by ``ref_intervals`` and
``est_intervals`` (see :func:`mir_eval.io.load_valued_intervals`), we see
the largest set of correspondences ``(i,j)`` such that the onse... | [
"Compute",
"a",
"maximum",
"matching",
"between",
"reference",
"and",
"estimated",
"notes",
"only",
"taking",
"note",
"onsets",
"into",
"account",
"."
] | python | train | 40.380282 |
LordSputnik/mutagen | mutagen/_vorbis.py | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_vorbis.py#L197-L201 | def clear(self):
"""Clear all keys from the comment."""
for i in list(self._internal):
self._internal.remove(i) | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
"in",
"list",
"(",
"self",
".",
"_internal",
")",
":",
"self",
".",
"_internal",
".",
"remove",
"(",
"i",
")"
] | Clear all keys from the comment. | [
"Clear",
"all",
"keys",
"from",
"the",
"comment",
"."
] | python | test | 27.2 |
callsign-viper/Flask-GraphQL-Auth | flask_graphql_auth/decorators.py | https://github.com/callsign-viper/Flask-GraphQL-Auth/blob/27897a6ef81e12f87e9695fbaf6659ff025ae782/flask_graphql_auth/decorators.py#L9-L34 | def decode_jwt(encoded_token, secret, algorithm, identity_claim_key,
user_claims_key):
"""
Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode the JWT
:param algorithm: Algorithm used to encode the JWT
:param iden... | [
"def",
"decode_jwt",
"(",
"encoded_token",
",",
"secret",
",",
"algorithm",
",",
"identity_claim_key",
",",
"user_claims_key",
")",
":",
"# This call verifies the ext, iat, and nbf claims",
"data",
"=",
"jwt",
".",
"decode",
"(",
"encoded_token",
",",
"secret",
",",
... | Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode the JWT
:param algorithm: Algorithm used to encode the JWT
:param identity_claim_key: expected key that contains the identity
:param user_claims_key: expected key that contains the... | [
"Decodes",
"an",
"encoded",
"JWT"
] | python | train | 42.230769 |
jtwhite79/pyemu | pyemu/utils/helpers.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/helpers.py#L3323-L3344 | def setup_smp(self):
""" setup observations from PEST-style SMP file pairs
"""
if self.obssim_smp_pairs is None:
return
if len(self.obssim_smp_pairs) == 2:
if isinstance(self.obssim_smp_pairs[0],str):
self.obssim_smp_pairs = [self.obssim_smp_pairs... | [
"def",
"setup_smp",
"(",
"self",
")",
":",
"if",
"self",
".",
"obssim_smp_pairs",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"self",
".",
"obssim_smp_pairs",
")",
"==",
"2",
":",
"if",
"isinstance",
"(",
"self",
".",
"obssim_smp_pairs",
"[",
"0",
"... | setup observations from PEST-style SMP file pairs | [
"setup",
"observations",
"from",
"PEST",
"-",
"style",
"SMP",
"file",
"pairs"
] | python | train | 49.5 |
ladybug-tools/ladybug | ladybug/wea.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/wea.py#L250-L298 | def from_ashrae_revised_clear_sky(cls, location, monthly_tau_beam,
monthly_tau_diffuse, timestep=1,
is_leap_year=False):
"""Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model")
ASHRAE Revised Clear Skies a... | [
"def",
"from_ashrae_revised_clear_sky",
"(",
"cls",
",",
"location",
",",
"monthly_tau_beam",
",",
"monthly_tau_diffuse",
",",
"timestep",
"=",
"1",
",",
"is_leap_year",
"=",
"False",
")",
":",
"# extract metadata",
"metadata",
"=",
"{",
"'source'",
":",
"location... | Create a wea object representing an ASHRAE Revised Clear Sky ("Tau Model")
ASHRAE Revised Clear Skies are intended to determine peak solar load
and sizing parmeters for HVAC systems. The revised clear sky is
currently the default recommended sky model used to autosize HVAC
systems in E... | [
"Create",
"a",
"wea",
"object",
"representing",
"an",
"ASHRAE",
"Revised",
"Clear",
"Sky",
"(",
"Tau",
"Model",
")"
] | python | train | 52.55102 |
brunato/lograptor | lograptor/core.py | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L562-L578 | def create_dispatcher(self):
"""
Return a dispatcher for configured channels.
"""
before_context = max(self.args.before_context, self.args.context)
after_context = max(self.args.after_context, self.args.context)
if self.args.files_with_match is not None or self.args.coun... | [
"def",
"create_dispatcher",
"(",
"self",
")",
":",
"before_context",
"=",
"max",
"(",
"self",
".",
"args",
".",
"before_context",
",",
"self",
".",
"args",
".",
"context",
")",
"after_context",
"=",
"max",
"(",
"self",
".",
"args",
".",
"after_context",
... | Return a dispatcher for configured channels. | [
"Return",
"a",
"dispatcher",
"for",
"configured",
"channels",
"."
] | python | train | 49.117647 |
happyleavesaoc/aoc-mgz | mgz/recorded_game/__init__.py | https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L124-L132 | def _num_players(self):
"""Compute number of players, both human and computer."""
self._player_num = 0
self._computer_num = 0
for player in self._header.scenario.game_settings.player_info:
if player.type == 'human':
self._player_num += 1
elif playe... | [
"def",
"_num_players",
"(",
"self",
")",
":",
"self",
".",
"_player_num",
"=",
"0",
"self",
".",
"_computer_num",
"=",
"0",
"for",
"player",
"in",
"self",
".",
"_header",
".",
"scenario",
".",
"game_settings",
".",
"player_info",
":",
"if",
"player",
"."... | Compute number of players, both human and computer. | [
"Compute",
"number",
"of",
"players",
"both",
"human",
"and",
"computer",
"."
] | python | train | 41.444444 |
sosreport/sos | sos/policies/__init__.py | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L591-L599 | def validate_plugin(self, plugin_class, experimental=False):
"""
Verifies that the plugin_class should execute under this policy
"""
valid_subclasses = [IndependentPlugin] + self.valid_subclasses
if experimental:
valid_subclasses += [ExperimentalPlugin]
return... | [
"def",
"validate_plugin",
"(",
"self",
",",
"plugin_class",
",",
"experimental",
"=",
"False",
")",
":",
"valid_subclasses",
"=",
"[",
"IndependentPlugin",
"]",
"+",
"self",
".",
"valid_subclasses",
"if",
"experimental",
":",
"valid_subclasses",
"+=",
"[",
"Expe... | Verifies that the plugin_class should execute under this policy | [
"Verifies",
"that",
"the",
"plugin_class",
"should",
"execute",
"under",
"this",
"policy"
] | python | train | 44.444444 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py#L404-L415 | def get_mac_acl_for_intf_input_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_acl_for_intf = ET.Element("get_mac_acl_for_intf")
config = get_mac_acl_for_intf
input = ET.SubElement(get_mac_acl_for_intf, "input")
int... | [
"def",
"get_mac_acl_for_intf_input_interface_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_acl_for_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_mac_acl_for_intf\"",
")",
"config",
"=... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 42.583333 |
google/openhtf | openhtf/plugs/usb/filesync_service.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L367-L387 | def write_message(self, msg, timeout=None):
"""Write an arbitrary message (of one of the types above).
For the host side implementation, this will only ever be a DataMessage, but
it's implemented generically enough here that you could use
FilesyncTransport to implement the device side if you wanted.
... | [
"def",
"write_message",
"(",
"self",
",",
"msg",
",",
"timeout",
"=",
"None",
")",
":",
"replace_dict",
"=",
"{",
"'command'",
":",
"self",
".",
"CMD_TO_WIRE",
"[",
"msg",
".",
"command",
"]",
"}",
"if",
"msg",
".",
"has_data",
":",
"# Swap out data for ... | Write an arbitrary message (of one of the types above).
For the host side implementation, this will only ever be a DataMessage, but
it's implemented generically enough here that you could use
FilesyncTransport to implement the device side if you wanted.
Args:
msg: The message to send, must be o... | [
"Write",
"an",
"arbitrary",
"message",
"(",
"of",
"one",
"of",
"the",
"types",
"above",
")",
"."
] | python | train | 40.095238 |
makearl/tornado-profile | tornado_profile.py | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L75-L109 | def get(self):
"""Return current profiler statistics."""
sort = self.get_argument('sort', 'cum_time')
count = self.get_argument('count', 20)
strip_dirs = self.get_argument('strip_dirs', True)
error = ''
sorts = ('num_calls', 'cum_time', 'total_time',
'cu... | [
"def",
"get",
"(",
"self",
")",
":",
"sort",
"=",
"self",
".",
"get_argument",
"(",
"'sort'",
",",
"'cum_time'",
")",
"count",
"=",
"self",
".",
"get_argument",
"(",
"'count'",
",",
"20",
")",
"strip_dirs",
"=",
"self",
".",
"get_argument",
"(",
"'stri... | Return current profiler statistics. | [
"Return",
"current",
"profiler",
"statistics",
"."
] | python | test | 38.742857 |
ngmarchant/oasis | oasis/experiments.py | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L187-L214 | def scores_to_preds(self, threshold, use_probs = True):
"""
use_probs : boolean, default True
if True, use probabilities for predictions, else use scores.
"""
self.threshold = threshold
if use_probs:
if self.probs is None:
raise DataError(... | [
"def",
"scores_to_preds",
"(",
"self",
",",
"threshold",
",",
"use_probs",
"=",
"True",
")",
":",
"self",
".",
"threshold",
"=",
"threshold",
"if",
"use_probs",
":",
"if",
"self",
".",
"probs",
"is",
"None",
":",
"raise",
"DataError",
"(",
"\"Probabilities... | use_probs : boolean, default True
if True, use probabilities for predictions, else use scores. | [
"use_probs",
":",
"boolean",
"default",
"True",
"if",
"True",
"use",
"probabilities",
"for",
"predictions",
"else",
"use",
"scores",
"."
] | python | train | 36.785714 |
ScriptSmith/socialreaper | socialreaper/apis.py | https://github.com/ScriptSmith/socialreaper/blob/87fcc3b74bbed6c4f8e7f49a5f0eb8a616cf38da/socialreaper/apis.py#L471-L498 | def post_comments(self, post_id, after='', order="chronological",
filter="stream", fields=None, **params):
"""
:param post_id:
:param after:
:param order: Can be 'ranked', 'chronological', 'reverse_chronological'
:param filter: Can be 'stream', 'to... | [
"def",
"post_comments",
"(",
"self",
",",
"post_id",
",",
"after",
"=",
"''",
",",
"order",
"=",
"\"chronological\"",
",",
"filter",
"=",
"\"stream\"",
",",
"fields",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"if",
"fields",
":",
"fields",
"=",
... | :param post_id:
:param after:
:param order: Can be 'ranked', 'chronological', 'reverse_chronological'
:param filter: Can be 'stream', 'toplevel'
:param fields: Can be 'id', 'application', 'attachment', 'can_comment',
'can_remove', 'can_hide', 'can_like', 'can_reply_privately... | [
":",
"param",
"post_id",
":",
":",
"param",
"after",
":",
":",
"param",
"order",
":",
"Can",
"be",
"ranked",
"chronological",
"reverse_chronological",
":",
"param",
"filter",
":",
"Can",
"be",
"stream",
"toplevel",
":",
"param",
"fields",
":",
"Can",
"be",... | python | valid | 40.214286 |
manns/pyspread | pyspread/src/gui/grid_panels.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/grid_panels.py#L125-L133 | def OnTogglePlay(self, event):
"""Toggles the video status between play and hold"""
if self.player.get_state() == vlc.State.Playing:
self.player.pause()
else:
self.player.play()
event.Skip() | [
"def",
"OnTogglePlay",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"player",
".",
"get_state",
"(",
")",
"==",
"vlc",
".",
"State",
".",
"Playing",
":",
"self",
".",
"player",
".",
"pause",
"(",
")",
"else",
":",
"self",
".",
"player",
... | Toggles the video status between play and hold | [
"Toggles",
"the",
"video",
"status",
"between",
"play",
"and",
"hold"
] | python | train | 26.666667 |
ouroboroscoding/format-oc-python | FormatOC/__init__.py | https://github.com/ouroboroscoding/format-oc-python/blob/c160b46fe4ff2c92333c776991c712de23991225/FormatOC/__init__.py#L2217-L2228 | def keys(self):
"""Keys
Returns a list of the node names in the parent
Returns:
list
"""
if hasattr(self._nodes, 'iterkeys'):
return self._nodes.keys()
else:
return tuple(self._nodes.keys()) | [
"def",
"keys",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_nodes",
",",
"'iterkeys'",
")",
":",
"return",
"self",
".",
"_nodes",
".",
"keys",
"(",
")",
"else",
":",
"return",
"tuple",
"(",
"self",
".",
"_nodes",
".",
"keys",
"(",
... | Keys
Returns a list of the node names in the parent
Returns:
list | [
"Keys"
] | python | train | 16.833333 |
razor-x/scipy-data_fitting | scipy_data_fitting/fit.py | https://github.com/razor-x/scipy-data_fitting/blob/c756a645da8629699b3f22244bfb7d5d4d88b179/scipy_data_fitting/fit.py#L704-L716 | def computed_fitting_parameters(self):
"""
A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`,
but in each dictionary, the key `value` is added with the fitted value of the quantity.
The reported value is scaled by the inverse prefix.
"""
fit... | [
"def",
"computed_fitting_parameters",
"(",
"self",
")",
":",
"fitted_parameters",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"v",
")",
"in",
"enumerate",
"(",
"self",
".",
"fitting_parameters",
")",
":",
"param",
"=",
"v",
".",
"copy",
"(",
")",
"param",
"["... | A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`,
but in each dictionary, the key `value` is added with the fitted value of the quantity.
The reported value is scaled by the inverse prefix. | [
"A",
"list",
"identical",
"to",
"what",
"is",
"set",
"with",
"scipy_data_fitting",
".",
"Fit",
".",
"fitting_parameters",
"but",
"in",
"each",
"dictionary",
"the",
"key",
"value",
"is",
"added",
"with",
"the",
"fitted",
"value",
"of",
"the",
"quantity",
".",... | python | train | 44.307692 |
bwohlberg/sporco | sporco/dictlrn/prlcnscdl.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L1123-L1132 | def getdict(self, crop=True):
"""Get final dictionary. If ``crop`` is ``True``, apply
:func:`.cnvrep.bcrop` to returned array.
"""
global mp_D_Y0
D = mp_D_Y0
if crop:
D = cr.bcrop(D, self.dstep.cri.dsz, self.dstep.cri.dimN)
return D | [
"def",
"getdict",
"(",
"self",
",",
"crop",
"=",
"True",
")",
":",
"global",
"mp_D_Y0",
"D",
"=",
"mp_D_Y0",
"if",
"crop",
":",
"D",
"=",
"cr",
".",
"bcrop",
"(",
"D",
",",
"self",
".",
"dstep",
".",
"cri",
".",
"dsz",
",",
"self",
".",
"dstep"... | Get final dictionary. If ``crop`` is ``True``, apply
:func:`.cnvrep.bcrop` to returned array. | [
"Get",
"final",
"dictionary",
".",
"If",
"crop",
"is",
"True",
"apply",
":",
"func",
":",
".",
"cnvrep",
".",
"bcrop",
"to",
"returned",
"array",
"."
] | python | train | 29.2 |
angr/angr | angr/state_plugins/heap/heap_freelist.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/heap/heap_freelist.py#L166-L171 | def allocated_chunks(self):
"""
Returns an iterator over all the allocated chunks in the heap.
"""
raise NotImplementedError("%s not implemented for %s" % (self.allocated_chunks.__func__.__name__,
self.__class__.__name__)) | [
"def",
"allocated_chunks",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"%s not implemented for %s\"",
"%",
"(",
"self",
".",
"allocated_chunks",
".",
"__func__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | Returns an iterator over all the allocated chunks in the heap. | [
"Returns",
"an",
"iterator",
"over",
"all",
"the",
"allocated",
"chunks",
"in",
"the",
"heap",
"."
] | python | train | 52.333333 |
tulsawebdevs/django-multi-gtfs | multigtfs/models/base.py | https://github.com/tulsawebdevs/django-multi-gtfs/blob/8c442bfb67e87566c24a7364d8fa0aacd4a0a652/multigtfs/models/base.py#L108-L300 | def import_txt(cls, txt_file, feed, filter_func=None):
'''Import from the GTFS text file'''
# Setup the conversion from GTFS to Django Format
# Conversion functions
def no_convert(value): return value
def date_convert(value): return datetime.strptime(value, '%Y%m%d')
d... | [
"def",
"import_txt",
"(",
"cls",
",",
"txt_file",
",",
"feed",
",",
"filter_func",
"=",
"None",
")",
":",
"# Setup the conversion from GTFS to Django Format",
"# Conversion functions",
"def",
"no_convert",
"(",
"value",
")",
":",
"return",
"value",
"def",
"date_conv... | Import from the GTFS text file | [
"Import",
"from",
"the",
"GTFS",
"text",
"file"
] | python | train | 37.233161 |
osrg/ryu | ryu/controller/handler.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/controller/handler.py#L49-L83 | def set_ev_cls(ev_cls, dispatchers=None):
"""
A decorator for Ryu application to declare an event handler.
Decorated method will become an event handler.
ev_cls is an event class whose instances this RyuApp wants to receive.
dispatchers argument specifies one of the following negotiation phases
... | [
"def",
"set_ev_cls",
"(",
"ev_cls",
",",
"dispatchers",
"=",
"None",
")",
":",
"def",
"_set_ev_cls_dec",
"(",
"handler",
")",
":",
"if",
"'callers'",
"not",
"in",
"dir",
"(",
"handler",
")",
":",
"handler",
".",
"callers",
"=",
"{",
"}",
"for",
"e",
... | A decorator for Ryu application to declare an event handler.
Decorated method will become an event handler.
ev_cls is an event class whose instances this RyuApp wants to receive.
dispatchers argument specifies one of the following negotiation phases
(or a list of them) for which events should be genera... | [
"A",
"decorator",
"for",
"Ryu",
"application",
"to",
"declare",
"an",
"event",
"handler",
"."
] | python | train | 51.342857 |
ranaroussi/pywallet | pywallet/utils/bip32.py | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L190-L249 | def get_child_for_path(self, path):
"""Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or,... | [
"def",
"get_child_for_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"ensure_str",
"(",
"path",
")",
"if",
"not",
"path",
":",
"raise",
"InvalidPathError",
"(",
"\"%s is not a valid path\"",
"%",
"path",
")",
"# Figure out public/private derivation",
"as_... | Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or, in other words, the 10th publicly derived chil... | [
"Get",
"a",
"child",
"for",
"a",
"given",
"path",
"."
] | python | train | 31.75 |
scour-project/scour | scour/scour.py | https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L2754-L2804 | def scourUnitlessLength(length, renderer_workaround=False, is_control_point=False): # length is of a numeric type
"""
Scours the numeric part of a length only. Does not accept units.
This is faster than scourLength on elements guaranteed not to
contain units.
"""
if not isinstance(length, Deci... | [
"def",
"scourUnitlessLength",
"(",
"length",
",",
"renderer_workaround",
"=",
"False",
",",
"is_control_point",
"=",
"False",
")",
":",
"# length is of a numeric type",
"if",
"not",
"isinstance",
"(",
"length",
",",
"Decimal",
")",
":",
"length",
"=",
"getcontext"... | Scours the numeric part of a length only. Does not accept units.
This is faster than scourLength on elements guaranteed not to
contain units. | [
"Scours",
"the",
"numeric",
"part",
"of",
"a",
"length",
"only",
".",
"Does",
"not",
"accept",
"units",
"."
] | python | train | 42.901961 |
smarie/python-valid8 | valid8/validation_lib/collections.py | https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L200-L217 | def is_in(allowed_values # type: Set
):
"""
'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return:
"""
def is_in_allowed_values(x):
if x in a... | [
"def",
"is_in",
"(",
"allowed_values",
"# type: Set",
")",
":",
"def",
"is_in_allowed_values",
"(",
"x",
")",
":",
"if",
"x",
"in",
"allowed_values",
":",
"return",
"True",
"else",
":",
"# raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(... | 'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return: | [
"Values",
"in",
"validation_function",
"generator",
".",
"Returns",
"a",
"validation_function",
"to",
"check",
"that",
"x",
"is",
"in",
"the",
"provided",
"set",
"of",
"allowed",
"values"
] | python | train | 35.666667 |
google/grr | grr/server/grr_response_server/data_store.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/data_store.py#L389-L416 | def QueueQueryAndOwn(self, queue, lease_seconds, limit, timestamp):
"""Returns a list of Tasks leased for a certain time.
Args:
queue: The queue to query from.
lease_seconds: The tasks will be leased for this long.
limit: Number of values to fetch.
timestamp: Range of times for consider... | [
"def",
"QueueQueryAndOwn",
"(",
"self",
",",
"queue",
",",
"lease_seconds",
",",
"limit",
",",
"timestamp",
")",
":",
"# Do the real work in a transaction",
"try",
":",
"lock",
"=",
"DB",
".",
"LockRetryWrapper",
"(",
"queue",
",",
"lease_time",
"=",
"lease_seco... | Returns a list of Tasks leased for a certain time.
Args:
queue: The queue to query from.
lease_seconds: The tasks will be leased for this long.
limit: Number of values to fetch.
timestamp: Range of times for consideration.
Returns:
A list of GrrMessage() objects leased. | [
"Returns",
"a",
"list",
"of",
"Tasks",
"leased",
"for",
"a",
"certain",
"time",
"."
] | python | train | 34.321429 |
Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L493-L498 | def _rand_init(x_bounds, x_types, selection_num_starting_points):
'''
Random sample some init seed within bounds.
'''
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | [
"def",
"_rand_init",
"(",
"x_bounds",
",",
"x_types",
",",
"selection_num_starting_points",
")",
":",
"return",
"[",
"lib_data",
".",
"rand",
"(",
"x_bounds",
",",
"x_types",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"selection_num_starting_points",
")",
... | Random sample some init seed within bounds. | [
"Random",
"sample",
"some",
"init",
"seed",
"within",
"bounds",
"."
] | python | train | 40.166667 |
pypa/setuptools | setuptools/config.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/config.py#L68-L77 | def _get_option(target_obj, key):
"""
Given a target object and option key, get that option from
the target object, either through a get_{key} method or
from an attribute directly.
"""
getter_name = 'get_{key}'.format(**locals())
by_attribute = functools.partial(getattr, target_obj, key)
... | [
"def",
"_get_option",
"(",
"target_obj",
",",
"key",
")",
":",
"getter_name",
"=",
"'get_{key}'",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"by_attribute",
"=",
"functools",
".",
"partial",
"(",
"getattr",
",",
"target_obj",
",",
"key",
")",... | Given a target object and option key, get that option from
the target object, either through a get_{key} method or
from an attribute directly. | [
"Given",
"a",
"target",
"object",
"and",
"option",
"key",
"get",
"that",
"option",
"from",
"the",
"target",
"object",
"either",
"through",
"a",
"get_",
"{",
"key",
"}",
"method",
"or",
"from",
"an",
"attribute",
"directly",
"."
] | python | train | 38.7 |
senaite/senaite.core | bika/lims/browser/worksheet/views/referencesamples.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/worksheet/views/referencesamples.py#L229-L258 | def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | [
"def",
"folderitem",
"(",
"self",
",",
"obj",
",",
"item",
",",
"index",
")",
":",
"item",
"=",
"super",
"(",
"ReferenceSamplesView",
",",
"self",
")",
".",
"folderitem",
"(",
"obj",
",",
"item",
",",
"index",
")",
"# ensure we have an object and not a brain... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current i... | [
"Service",
"triggered",
"each",
"time",
"an",
"item",
"is",
"iterated",
"in",
"folderitems",
"."
] | python | train | 35.8 |
nathan-hoad/outbox | outbox.py | https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L219-L235 | def add_attachment(message, attachment, rfc2231=True):
'''Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance.
'''
data = attachment.read()
part = MIMEBase('application', 'octet-stream')
part.set_payloa... | [
"def",
"add_attachment",
"(",
"message",
",",
"attachment",
",",
"rfc2231",
"=",
"True",
")",
":",
"data",
"=",
"attachment",
".",
"read",
"(",
")",
"part",
"=",
"MIMEBase",
"(",
"'application'",
",",
"'octet-stream'",
")",
"part",
".",
"set_payload",
"(",... | Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance. | [
"Attach",
"an",
"attachment",
"to",
"a",
"message",
"as",
"a",
"side",
"effect",
"."
] | python | train | 32.117647 |
remind101/stacker_blueprints | stacker_blueprints/policies.py | https://github.com/remind101/stacker_blueprints/blob/71624f6e1bd4ea794dc98fb621a04235e1931cae/stacker_blueprints/policies.py#L222-L246 | def dynamodb_autoscaling_policy(tables):
"""Policy to allow AutoScaling a list of DynamoDB tables."""
return Policy(
Statement=[
Statement(
Effect=Allow,
Resource=dynamodb_arns(tables),
Action=[
dynamodb.DescribeTable,
... | [
"def",
"dynamodb_autoscaling_policy",
"(",
"tables",
")",
":",
"return",
"Policy",
"(",
"Statement",
"=",
"[",
"Statement",
"(",
"Effect",
"=",
"Allow",
",",
"Resource",
"=",
"dynamodb_arns",
"(",
"tables",
")",
",",
"Action",
"=",
"[",
"dynamodb",
".",
"D... | Policy to allow AutoScaling a list of DynamoDB tables. | [
"Policy",
"to",
"allow",
"AutoScaling",
"a",
"list",
"of",
"DynamoDB",
"tables",
"."
] | python | train | 30.44 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-django/opencensus/ext/django/middleware.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-django/opencensus/ext/django/middleware.py#L135-L186 | def process_request(self, request):
"""Called on each request, before Django decides which view to execute.
:type request: :class:`~django.http.request.HttpRequest`
:param request: Django http request.
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"# Do not trace if the url is blacklisted",
"if",
"utils",
".",
"disable_tracing_url",
"(",
"request",
".",
"path",
",",
"self",
".",
"blacklist_paths",
")",
":",
"return",
"# Add the request to thread l... | Called on each request, before Django decides which view to execute.
:type request: :class:`~django.http.request.HttpRequest`
:param request: Django http request. | [
"Called",
"on",
"each",
"request",
"before",
"Django",
"decides",
"which",
"view",
"to",
"execute",
"."
] | python | train | 37.711538 |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L535-L544 | def competition_submissions(self, competition):
""" get the list of Submission for a particular competition
Parameters
==========
competition: the name of the competition
"""
submissions_result = self.process_response(
self.competitions_submission... | [
"def",
"competition_submissions",
"(",
"self",
",",
"competition",
")",
":",
"submissions_result",
"=",
"self",
".",
"process_response",
"(",
"self",
".",
"competitions_submissions_list_with_http_info",
"(",
"id",
"=",
"competition",
")",
")",
"return",
"[",
"Submis... | get the list of Submission for a particular competition
Parameters
==========
competition: the name of the competition | [
"get",
"the",
"list",
"of",
"Submission",
"for",
"a",
"particular",
"competition"
] | python | train | 40.8 |
openeemeter/eeweather | eeweather/summaries.py | https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/summaries.py#L25-L55 | def get_zcta_ids(state=None):
""" Get ids of all supported ZCTAs, optionally by state.
Parameters
----------
state : str, optional
Select zipcodes only from this state or territory, given as 2-letter
abbreviation (e.g., ``'CA'``, ``'PR'``).
Returns
-------
results : list of... | [
"def",
"get_zcta_ids",
"(",
"state",
"=",
"None",
")",
":",
"conn",
"=",
"metadata_db_connection_proxy",
".",
"get_connection",
"(",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"if",
"state",
"is",
"None",
":",
"cur",
".",
"execute",
"(",
"\"\"\"\n... | Get ids of all supported ZCTAs, optionally by state.
Parameters
----------
state : str, optional
Select zipcodes only from this state or territory, given as 2-letter
abbreviation (e.g., ``'CA'``, ``'PR'``).
Returns
-------
results : list of str
List of all supported sel... | [
"Get",
"ids",
"of",
"all",
"supported",
"ZCTAs",
"optionally",
"by",
"state",
"."
] | python | train | 24.387097 |
inveniosoftware/invenio-oauth2server | invenio_oauth2server/errors.py | https://github.com/inveniosoftware/invenio-oauth2server/blob/7033d3495c1a2b830e101e43918e92a37bbb49f2/invenio_oauth2server/errors.py#L50-L61 | def get_body(self, environ=None):
"""Get the request body."""
body = dict(
status=self.code,
message=self.description,
)
errors = self.get_errors()
if self.errors:
body['errors'] = errors
return json.dumps(body) | [
"def",
"get_body",
"(",
"self",
",",
"environ",
"=",
"None",
")",
":",
"body",
"=",
"dict",
"(",
"status",
"=",
"self",
".",
"code",
",",
"message",
"=",
"self",
".",
"description",
",",
")",
"errors",
"=",
"self",
".",
"get_errors",
"(",
")",
"if"... | Get the request body. | [
"Get",
"the",
"request",
"body",
"."
] | python | train | 23.833333 |
benley/butcher | butcher/targets/genrule.py | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/genrule.py#L64-L174 | def expand_cmd_labels(self):
"""Expand make-style variables in cmd parameters.
Currently:
$(location <foo>) Location of one dependency or output file.
$(locations <foo>) Space-delimited list of foo's output files.
$(SRCS) Space-delimited list of this rule's ... | [
"def",
"expand_cmd_labels",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"cmd",
"def",
"_expand_onesrc",
"(",
")",
":",
"\"\"\"Expand $@ or $(@) to one output file.\"\"\"",
"outs",
"=",
"self",
".",
"rule",
".",
"params",
"[",
"'outs'",
"]",
"or",
"[",
"]... | Expand make-style variables in cmd parameters.
Currently:
$(location <foo>) Location of one dependency or output file.
$(locations <foo>) Space-delimited list of foo's output files.
$(SRCS) Space-delimited list of this rule's source files.
$(OUTS) ... | [
"Expand",
"make",
"-",
"style",
"variables",
"in",
"cmd",
"parameters",
"."
] | python | train | 45 |
singularityhub/sregistry-cli | sregistry/main/nvidia/__init__.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/nvidia/__init__.py#L83-L110 | def _set_base(self):
'''set the API base or default to use Docker Hub. The user is able
to set the base, api version, and protocol via a settings file
of environment variables:
SREGISTRY_NVIDIA_BASE: defaults to nvcr.io
SREGISTRY_NVIDIA_TOKEN: defaults to $oauthtoke... | [
"def",
"_set_base",
"(",
"self",
")",
":",
"base",
"=",
"self",
".",
"_get_setting",
"(",
"'SREGISTRY_NVIDIA_BASE'",
")",
"version",
"=",
"self",
".",
"_get_setting",
"(",
"'SREGISTRY_NVIDIA_VERSION'",
")",
"if",
"base",
"is",
"None",
":",
"base",
"=",
"\"nv... | set the API base or default to use Docker Hub. The user is able
to set the base, api version, and protocol via a settings file
of environment variables:
SREGISTRY_NVIDIA_BASE: defaults to nvcr.io
SREGISTRY_NVIDIA_TOKEN: defaults to $oauthtoken
SREGISTRY_NVIDIA_VE... | [
"set",
"the",
"API",
"base",
"or",
"default",
"to",
"use",
"Docker",
"Hub",
".",
"The",
"user",
"is",
"able",
"to",
"set",
"the",
"base",
"api",
"version",
"and",
"protocol",
"via",
"a",
"settings",
"file",
"of",
"environment",
"variables",
":",
"SREGIST... | python | test | 33.607143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.