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 |
|---|---|---|---|---|---|---|---|---|---|
ARMmbed/icetea | icetea_lib/Plugin/PluginManager.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L64-L88 | def register_tc_plugins(self, plugin_name, plugin_class):
"""
Loads a plugin as a dictionary and attaches needed parts to correct areas for testing
parts.
:param plugin_name: Name of the plugins
:param plugin_class: PluginBase
:return: Nothing
"""
if plug... | [
"def",
"register_tc_plugins",
"(",
"self",
",",
"plugin_name",
",",
"plugin_class",
")",
":",
"if",
"plugin_name",
"in",
"self",
".",
"registered_plugins",
":",
"raise",
"PluginException",
"(",
"\"Plugin {} already registered! Duplicate \"",
"\"plugins?\"",
".",
"format... | Loads a plugin as a dictionary and attaches needed parts to correct areas for testing
parts.
:param plugin_name: Name of the plugins
:param plugin_class: PluginBase
:return: Nothing | [
"Loads",
"a",
"plugin",
"as",
"a",
"dictionary",
"and",
"attaches",
"needed",
"parts",
"to",
"correct",
"areas",
"for",
"testing",
"parts",
"."
] | python | train | 46.4 |
hangyan/shaw | shaw/log.py | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/log.py#L129-L204 | def get_log_config(component, handlers, level='DEBUG', path='/var/log/vfine/'):
"""Return a log config for django project."""
config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s][%(thr... | [
"def",
"get_log_config",
"(",
"component",
",",
"handlers",
",",
"level",
"=",
"'DEBUG'",
",",
"path",
"=",
"'/var/log/vfine/'",
")",
":",
"config",
"=",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
":",
"... | Return a log config for django project. | [
"Return",
"a",
"log",
"config",
"for",
"django",
"project",
"."
] | python | train | 35.118421 |
pvlib/pvlib-python | pvlib/irradiance.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/irradiance.py#L1626-L1637 | def _temp_dew_dirint(temp_dew, times):
"""
Calculate precipitable water from surface dew point temp (Perez eqn 4),
or return a default value for use with :py:func:`_dirint_bins`.
"""
if temp_dew is not None:
# Perez eqn 4
w = pd.Series(np.exp(0.07 * temp_dew - 0.075), index=times)
... | [
"def",
"_temp_dew_dirint",
"(",
"temp_dew",
",",
"times",
")",
":",
"if",
"temp_dew",
"is",
"not",
"None",
":",
"# Perez eqn 4",
"w",
"=",
"pd",
".",
"Series",
"(",
"np",
".",
"exp",
"(",
"0.07",
"*",
"temp_dew",
"-",
"0.075",
")",
",",
"index",
"=",... | Calculate precipitable water from surface dew point temp (Perez eqn 4),
or return a default value for use with :py:func:`_dirint_bins`. | [
"Calculate",
"precipitable",
"water",
"from",
"surface",
"dew",
"point",
"temp",
"(",
"Perez",
"eqn",
"4",
")",
"or",
"return",
"a",
"default",
"value",
"for",
"use",
"with",
":",
"py",
":",
"func",
":",
"_dirint_bins",
"."
] | python | train | 35.583333 |
Azure/azure-cli-extensions | src/alias/azext_alias/util.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L35-L44 | def get_alias_table():
"""
Get the current alias table.
"""
try:
alias_table = get_config_parser()
alias_table.read(azext_alias.alias.GLOBAL_ALIAS_PATH)
return alias_table
except Exception: # pylint: disable=broad-except
return get_config_parser() | [
"def",
"get_alias_table",
"(",
")",
":",
"try",
":",
"alias_table",
"=",
"get_config_parser",
"(",
")",
"alias_table",
".",
"read",
"(",
"azext_alias",
".",
"alias",
".",
"GLOBAL_ALIAS_PATH",
")",
"return",
"alias_table",
"except",
"Exception",
":",
"# pylint: d... | Get the current alias table. | [
"Get",
"the",
"current",
"alias",
"table",
"."
] | python | train | 29.1 |
inasafe/inasafe | safe/plugin.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L769-L778 | def show_minimum_needs_configuration(self):
"""Show the minimum needs dialog."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.minimum_needs.needs_manager_dialog import (
NeedsManagerDialog)
dialog = NeedsManagerDialog(
parent=self.iface.... | [
"def",
"show_minimum_needs_configuration",
"(",
"self",
")",
":",
"# import here only so that it is AFTER i18n set up",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"minimum_needs",
".",
"needs_manager_dialog",
"import",
"(",
"NeedsManagerDialog",
")",
"dialog",
"=",
... | Show the minimum needs dialog. | [
"Show",
"the",
"minimum",
"needs",
"dialog",
"."
] | python | train | 38.2 |
unfoldingWord-dev/python-gogs-client | gogs_client/interface.py | https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L642-L653 | def delete(self, path, auth=None, **kwargs):
"""
Manually make a DELETE request.
:param str path: relative url of the request (e.g. `/users/username`)
:param auth.Authentication auth: authentication object
:param kwargs dict: Extra arguments for the request, as supported by the
... | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_check_ok",
"(",
"self",
".",
"_delete",
"(",
"path",
",",
"auth",
"=",
"auth",
",",
"*",
"*",
"kwargs",
")",
")"
] | Manually make a DELETE request.
:param str path: relative url of the request (e.g. `/users/username`)
:param auth.Authentication auth: authentication object
:param kwargs dict: Extra arguments for the request, as supported by the
`requests <http://docs.python-request... | [
"Manually",
"make",
"a",
"DELETE",
"request",
"."
] | python | train | 51.666667 |
CodyKochmann/generators | generators/skip_first.py | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/skip_first.py#L9-L16 | def skip_first(pipe, items=1):
''' this is an alias for skip to parallel the dedicated skip_last function
to provide a little more readability to the code. the action of actually
skipping does not occur until the first iteration is done
'''
pipe = iter(pipe)
for i in skip(pipe, items):
... | [
"def",
"skip_first",
"(",
"pipe",
",",
"items",
"=",
"1",
")",
":",
"pipe",
"=",
"iter",
"(",
"pipe",
")",
"for",
"i",
"in",
"skip",
"(",
"pipe",
",",
"items",
")",
":",
"yield",
"i"
] | this is an alias for skip to parallel the dedicated skip_last function
to provide a little more readability to the code. the action of actually
skipping does not occur until the first iteration is done | [
"this",
"is",
"an",
"alias",
"for",
"skip",
"to",
"parallel",
"the",
"dedicated",
"skip_last",
"function",
"to",
"provide",
"a",
"little",
"more",
"readability",
"to",
"the",
"code",
".",
"the",
"action",
"of",
"actually",
"skipping",
"does",
"not",
"occur",... | python | train | 40.875 |
cytoscape/py2cytoscape | py2cytoscape/data/cynetwork.py | https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/data/cynetwork.py#L46-L52 | def to_networkx(self):
"""
Return this network in NetworkX graph object.
:return: Network as NetworkX graph object
"""
return nx_util.to_networkx(self.session.get(self.__url).json()) | [
"def",
"to_networkx",
"(",
"self",
")",
":",
"return",
"nx_util",
".",
"to_networkx",
"(",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"__url",
")",
".",
"json",
"(",
")",
")"
] | Return this network in NetworkX graph object.
:return: Network as NetworkX graph object | [
"Return",
"this",
"network",
"in",
"NetworkX",
"graph",
"object",
"."
] | python | train | 31 |
CivicSpleen/ambry | ambry/orm/source.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L183-L192 | def spec(self):
"""Return a SourceSpec to describe this source"""
from ambry_sources.sources import SourceSpec
d = self.dict
d['url'] = self.url
# Will get the URL twice; once as ref and once as URL, but the ref is ignored
return SourceSpec(**d) | [
"def",
"spec",
"(",
"self",
")",
":",
"from",
"ambry_sources",
".",
"sources",
"import",
"SourceSpec",
"d",
"=",
"self",
".",
"dict",
"d",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"# Will get the URL twice; once as ref and once as URL, but the ref is ignored",
... | Return a SourceSpec to describe this source | [
"Return",
"a",
"SourceSpec",
"to",
"describe",
"this",
"source"
] | python | train | 28.7 |
polysquare/cmake-ast | cmakeast/ast.py | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L631-L654 | def consume_token(self, tokens, index, tokens_len):
"""Consume a token.
Returns a tuple of (tokens, tokens_len, index) when consumption is
completed and tokens have been merged together.
"""
if _is_really_comment(tokens, index):
self.last_line_with_comment = tokens[i... | [
"def",
"consume_token",
"(",
"self",
",",
"tokens",
",",
"index",
",",
"tokens_len",
")",
":",
"if",
"_is_really_comment",
"(",
"tokens",
",",
"index",
")",
":",
"self",
".",
"last_line_with_comment",
"=",
"tokens",
"[",
"index",
"]",
".",
"line",
"finishe... | Consume a token.
Returns a tuple of (tokens, tokens_len, index) when consumption is
completed and tokens have been merged together. | [
"Consume",
"a",
"token",
"."
] | python | train | 35.666667 |
pandas-dev/pandas | scripts/validate_docstrings.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/scripts/validate_docstrings.py#L599-L785 | def get_validation_data(doc):
"""
Validate the docstring.
Parameters
----------
doc : Docstring
A Docstring object with the given function name.
Returns
-------
tuple
errors : list of tuple
Errors occurred during validation.
warnings : list of tuple
... | [
"def",
"get_validation_data",
"(",
"doc",
")",
":",
"errs",
"=",
"[",
"]",
"wrns",
"=",
"[",
"]",
"if",
"not",
"doc",
".",
"raw_doc",
":",
"errs",
".",
"append",
"(",
"error",
"(",
"'GL08'",
")",
")",
"return",
"errs",
",",
"wrns",
",",
"''",
"if... | Validate the docstring.
Parameters
----------
doc : Docstring
A Docstring object with the given function name.
Returns
-------
tuple
errors : list of tuple
Errors occurred during validation.
warnings : list of tuple
Warnings occurred during valid... | [
"Validate",
"the",
"docstring",
"."
] | python | train | 37.609626 |
google/neuroglancer | python/neuroglancer/downsample_scales.py | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L24-L50 | def compute_near_isotropic_downsampling_scales(size,
voxel_size,
dimensions_to_downsample,
max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES,
... | [
"def",
"compute_near_isotropic_downsampling_scales",
"(",
"size",
",",
"voxel_size",
",",
"dimensions_to_downsample",
",",
"max_scales",
"=",
"DEFAULT_MAX_DOWNSAMPLING_SCALES",
",",
"max_downsampling",
"=",
"DEFAULT_MAX_DOWNSAMPLING",
",",
"max_downsampled_size",
"=",
"DEFAULT_... | Compute a list of successive downsampling factors. | [
"Compute",
"a",
"list",
"of",
"successive",
"downsampling",
"factors",
"."
] | python | train | 54.222222 |
bwesterb/sarah | src/cacheDecorators.py | https://github.com/bwesterb/sarah/blob/a9e46e875dfff1dc11255d714bb736e5eb697809/src/cacheDecorators.py#L5-L28 | def cacheOnSameArgs(timeout=None):
""" Caches the return of the function until the the specified time has
elapsed or the arguments change. If timeout is None it will not
be considered. """
if isinstance(timeout, int):
timeout = datetime.timedelta(0, timeout)
def decorator(f):
... | [
"def",
"cacheOnSameArgs",
"(",
"timeout",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"timeout",
",",
"int",
")",
":",
"timeout",
"=",
"datetime",
".",
"timedelta",
"(",
"0",
",",
"timeout",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"_cache",
... | Caches the return of the function until the the specified time has
elapsed or the arguments change. If timeout is None it will not
be considered. | [
"Caches",
"the",
"return",
"of",
"the",
"function",
"until",
"the",
"the",
"specified",
"time",
"has",
"elapsed",
"or",
"the",
"arguments",
"change",
".",
"If",
"timeout",
"is",
"None",
"it",
"will",
"not",
"be",
"considered",
"."
] | python | train | 39.083333 |
lepture/flask-oauthlib | flask_oauthlib/provider/oauth2.py | https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L893-L911 | def validate_code(self, client_id, code, client, request, *args, **kwargs):
"""Ensure the grant code is valid."""
client = client or self._clientgetter(client_id)
log.debug(
'Validate code for client %r and code %r', client.client_id, code
)
grant = self._grantgetter(... | [
"def",
"validate_code",
"(",
"self",
",",
"client_id",
",",
"code",
",",
"client",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"client",
"or",
"self",
".",
"_clientgetter",
"(",
"client_id",
")",
"log",
".",
"d... | Ensure the grant code is valid. | [
"Ensure",
"the",
"grant",
"code",
"is",
"valid",
"."
] | python | test | 38.526316 |
dcos/shakedown | shakedown/dcos/spinner.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/spinner.py#L79-L94 | def time_wait(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=True,
required_consecutive_success_count=1):
""" waits or spins for a predicate and returns the time of the wait.
An exception in the function will be returned.
... | [
"def",
"time_wait",
"(",
"predicate",
",",
"timeout_seconds",
"=",
"120",
",",
"sleep_seconds",
"=",
"1",
",",
"ignore_exceptions",
"=",
"True",
",",
"inverse_predicate",
"=",
"False",
",",
"noisy",
"=",
"True",
",",
"required_consecutive_success_count",
"=",
"1... | waits or spins for a predicate and returns the time of the wait.
An exception in the function will be returned.
A timeout will throw a TimeoutExpired Exception. | [
"waits",
"or",
"spins",
"for",
"a",
"predicate",
"and",
"returns",
"the",
"time",
"of",
"the",
"wait",
".",
"An",
"exception",
"in",
"the",
"function",
"will",
"be",
"returned",
".",
"A",
"timeout",
"will",
"throw",
"a",
"TimeoutExpired",
"Exception",
"."
... | python | train | 35.5 |
tbreitenfeldt/invisible_ui | invisible_ui/elements/group.py | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/elements/group.py#L25-L32 | def activate(self, event):
"""Change the value."""
self._index += 1
if self._index >= len(self._values):
self._index = 0
self._selection = self._values[self._index]
self.ao2.speak(self._selection) | [
"def",
"activate",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_index",
"+=",
"1",
"if",
"self",
".",
"_index",
">=",
"len",
"(",
"self",
".",
"_values",
")",
":",
"self",
".",
"_index",
"=",
"0",
"self",
".",
"_selection",
"=",
"self",
".... | Change the value. | [
"Change",
"the",
"value",
"."
] | python | train | 30.25 |
saltstack/salt | salt/utils/json.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/json.py#L81-L99 | def loads(s, **kwargs):
'''
.. versionadded:: 2018.3.0
Wraps json.loads and prevents a traceback in the event that a bytestring is
passed to the function. (Python < 3.6 cannot load bytestrings)
You can pass an alternate json module (loaded via import_json() above)
using the _json_module argume... | [
"def",
"loads",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
":",
"json_module",
"=",
"kwargs",
".",
"pop",
"(",
"'_json_module'",
",",
"json",
")",
"try",
":",
"return",
"json_module",
".",
"loads",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
"except",
"Ty... | .. versionadded:: 2018.3.0
Wraps json.loads and prevents a traceback in the event that a bytestring is
passed to the function. (Python < 3.6 cannot load bytestrings)
You can pass an alternate json module (loaded via import_json() above)
using the _json_module argument) | [
"..",
"versionadded",
"::",
"2018",
".",
"3",
".",
"0"
] | python | train | 35.526316 |
gwastro/pycbc | pycbc/inference/sampler/base_mcmc.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/sampler/base_mcmc.py#L82-L115 | def blob_data_to_dict(stat_names, blobs):
"""Converts list of "blobs" to a dictionary of model stats.
Samplers like ``emcee`` store the extra tuple returned by ``CallModel`` to
a list called blobs. This is a list of lists of tuples with shape
niterations x nwalkers x nstats, where nstats is the number ... | [
"def",
"blob_data_to_dict",
"(",
"stat_names",
",",
"blobs",
")",
":",
"# get the dtypes of each of the stats; we'll just take this from the",
"# first iteration and walker",
"dtypes",
"=",
"[",
"type",
"(",
"val",
")",
"for",
"val",
"in",
"blobs",
"[",
"0",
"]",
"[",... | Converts list of "blobs" to a dictionary of model stats.
Samplers like ``emcee`` store the extra tuple returned by ``CallModel`` to
a list called blobs. This is a list of lists of tuples with shape
niterations x nwalkers x nstats, where nstats is the number of stats
returned by the model's ``default_st... | [
"Converts",
"list",
"of",
"blobs",
"to",
"a",
"dictionary",
"of",
"model",
"stats",
"."
] | python | train | 41.264706 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L167-L191 | def dedupe_all_lists(obj, exclude_keys=()):
"""Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication
"""
squared_dedupe_len = 10
if isinstance(obj, dict):
new_obj = {}
f... | [
"def",
"dedupe_all_lists",
"(",
"obj",
",",
"exclude_keys",
"=",
"(",
")",
")",
":",
"squared_dedupe_len",
"=",
"10",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"new_obj",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"obj",
".",
"item... | Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication | [
"Recursively",
"remove",
"duplucates",
"from",
"all",
"lists",
"."
] | python | train | 33.24 |
graphql-python/graphql-core | graphql/backend/cache.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/cache.py#L18-L27 | def get_unique_schema_id(schema):
# type: (GraphQLSchema) -> str
"""Get a unique id given a GraphQLSchema"""
assert isinstance(schema, GraphQLSchema), (
"Must receive a GraphQLSchema as schema. Received {}"
).format(repr(schema))
if schema not in _cached_schemas:
_cached_schemas[sch... | [
"def",
"get_unique_schema_id",
"(",
"schema",
")",
":",
"# type: (GraphQLSchema) -> str",
"assert",
"isinstance",
"(",
"schema",
",",
"GraphQLSchema",
")",
",",
"(",
"\"Must receive a GraphQLSchema as schema. Received {}\"",
")",
".",
"format",
"(",
"repr",
"(",
"schema... | Get a unique id given a GraphQLSchema | [
"Get",
"a",
"unique",
"id",
"given",
"a",
"GraphQLSchema"
] | python | train | 39.8 |
ActivisionGameScience/assertpy | assertpy/assertpy.py | https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L174-L178 | def is_not_equal_to(self, other):
"""Asserts that val is not equal to other."""
if self.val == other:
self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))
return self | [
"def",
"is_not_equal_to",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"val",
"==",
"other",
":",
"self",
".",
"_err",
"(",
"'Expected <%s> to be not equal to <%s>, but was.'",
"%",
"(",
"self",
".",
"val",
",",
"other",
")",
")",
"return",
"sel... | Asserts that val is not equal to other. | [
"Asserts",
"that",
"val",
"is",
"not",
"equal",
"to",
"other",
"."
] | python | valid | 45.2 |
JustinLovinger/optimal | optimal/algorithms/pbil.py | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L132-L138 | def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate):
"""Shift probabilities towards the best solution."""
best_solution = max(zip(fitnesses, population))[1]
# Shift probabilities towards best solution
return _adjust(probability_vec, bes... | [
"def",
"_adjust_probability_vec_best",
"(",
"population",
",",
"fitnesses",
",",
"probability_vec",
",",
"adjust_rate",
")",
":",
"best_solution",
"=",
"max",
"(",
"zip",
"(",
"fitnesses",
",",
"population",
")",
")",
"[",
"1",
"]",
"# Shift probabilities towards ... | Shift probabilities towards the best solution. | [
"Shift",
"probabilities",
"towards",
"the",
"best",
"solution",
"."
] | python | train | 48.285714 |
tensorflow/probability | tensorflow_probability/python/internal/distribution_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L710-L737 | def same_dynamic_shape(a, b):
"""Returns whether a and b have the same dynamic shape.
Args:
a: `Tensor`
b: `Tensor`
Returns:
`bool` `Tensor` representing if both tensors have the same shape.
"""
a = tf.convert_to_tensor(value=a, name="a")
b = tf.convert_to_tensor(value=b, name="b")
# Here w... | [
"def",
"same_dynamic_shape",
"(",
"a",
",",
"b",
")",
":",
"a",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"a",
",",
"name",
"=",
"\"a\"",
")",
"b",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"b",
",",
"name",
"=",
"\"b\""... | Returns whether a and b have the same dynamic shape.
Args:
a: `Tensor`
b: `Tensor`
Returns:
`bool` `Tensor` representing if both tensors have the same shape. | [
"Returns",
"whether",
"a",
"and",
"b",
"have",
"the",
"same",
"dynamic",
"shape",
"."
] | python | test | 31.75 |
Karaage-Cluster/karaage | karaage/plugins/kgapplications/views/base.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/base.py#L253-L291 | def _next(self, request, application, roles, next_config):
""" Continue the state machine at given state. """
# we only support state changes for POST requests
if request.method == "POST":
key = None
# If next state is a transition, process it
while True:
... | [
"def",
"_next",
"(",
"self",
",",
"request",
",",
"application",
",",
"roles",
",",
"next_config",
")",
":",
"# we only support state changes for POST requests",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"key",
"=",
"None",
"# If next state is a transit... | Continue the state machine at given state. | [
"Continue",
"the",
"state",
"machine",
"at",
"given",
"state",
"."
] | python | train | 35.435897 |
MisterY/asset-allocation | asset_allocation/formatters.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L52-L122 | def __format_row(self, row: AssetAllocationViewModel):
""" display-format one row
Formats one Asset Class record """
output = ""
index = 0
# Name
value = row.name
# Indent according to depth.
for _ in range(0, row.depth):
value = f" {value}"... | [
"def",
"__format_row",
"(",
"self",
",",
"row",
":",
"AssetAllocationViewModel",
")",
":",
"output",
"=",
"\"\"",
"index",
"=",
"0",
"# Name",
"value",
"=",
"row",
".",
"name",
"# Indent according to depth.",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"row"... | display-format one row
Formats one Asset Class record | [
"display",
"-",
"format",
"one",
"row",
"Formats",
"one",
"Asset",
"Class",
"record"
] | python | train | 30.464789 |
scopus-api/scopus | scopus/abstract_retrieval.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L177-L184 | def confsponsor(self):
"""Sponsor(s) of the conference the abstract belongs to."""
sponsors = chained_get(self._confevent, ['confsponsors', 'confsponsor'], [])
if len(sponsors) == 0:
return None
if isinstance(sponsors, list):
return [s['$'] for s in sponsors]
... | [
"def",
"confsponsor",
"(",
"self",
")",
":",
"sponsors",
"=",
"chained_get",
"(",
"self",
".",
"_confevent",
",",
"[",
"'confsponsors'",
",",
"'confsponsor'",
"]",
",",
"[",
"]",
")",
"if",
"len",
"(",
"sponsors",
")",
"==",
"0",
":",
"return",
"None",... | Sponsor(s) of the conference the abstract belongs to. | [
"Sponsor",
"(",
"s",
")",
"of",
"the",
"conference",
"the",
"abstract",
"belongs",
"to",
"."
] | python | train | 41.5 |
westurner/pgs | pgs/bottle.py | https://github.com/westurner/pgs/blob/1cc2bf2c41479d8d3ba50480f003183f1675e518/pgs/bottle.py#L3152-L3251 | def run(app=None,
server='wsgiref',
host='127.0.0.1',
port=8080,
interval=1,
reloader=False,
quiet=False,
plugins=None,
debug=None, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI applica... | [
"def",
"run",
"(",
"app",
"=",
"None",
",",
"server",
"=",
"'wsgiref'",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
",",
"interval",
"=",
"1",
",",
"reloader",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"plugins",
"=",
"None",
",... | Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass ... | [
"Start",
"a",
"server",
"instance",
".",
"This",
"method",
"blocks",
"until",
"the",
"server",
"terminates",
"."
] | python | valid | 38.37 |
RusticiSoftware/TinCanPython | tincan/remote_lrs.py | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/remote_lrs.py#L709-L736 | def retrieve_agent_profile_ids(self, agent, since=None):
"""Retrieve agent profile id(s) with the specified parameters
:param agent: Agent object of desired agent profiles
:type agent: :class:`tincan.agent.Agent`
:param since: Retrieve agent profile id's since this time
:type si... | [
"def",
"retrieve_agent_profile_ids",
"(",
"self",
",",
"agent",
",",
"since",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"agent",
",",
"Agent",
")",
":",
"agent",
"=",
"Agent",
"(",
"agent",
")",
"request",
"=",
"HTTPRequest",
"(",
"method",
... | Retrieve agent profile id(s) with the specified parameters
:param agent: Agent object of desired agent profiles
:type agent: :class:`tincan.agent.Agent`
:param since: Retrieve agent profile id's since this time
:type since: str | unicode
:return: LRS Response object with list of... | [
"Retrieve",
"agent",
"profile",
"id",
"(",
"s",
")",
"with",
"the",
"specified",
"parameters"
] | python | train | 34.964286 |
materialsproject/pymatgen | pymatgen/phonon/bandstructure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/phonon/bandstructure.py#L203-L231 | def asr_breaking(self, tol_eigendisplacements=1e-5):
"""
Returns the breaking of the acoustic sum rule for the three acoustic modes,
if Gamma is present. None otherwise.
If eigendisplacements are available they are used to determine the acoustic
modes: selects the bands correspon... | [
"def",
"asr_breaking",
"(",
"self",
",",
"tol_eigendisplacements",
"=",
"1e-5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nb_qpoints",
")",
":",
"if",
"np",
".",
"allclose",
"(",
"self",
".",
"qpoints",
"[",
"i",
"]",
".",
"frac_coords",
... | Returns the breaking of the acoustic sum rule for the three acoustic modes,
if Gamma is present. None otherwise.
If eigendisplacements are available they are used to determine the acoustic
modes: selects the bands corresponding to the eigendisplacements that
represent to a translation w... | [
"Returns",
"the",
"breaking",
"of",
"the",
"acoustic",
"sum",
"rule",
"for",
"the",
"three",
"acoustic",
"modes",
"if",
"Gamma",
"is",
"present",
".",
"None",
"otherwise",
".",
"If",
"eigendisplacements",
"are",
"available",
"they",
"are",
"used",
"to",
"det... | python | train | 47.62069 |
marshmallow-code/webargs | src/webargs/flaskparser.py | https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/flaskparser.py#L101-L112 | def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
abort(
status_code,
... | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"req",
",",
"schema",
",",
"error_status_code",
",",
"error_headers",
")",
":",
"status_code",
"=",
"error_status_code",
"or",
"self",
".",
"DEFAULT_VALIDATION_STATUS",
"abort",
"(",
"status_code",
",",
"exc... | Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error. | [
"Handles",
"errors",
"during",
"parsing",
".",
"Aborts",
"the",
"current",
"HTTP",
"request",
"and",
"responds",
"with",
"a",
"422",
"error",
"."
] | python | train | 36.416667 |
numenta/htmresearch | projects/sdr_paper/scalar_sdrs.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sdr_paper/scalar_sdrs.py#L136-L152 | def getTheta(k, nTrials=100000):
"""
Estimate a reasonable value of theta for this k.
"""
theDots = np.zeros(nTrials)
w1 = getSparseTensor(k, k, nTrials, fixedRange=1.0/k)
for i in range(nTrials):
theDots[i] = w1[i].dot(w1[i])
dotMean = theDots.mean()
print("k=", k, "min/mean/max diag of w dot prod... | [
"def",
"getTheta",
"(",
"k",
",",
"nTrials",
"=",
"100000",
")",
":",
"theDots",
"=",
"np",
".",
"zeros",
"(",
"nTrials",
")",
"w1",
"=",
"getSparseTensor",
"(",
"k",
",",
"k",
",",
"nTrials",
",",
"fixedRange",
"=",
"1.0",
"/",
"k",
")",
"for",
... | Estimate a reasonable value of theta for this k. | [
"Estimate",
"a",
"reasonable",
"value",
"of",
"theta",
"for",
"this",
"k",
"."
] | python | train | 26.705882 |
shmir/PyIxExplorer | ixexplorer/ixe_app.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_app.py#L243-L255 | def get_cap_files(self, *ports):
"""
:param ports: list of ports to get capture files names for.
:return: dictionary (port, capture file)
"""
cap_files = {}
for port in ports:
if port.cap_file_name:
with open(port.cap_file_name) as f:
... | [
"def",
"get_cap_files",
"(",
"self",
",",
"*",
"ports",
")",
":",
"cap_files",
"=",
"{",
"}",
"for",
"port",
"in",
"ports",
":",
"if",
"port",
".",
"cap_file_name",
":",
"with",
"open",
"(",
"port",
".",
"cap_file_name",
")",
"as",
"f",
":",
"cap_fil... | :param ports: list of ports to get capture files names for.
:return: dictionary (port, capture file) | [
":",
"param",
"ports",
":",
"list",
"of",
"ports",
"to",
"get",
"capture",
"files",
"names",
"for",
".",
":",
"return",
":",
"dictionary",
"(",
"port",
"capture",
"file",
")"
] | python | train | 33.846154 |
yahoo/TensorFlowOnSpark | examples/cifar10/cifar10.py | https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/cifar10/cifar10.py#L98-L112 | def _variable_on_cpu(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of the variable
shape: list of ints
initializer: initializer for Variable
Returns:
Variable Tensor
"""
with tf.device('/cpu:0'):
dtype = tf.float16 if FLAGS.use_fp16 else... | [
"def",
"_variable_on_cpu",
"(",
"name",
",",
"shape",
",",
"initializer",
")",
":",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"dtype",
"=",
"tf",
".",
"float16",
"if",
"FLAGS",
".",
"use_fp16",
"else",
"tf",
".",
"float32",
"var",
"=",
... | Helper to create a Variable stored on CPU memory.
Args:
name: name of the variable
shape: list of ints
initializer: initializer for Variable
Returns:
Variable Tensor | [
"Helper",
"to",
"create",
"a",
"Variable",
"stored",
"on",
"CPU",
"memory",
"."
] | python | train | 27.133333 |
manns/pyspread | pyspread/src/gui/_main_window.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L684-L693 | def OnAttributesToolbarToggle(self, event):
"""Format toolbar toggle event handler"""
self.main_window.attributes_toolbar.SetGripperVisible(True)
attributes_toolbar_info = \
self.main_window._mgr.GetPane("attributes_toolbar")
self._toggle_pane(attributes_toolbar_info)
... | [
"def",
"OnAttributesToolbarToggle",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"main_window",
".",
"attributes_toolbar",
".",
"SetGripperVisible",
"(",
"True",
")",
"attributes_toolbar_info",
"=",
"self",
".",
"main_window",
".",
"_mgr",
".",
"GetPane",
"... | Format toolbar toggle event handler | [
"Format",
"toolbar",
"toggle",
"event",
"handler"
] | python | train | 32.7 |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv1/blueprint.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/blueprint.py#L51-L61 | def GetPackages(classification,visibility):
"""Gets a list of Blueprint Packages filtered by classification and visibility.
https://t3n.zendesk.com/entries/20411357-Get-Packages
:param classification: package type filter (System, Script, Software)
:param visibility: package visibility filter (Public, Private,... | [
"def",
"GetPackages",
"(",
"classification",
",",
"visibility",
")",
":",
"r",
"=",
"clc",
".",
"v1",
".",
"API",
".",
"Call",
"(",
"'post'",
",",
"'Blueprint/GetPackages'",
",",
"{",
"'Classification'",
":",
"Blueprint",
".",
"classification_stoi",
"[",
"cl... | Gets a list of Blueprint Packages filtered by classification and visibility.
https://t3n.zendesk.com/entries/20411357-Get-Packages
:param classification: package type filter (System, Script, Software)
:param visibility: package visibility filter (Public, Private, Shared) | [
"Gets",
"a",
"list",
"of",
"Blueprint",
"Packages",
"filtered",
"by",
"classification",
"and",
"visibility",
"."
] | python | train | 50.818182 |
LuqueDaniel/pybooru | pybooru/pybooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/pybooru.py#L106-L134 | def site_url(self, url):
"""URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid.
"""
# Regular expression to URL validate
regex =... | [
"def",
"site_url",
"(",
"self",
",",
"url",
")",
":",
"# Regular expression to URL validate",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^(?:http|https)://'",
"# Scheme only HTTP/HTTPS",
"r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?| \\\n [A-Z0-9-]... | URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid. | [
"URL",
"setter",
"and",
"validator",
"for",
"site_url",
"property",
"."
] | python | train | 37.344828 |
thieman/dagobah | dagobah/core/core.py | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1080-L1102 | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Task to a Python dict. """
result = {'command': self.command,
'name': self.name,
'started_at': self.started_at,
'completed_at': self.completed_at... | [
"def",
"_serialize",
"(",
"self",
",",
"include_run_logs",
"=",
"False",
",",
"strict_json",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'command'",
":",
"self",
".",
"command",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'started_at'",
":",
"self",
... | Serialize a representation of this Task to a Python dict. | [
"Serialize",
"a",
"representation",
"of",
"this",
"Task",
"to",
"a",
"Python",
"dict",
"."
] | python | train | 41.956522 |
pytorch/vision | torchvision/datasets/utils.py | https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/utils.py#L139-L171 | def download_file_from_google_drive(file_id, root, filename=None, md5=None):
"""Download a Google Drive file from and place it in root.
Args:
file_id (str): id of file to be downloaded
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file und... | [
"def",
"download_file_from_google_drive",
"(",
"file_id",
",",
"root",
",",
"filename",
"=",
"None",
",",
"md5",
"=",
"None",
")",
":",
"# Based on https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url",
"import",
"requests",
"url",
"=... | Download a Google Drive file from and place it in root.
Args:
file_id (str): id of file to be downloaded
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under. If None, use the id of the file.
md5 (str, optional): MD5 checksum of th... | [
"Download",
"a",
"Google",
"Drive",
"file",
"from",
"and",
"place",
"it",
"in",
"root",
"."
] | python | test | 37.393939 |
pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/checkstyle.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/checkstyle.py#L215-L240 | def execute(self):
""""Run Checkstyle on all found non-synthetic source files."""
python_tgts = self.context.targets(
lambda tgt: isinstance(tgt, (PythonTarget))
)
if not python_tgts:
return 0
interpreter_cache = PythonInterpreterCache.global_instance()
with self.invalidated(self.get... | [
"def",
"execute",
"(",
"self",
")",
":",
"python_tgts",
"=",
"self",
".",
"context",
".",
"targets",
"(",
"lambda",
"tgt",
":",
"isinstance",
"(",
"tgt",
",",
"(",
"PythonTarget",
")",
")",
")",
"if",
"not",
"python_tgts",
":",
"return",
"0",
"interpre... | Run Checkstyle on all found non-synthetic source files. | [
"Run",
"Checkstyle",
"on",
"all",
"found",
"non",
"-",
"synthetic",
"source",
"files",
"."
] | python | train | 48.961538 |
jmoiron/micromongo | micromongo/models.py | https://github.com/jmoiron/micromongo/blob/0d7dd1396e2f25ece6648619ccff32345bc306a1/micromongo/models.py#L118-L131 | def save(self):
"""Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'pre_save'",
")",
":",
"self",
".",
"pre_save",
"(",
")",
"database",
",",
"collection",
"=",
"self",
".",
"_collection_key",
".",
"split",
"(",
"'.'",
")",
"self",
".",
"valid... | Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
validated against it after ... | [
"Save",
"this",
"object",
"to",
"the",
"database",
".",
"Behaves",
"very",
"similarly",
"to",
"whatever",
"collection",
".",
"save",
"(",
"document",
")",
"would",
"ie",
".",
"does",
"upserts",
"on",
"_id",
"presence",
".",
"If",
"methods",
"pre_save",
"or... | python | train | 49.571429 |
pyviz/holoviews | holoviews/plotting/bokeh/plot.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/plot.py#L156-L177 | def _construct_callbacks(self):
"""
Initializes any callbacks for streams which have defined
the plotted object as a source.
"""
cb_classes = set()
registry = list(Stream.registry.items())
callbacks = Stream._callbacks['bokeh']
for source in self.link_sour... | [
"def",
"_construct_callbacks",
"(",
"self",
")",
":",
"cb_classes",
"=",
"set",
"(",
")",
"registry",
"=",
"list",
"(",
"Stream",
".",
"registry",
".",
"items",
"(",
")",
")",
"callbacks",
"=",
"Stream",
".",
"_callbacks",
"[",
"'bokeh'",
"]",
"for",
"... | Initializes any callbacks for streams which have defined
the plotted object as a source. | [
"Initializes",
"any",
"callbacks",
"for",
"streams",
"which",
"have",
"defined",
"the",
"plotted",
"object",
"as",
"a",
"source",
"."
] | python | train | 45.681818 |
wummel/dosage | scripts/comicgenesis.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/scripts/comicgenesis.py#L421-L431 | def has_comic(name):
"""Check if comic name already exists."""
names = [
("Creators/%s" % name).lower(),
("GoComics/%s" % name).lower(),
]
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname in names:
return True
retur... | [
"def",
"has_comic",
"(",
"name",
")",
":",
"names",
"=",
"[",
"(",
"\"Creators/%s\"",
"%",
"name",
")",
".",
"lower",
"(",
")",
",",
"(",
"\"GoComics/%s\"",
"%",
"name",
")",
".",
"lower",
"(",
")",
",",
"]",
"for",
"scraperclass",
"in",
"get_scraper... | Check if comic name already exists. | [
"Check",
"if",
"comic",
"name",
"already",
"exists",
"."
] | python | train | 28.818182 |
saltstack/salt | salt/modules/win_lgpo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L6542-L6582 | def _admx_policy_parent_walk(path,
policy_namespace,
parent_category,
policy_nsmap,
return_full_policy_names,
adml_language):
'''
helper function to recursively walk u... | [
"def",
"_admx_policy_parent_walk",
"(",
"path",
",",
"policy_namespace",
",",
"parent_category",
",",
"policy_nsmap",
",",
"return_full_policy_names",
",",
"adml_language",
")",
":",
"admx_policy_definitions",
"=",
"_get_policy_definitions",
"(",
"language",
"=",
"adml_la... | helper function to recursively walk up the ADMX namespaces and build the
hierarchy for the policy | [
"helper",
"function",
"to",
"recursively",
"walk",
"up",
"the",
"ADMX",
"namespaces",
"and",
"build",
"the",
"hierarchy",
"for",
"the",
"policy"
] | python | train | 57.268293 |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L30-L58 | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency befo... | [
"def",
"_add_sync_queues_and_barrier",
"(",
"self",
",",
"name",
",",
"dependencies",
")",
":",
"self",
".",
"_sync_queue_counter",
"+=",
"1",
"with",
"tf",
".",
"device",
"(",
"self",
".",
"sync_queue_devices",
"[",
"self",
".",
"_sync_queue_counter",
"%",
"l... | Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step. | [
"Adds",
"ops",
"to",
"enqueue",
"on",
"all",
"worker",
"queues",
"."
] | python | train | 44.931034 |
eddieantonio/perfection | perfection/forest.py | https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/forest.py#L61-L90 | def add_edge(self, edge):
"""
Add edge (u, v) to the graph. Raises InvariantError if adding the edge
would form a cycle.
"""
u, v = edge
both_exist = u in self.vertices and v in self.vertices
# Using `is` because if they belong to the same component, they MUST
... | [
"def",
"add_edge",
"(",
"self",
",",
"edge",
")",
":",
"u",
",",
"v",
"=",
"edge",
"both_exist",
"=",
"u",
"in",
"self",
".",
"vertices",
"and",
"v",
"in",
"self",
".",
"vertices",
"# Using `is` because if they belong to the same component, they MUST",
"# share ... | Add edge (u, v) to the graph. Raises InvariantError if adding the edge
would form a cycle. | [
"Add",
"edge",
"(",
"u",
"v",
")",
"to",
"the",
"graph",
".",
"Raises",
"InvariantError",
"if",
"adding",
"the",
"edge",
"would",
"form",
"a",
"cycle",
"."
] | python | train | 39.533333 |
tensorflow/cleverhans | cleverhans/attacks/bapp.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L161-L213 | def parse_params(self,
y_target=None,
image_target=None,
initial_num_evals=100,
max_num_evals=10000,
stepsize_search='grid_search',
num_iterations=64,
gamma=0.01,
const... | [
"def",
"parse_params",
"(",
"self",
",",
"y_target",
"=",
"None",
",",
"image_target",
"=",
"None",
",",
"initial_num_evals",
"=",
"100",
",",
"max_num_evals",
"=",
"10000",
",",
"stepsize_search",
"=",
"'grid_search'",
",",
"num_iterations",
"=",
"64",
",",
... | :param y: A tensor of shape (1, nb_classes) for true labels.
:param y_target: A tensor of shape (1, nb_classes) for target labels.
Required for targeted attack.
:param image_target: A tensor of shape (1, **image shape) for initial
target images. Required for targeted attack.
:param initial_num_eval... | [
":",
"param",
"y",
":",
"A",
"tensor",
"of",
"shape",
"(",
"1",
"nb_classes",
")",
"for",
"true",
"labels",
".",
":",
"param",
"y_target",
":",
"A",
"tensor",
"of",
"shape",
"(",
"1",
"nb_classes",
")",
"for",
"target",
"labels",
".",
"Required",
"fo... | python | train | 46.301887 |
pgmpy/pgmpy | pgmpy/readwrite/XMLBeliefNetwork.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBeliefNetwork.py#L340-L366 | def set_variables(self, data):
"""
Set variables for the network.
Parameters
----------
data: dict
dict for variable in the form of example as shown.
Examples
--------
>>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter
>>> wri... | [
"def",
"set_variables",
"(",
"self",
",",
"data",
")",
":",
"variables",
"=",
"etree",
".",
"SubElement",
"(",
"self",
".",
"bnmodel",
",",
"\"VARIABLES\"",
")",
"for",
"var",
"in",
"sorted",
"(",
"data",
")",
":",
"variable",
"=",
"etree",
".",
"SubEl... | Set variables for the network.
Parameters
----------
data: dict
dict for variable in the form of example as shown.
Examples
--------
>>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter
>>> writer = XBNWriter()
>>> writer.set_variables(... | [
"Set",
"variables",
"for",
"the",
"network",
"."
] | python | train | 50.62963 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/rst/heilman_sagae_2015.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/rst/heilman_sagae_2015.py#L171-L201 | def parse_hs2015(heilman_filepath):
"""convert the output of the Heilman and Sagae (2015) discourse parser
into a nltk.ParentedTree instance.
Parameters
----------
heilman_filepath : str
path to a file containing the output of Heilman and Sagae's 2015
discourse parser
Returns
... | [
"def",
"parse_hs2015",
"(",
"heilman_filepath",
")",
":",
"with",
"open",
"(",
"heilman_filepath",
",",
"'r'",
")",
"as",
"parsed_file",
":",
"heilman_json",
"=",
"json",
".",
"load",
"(",
"parsed_file",
")",
"edus",
"=",
"heilman_json",
"[",
"'edu_tokens'",
... | convert the output of the Heilman and Sagae (2015) discourse parser
into a nltk.ParentedTree instance.
Parameters
----------
heilman_filepath : str
path to a file containing the output of Heilman and Sagae's 2015
discourse parser
Returns
-------
parented_tree : nltk.Parente... | [
"convert",
"the",
"output",
"of",
"the",
"Heilman",
"and",
"Sagae",
"(",
"2015",
")",
"discourse",
"parser",
"into",
"a",
"nltk",
".",
"ParentedTree",
"instance",
"."
] | python | train | 33.83871 |
mozillazg/baidu-pcs-python-sdk | baidupcs/api.py | https://github.com/mozillazg/baidu-pcs-python-sdk/blob/12fe3f13b2ecda8f8bdcc5334c876e934776a5cc/baidupcs/api.py#L502-L529 | def search(self, remote_path, keyword, recurrent='0', **kwargs):
"""按文件名搜索文件(不支持查找目录).
:param remote_path: 需要检索的目录路径,路径必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
... | [
"def",
"search",
"(",
"self",
",",
"remote_path",
",",
"keyword",
",",
"recurrent",
"=",
"'0'",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'path'",
":",
"remote_path",
",",
"'wd'",
":",
"keyword",
",",
"'re'",
":",
"recurrent",
",",
"}",... | 按文件名搜索文件(不支持查找目录).
:param remote_path: 需要检索的目录路径,路径必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
... | [
"按文件名搜索文件(不支持查找目录)",
"."
] | python | train | 32.607143 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_dai.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_dai.py#L24-L44 | def arp_access_list_permit_permit_list_ip_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
arp = ET.SubElement(config, "arp", xmlns="urn:brocade.com:mgmt:brocade-dai")
access_list = ET.SubElement(arp, "access-list")
acl_name_key = ET.SubEleme... | [
"def",
"arp_access_list_permit_permit_list_ip_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"arp",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"arp\"",
",",
"xmlns",
"=",
"\"urn:... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 48.47619 |
StackStorm/pybind | pybind/nos/v7_2_0/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/__init__.py#L1646-L1667 | def _set_vlag_commit_mode(self, v, load=False):
"""
Setter method for vlag_commit_mode, mapped from YANG variable /vlag_commit_mode (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlag_commit_mode is considered as a private
method. Backends looking to pop... | [
"def",
"_set_vlag_commit_mode",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for vlag_commit_mode, mapped from YANG variable /vlag_commit_mode (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlag_commit_mode is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._se... | [
"Setter",
"method",
"for",
"vlag_commit_mode",
"mapped",
"from",
"YANG",
"variable",
"/",
"vlag_commit_mode",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",... | python | train | 86.181818 |
nickoala/telepot | telepot/delegate.py | https://github.com/nickoala/telepot/blob/3792fde251d0f1d5a6ca16c8ad1a71f89360c41d/telepot/delegate.py#L152-L167 | def per_event_source_id(event_space):
"""
:return:
a seeder function that returns an event's source id only if that event's
source space equals to ``event_space``.
"""
def f(event):
if is_event(event):
v = peel(event)
if v['source']['space'] == event_space... | [
"def",
"per_event_source_id",
"(",
"event_space",
")",
":",
"def",
"f",
"(",
"event",
")",
":",
"if",
"is_event",
"(",
"event",
")",
":",
"v",
"=",
"peel",
"(",
"event",
")",
"if",
"v",
"[",
"'source'",
"]",
"[",
"'space'",
"]",
"==",
"event_space",
... | :return:
a seeder function that returns an event's source id only if that event's
source space equals to ``event_space``. | [
":",
"return",
":",
"a",
"seeder",
"function",
"that",
"returns",
"an",
"event",
"s",
"source",
"id",
"only",
"if",
"that",
"event",
"s",
"source",
"space",
"equals",
"to",
"event_space",
"."
] | python | train | 28.5 |
marcinn/sqltemplate | sqltemplate/contrib/django/loader.py | https://github.com/marcinn/sqltemplate/blob/28d26ebcc474b8c37942218adfa9f54e89327ce0/sqltemplate/contrib/django/loader.py#L11-L23 | def get_template(template_name, using=None):
"""
Loads and returns a template for the given name.
Raises TemplateDoesNotExist if no such template exists.
"""
engines = _engine_list(using)
for engine in engines:
try:
return engine.get_template(template_name)
except Tem... | [
"def",
"get_template",
"(",
"template_name",
",",
"using",
"=",
"None",
")",
":",
"engines",
"=",
"_engine_list",
"(",
"using",
")",
"for",
"engine",
"in",
"engines",
":",
"try",
":",
"return",
"engine",
".",
"get_template",
"(",
"template_name",
")",
"exc... | Loads and returns a template for the given name.
Raises TemplateDoesNotExist if no such template exists. | [
"Loads",
"and",
"returns",
"a",
"template",
"for",
"the",
"given",
"name",
".",
"Raises",
"TemplateDoesNotExist",
"if",
"no",
"such",
"template",
"exists",
"."
] | python | train | 30.384615 |
edx/edx-django-utils | edx_django_utils/cache/utils.py | https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L152-L169 | def get_cached_response(cls, key):
"""
Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value.
"""
request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key)
... | [
"def",
"get_cached_response",
"(",
"cls",
",",
"key",
")",
":",
"request_cached_response",
"=",
"DEFAULT_REQUEST_CACHE",
".",
"get_cached_response",
"(",
"key",
")",
"if",
"not",
"request_cached_response",
".",
"is_found",
":",
"django_cached_response",
"=",
"cls",
... | Retrieves a CachedResponse for the provided key.
Args:
key (string)
Returns:
A CachedResponse with is_found status and value. | [
"Retrieves",
"a",
"CachedResponse",
"for",
"the",
"provided",
"key",
"."
] | python | train | 33.277778 |
UUDigitalHumanitieslab/tei_reader | tei_reader/models/element.py | https://github.com/UUDigitalHumanitieslab/tei_reader/blob/7b19c34a9d7cc941a36ecdcf6f361e26c6488697/tei_reader/models/element.py#L69-L81 | def parts(self):
"""
Get the parts directly below this element.
"""
for item in self.__parts_and_divisions:
if item.tag == 'part':
yield item
else:
# Divisions shouldn't be beneath a part, but here's a fallback
# fo... | [
"def",
"parts",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"__parts_and_divisions",
":",
"if",
"item",
".",
"tag",
"==",
"'part'",
":",
"yield",
"item",
"else",
":",
"# Divisions shouldn't be beneath a part, but here's a fallback",
"# for if this does ... | Get the parts directly below this element. | [
"Get",
"the",
"parts",
"directly",
"below",
"this",
"element",
"."
] | python | train | 30.769231 |
numenta/nupic | src/nupic/algorithms/backtracking_tm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L1018-L1035 | def printConfidence(self, aState, maxCols = 20):
"""
Print a floating point array that is the same shape as activeState.
:param aState: TODO: document
:param maxCols: TODO: document
"""
def formatFPRow(var, i):
s = ''
for c in range(min(maxCols, self.numberOfCols)):
if c > 0... | [
"def",
"printConfidence",
"(",
"self",
",",
"aState",
",",
"maxCols",
"=",
"20",
")",
":",
"def",
"formatFPRow",
"(",
"var",
",",
"i",
")",
":",
"s",
"=",
"''",
"for",
"c",
"in",
"range",
"(",
"min",
"(",
"maxCols",
",",
"self",
".",
"numberOfCols"... | Print a floating point array that is the same shape as activeState.
:param aState: TODO: document
:param maxCols: TODO: document | [
"Print",
"a",
"floating",
"point",
"array",
"that",
"is",
"the",
"same",
"shape",
"as",
"activeState",
"."
] | python | valid | 26.833333 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L555-L594 | def run(self):
"""The thread's main activity. Call start() instead."""
self._create_socket()
self._running = True
self._beating = True
while self._running:
if self._pause:
# just sleep, and skip the rest of the loop
time.sleep... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_create_socket",
"(",
")",
"self",
".",
"_running",
"=",
"True",
"self",
".",
"_beating",
"=",
"True",
"while",
"self",
".",
"_running",
":",
"if",
"self",
".",
"_pause",
":",
"# just sleep, and skip the... | The thread's main activity. Call start() instead. | [
"The",
"thread",
"s",
"main",
"activity",
".",
"Call",
"start",
"()",
"instead",
"."
] | python | test | 39.6 |
AdvancedClimateSystems/uModbus | umodbus/server/serial/__init__.py | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/server/serial/__init__.py#L16-L33 | def get_server(server_class, serial_port):
""" Return instance of :param:`server_class` with :param:`request_handler`
bound to it.
This method also binds a :func:`route` method to the server instance.
>>> server = get_server(TcpServer, ('localhost', 502), RequestHandler)
>>> server.serve_for... | [
"def",
"get_server",
"(",
"server_class",
",",
"serial_port",
")",
":",
"s",
"=",
"server_class",
"(",
")",
"s",
".",
"serial_port",
"=",
"serial_port",
"s",
".",
"route_map",
"=",
"Map",
"(",
")",
"s",
".",
"route",
"=",
"MethodType",
"(",
"route",
",... | Return instance of :param:`server_class` with :param:`request_handler`
bound to it.
This method also binds a :func:`route` method to the server instance.
>>> server = get_server(TcpServer, ('localhost', 502), RequestHandler)
>>> server.serve_forever()
:param server_class: (sub)Class of :clas... | [
"Return",
"instance",
"of",
":",
"param",
":",
"server_class",
"with",
":",
"param",
":",
"request_handler",
"bound",
"to",
"it",
".",
"This",
"method",
"also",
"binds",
"a",
":",
"func",
":",
"route",
"method",
"to",
"the",
"server",
"instance",
".",
">... | python | train | 36.833333 |
kgaughan/dbkit | examples/counters.py | https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/counters.py#L82-L87 | def print_help(filename, table, dest=sys.stdout):
"""
Print help to the given destination file object.
"""
cmds = '|'.join(sorted(table.keys()))
print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds) | [
"def",
"print_help",
"(",
"filename",
",",
"table",
",",
"dest",
"=",
"sys",
".",
"stdout",
")",
":",
"cmds",
"=",
"'|'",
".",
"join",
"(",
"sorted",
"(",
"table",
".",
"keys",
"(",
")",
")",
")",
"print",
">>",
"dest",
",",
"\"Syntax: %s %s [args]\"... | Print help to the given destination file object. | [
"Print",
"help",
"to",
"the",
"given",
"destination",
"file",
"object",
"."
] | python | train | 38.5 |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2120-L2131 | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userlo... | [
"def",
"get_userloved",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
":",
"return",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"username\"",
"]",
"=",
"self",
".",
"username",
"doc",
"=",
"self",
".",
"_reques... | Whether the user loved this track | [
"Whether",
"the",
"user",
"loved",
"this",
"track"
] | python | train | 28.5 |
LogicalDash/LiSE | ELiDE/ELiDE/rulesview.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/rulesview.py#L71-L76 | def on_rulebook(self, *args):
"""Make sure to update when the rulebook changes"""
if self.rulebook is None:
return
self.rulebook.connect(self._trigger_redata, weak=False)
self.redata() | [
"def",
"on_rulebook",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"rulebook",
"is",
"None",
":",
"return",
"self",
".",
"rulebook",
".",
"connect",
"(",
"self",
".",
"_trigger_redata",
",",
"weak",
"=",
"False",
")",
"self",
".",
"red... | Make sure to update when the rulebook changes | [
"Make",
"sure",
"to",
"update",
"when",
"the",
"rulebook",
"changes"
] | python | train | 37.166667 |
InfoAgeTech/django-core | django_core/forms/fields.py | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/forms/fields.py#L130-L142 | def clean(self, value):
"""Validates that the input can be converted to a list of decimals."""
if not value:
return None
# if any value exists, then add "0" as a placeholder to the remaining
# values.
if isinstance(value, list) and any(value):
for i, item... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"# if any value exists, then add \"0\" as a placeholder to the remaining",
"# values.",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"any",
"(",
"value"... | Validates that the input can be converted to a list of decimals. | [
"Validates",
"that",
"the",
"input",
"can",
"be",
"converted",
"to",
"a",
"list",
"of",
"decimals",
"."
] | python | train | 35.076923 |
kata198/ProcessMappingScanner | ProcessMappingScanner/__init__.py | https://github.com/kata198/ProcessMappingScanner/blob/d1735fe6746493c51aaae213b982fa96f5c5b621/ProcessMappingScanner/__init__.py#L25-L50 | def getProcessOwner(pid):
'''
getProcessOwner - Get the process owner of a pid
@param pid <int> - process id
@return - None if process not found or can't be determined. Otherwise, a dict:
{
uid - Owner UID
name - Owner name, or None if one cann... | [
"def",
"getProcessOwner",
"(",
"pid",
")",
":",
"try",
":",
"ownerUid",
"=",
"os",
".",
"stat",
"(",
"'/proc/'",
"+",
"str",
"(",
"pid",
")",
")",
".",
"st_uid",
"except",
":",
"return",
"None",
"try",
":",
"ownerName",
"=",
"pwd",
".",
"getpwuid",
... | getProcessOwner - Get the process owner of a pid
@param pid <int> - process id
@return - None if process not found or can't be determined. Otherwise, a dict:
{
uid - Owner UID
name - Owner name, or None if one cannot be determined
} | [
"getProcessOwner",
"-",
"Get",
"the",
"process",
"owner",
"of",
"a",
"pid"
] | python | valid | 23.230769 |
pudo/jsongraph | jsongraph/graph.py | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L82-L87 | def buffered(self):
""" Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. """
if 'buffered' not in self.config:
return not isinstance(self.store, (Memory, IOMemory))
return self.config.get('buffered') | [
"def",
"buffered",
"(",
"self",
")",
":",
"if",
"'buffered'",
"not",
"in",
"self",
".",
"config",
":",
"return",
"not",
"isinstance",
"(",
"self",
".",
"store",
",",
"(",
"Memory",
",",
"IOMemory",
")",
")",
"return",
"self",
".",
"config",
".",
"get... | Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. | [
"Whether",
"write",
"operations",
"should",
"be",
"buffered",
"i",
".",
"e",
".",
"run",
"against",
"a",
"local",
"graph",
"before",
"being",
"stored",
"to",
"the",
"main",
"data",
"store",
"."
] | python | train | 51.5 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/bases.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/bases.py#L599-L640 | def filter(self, criteria, applyto='measurement', ID=None):
"""
Filter measurements according to given criteria.
Retain only Measurements for which criteria returns True.
TODO: add support for multiple criteria
Parameters
----------
criteria : callable
... | [
"def",
"filter",
"(",
"self",
",",
"criteria",
",",
"applyto",
"=",
"'measurement'",
",",
"ID",
"=",
"None",
")",
":",
"fil",
"=",
"criteria",
"new",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"isinstance",
"(",
"applyto",
",",
"collections",
".",
"Ma... | Filter measurements according to given criteria.
Retain only Measurements for which criteria returns True.
TODO: add support for multiple criteria
Parameters
----------
criteria : callable
Returns bool.
applyto : 'measurement' | 'keys' | 'data' | mapping
... | [
"Filter",
"measurements",
"according",
"to",
"given",
"criteria",
".",
"Retain",
"only",
"Measurements",
"for",
"which",
"criteria",
"returns",
"True",
"."
] | python | train | 37.97619 |
rwl/godot | godot/xdot_parser.py | https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/xdot_parser.py#L342-L348 | def _proc_polygon(self, tokens, filled):
""" Returns the components of a polygon. """
pts = [(p["x"], p["y"]) for p in tokens["points"]]
component = Polygon(pen=self.pen, points=pts, filled=filled)
return component | [
"def",
"_proc_polygon",
"(",
"self",
",",
"tokens",
",",
"filled",
")",
":",
"pts",
"=",
"[",
"(",
"p",
"[",
"\"x\"",
"]",
",",
"p",
"[",
"\"y\"",
"]",
")",
"for",
"p",
"in",
"tokens",
"[",
"\"points\"",
"]",
"]",
"component",
"=",
"Polygon",
"("... | Returns the components of a polygon. | [
"Returns",
"the",
"components",
"of",
"a",
"polygon",
"."
] | python | test | 34.571429 |
ioos/compliance-checker | compliance_checker/cf/cf.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cf/cf.py#L154-L215 | def _find_cf_standard_name_table(self, ds):
'''
Parse out the `standard_name_vocabulary` attribute and download that
version of the cf standard name table. If the standard name table has
already been downloaded, use the cached version. Modifies `_std_names`
attribute to store s... | [
"def",
"_find_cf_standard_name_table",
"(",
"self",
",",
"ds",
")",
":",
"# Get the standard name vocab",
"standard_name_vocabulary",
"=",
"getattr",
"(",
"ds",
",",
"'standard_name_vocabulary'",
",",
"''",
")",
"# Try to parse this attribute to get version",
"version",
"="... | Parse out the `standard_name_vocabulary` attribute and download that
version of the cf standard name table. If the standard name table has
already been downloaded, use the cached version. Modifies `_std_names`
attribute to store standard names. Returns True if the file exists and
Fals... | [
"Parse",
"out",
"the",
"standard_name_vocabulary",
"attribute",
"and",
"download",
"that",
"version",
"of",
"the",
"cf",
"standard",
"name",
"table",
".",
"If",
"the",
"standard",
"name",
"table",
"has",
"already",
"been",
"downloaded",
"use",
"the",
"cached",
... | python | train | 48.016129 |
pyvisa/pyvisa | pyvisa/highlevel.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/highlevel.py#L1028-L1048 | def parse_resource_extended(self, session, resource_name):
"""Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
... | [
"def",
"parse_resource_extended",
"(",
"self",
",",
"session",
",",
"resource_name",
")",
":",
"try",
":",
"parsed",
"=",
"rname",
".",
"parse_resource_name",
"(",
"resource_name",
")",
"return",
"(",
"ResourceInfo",
"(",
"parsed",
".",
"interface_type_const",
"... | Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
returned from open_default_resource_manager()).
:pa... | [
"Parse",
"a",
"resource",
"string",
"to",
"get",
"extended",
"interface",
"information",
"."
] | python | train | 49.714286 |
ucsb-cs-education/hairball | hairball/plugins/checks.py | https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L28-L62 | def check_results(tmp_):
"""Return a 3 tuple for something."""
# TODO: Fix this to work with more meaningful names
if tmp_['t'] > 0:
if tmp_['l'] > 0:
if tmp_['rr'] > 0 or tmp_['ra'] > 1:
print 1, 3, tmp_
return 3
... | [
"def",
"check_results",
"(",
"tmp_",
")",
":",
"# TODO: Fix this to work with more meaningful names",
"if",
"tmp_",
"[",
"'t'",
"]",
">",
"0",
":",
"if",
"tmp_",
"[",
"'l'",
"]",
">",
"0",
":",
"if",
"tmp_",
"[",
"'rr'",
"]",
">",
"0",
"or",
"tmp_",
"[... | Return a 3 tuple for something. | [
"Return",
"a",
"3",
"tuple",
"for",
"something",
"."
] | python | train | 36.028571 |
FirefighterBlu3/python-pam | pam.py | https://github.com/FirefighterBlu3/python-pam/blob/fe44b334970f421635d9e373b563c9e6566613bd/pam.py#L106-L191 | def authenticate(self, username, password, service='login', encoding='utf-8', resetcreds=True):
"""username and password authentication for the given service.
Returns True for success, or False for failure.
self.code (integer) and self.reason (string) are always stored and may
... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
",",
"password",
",",
"service",
"=",
"'login'",
",",
"encoding",
"=",
"'utf-8'",
",",
"resetcreds",
"=",
"True",
")",
":",
"@",
"conv_func",
"def",
"my_conv",
"(",
"n_messages",
",",
"messages",
",",
... | username and password authentication for the given service.
Returns True for success, or False for failure.
self.code (integer) and self.reason (string) are always stored and may
be referenced for the reason why authentication failed. 0/'Success' will
be stored for success.... | [
"username",
"and",
"password",
"authentication",
"for",
"the",
"given",
"service",
"."
] | python | train | 39.674419 |
sveetch/django-feedparser | django_feedparser/templatetags/feedparser_tags.py | https://github.com/sveetch/django-feedparser/blob/78be6a3ea095a90e4b28cad1b8893ddf1febf60e/django_feedparser/templatetags/feedparser_tags.py#L14-L31 | def feedparser_render(url, *args, **kwargs):
"""
Render a feed and return its builded html
Usage: ::
{% feedparser_render 'http://localhost/sample.xml' %}
Or with all accepted arguments: ::
{% feedparser_render 'http://localhost/sample.xml' renderer='CustomRenderer' t... | [
"def",
"feedparser_render",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer_name",
"=",
"kwargs",
".",
"get",
"(",
"'renderer'",
",",
"settings",
".",
"FEED_DEFAULT_RENDERER_ENGINE",
")",
"renderer_template",
"=",
"kwargs",
".",
"g... | Render a feed and return its builded html
Usage: ::
{% feedparser_render 'http://localhost/sample.xml' %}
Or with all accepted arguments: ::
{% feedparser_render 'http://localhost/sample.xml' renderer='CustomRenderer' template='foo/custom.html' expiration=3600 %} | [
"Render",
"a",
"feed",
"and",
"return",
"its",
"builded",
"html",
"Usage",
":",
"::",
"{",
"%",
"feedparser_render",
"http",
":",
"//",
"localhost",
"/",
"sample",
".",
"xml",
"%",
"}",
"Or",
"with",
"all",
"accepted",
"arguments",
":",
"::",
"{",
"%",... | python | train | 39.055556 |
klmitch/tendril | tendril/framers.py | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/framers.py#L343-L378 | def frameify(self, state, data):
"""Split data into a sequence of frames."""
# Pull in any partially-processed data
data = state.recv_buf + data
# Loop over the data
while data:
if state.frame_len is None:
# Try to grab a frame length from the data
... | [
"def",
"frameify",
"(",
"self",
",",
"state",
",",
"data",
")",
":",
"# Pull in any partially-processed data",
"data",
"=",
"state",
".",
"recv_buf",
"+",
"data",
"# Loop over the data",
"while",
"data",
":",
"if",
"state",
".",
"frame_len",
"is",
"None",
":",... | Split data into a sequence of frames. | [
"Split",
"data",
"into",
"a",
"sequence",
"of",
"frames",
"."
] | python | train | 31.333333 |
fake-name/ChromeController | ChromeController/Generator/Generated.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L4517-L4533 | def DOMDebugger_removeDOMBreakpoint(self, nodeId, type):
"""
Function path: DOMDebugger.removeDOMBreakpoint
Domain: DOMDebugger
Method name: removeDOMBreakpoint
Parameters:
Required arguments:
'nodeId' (type: DOM.NodeId) -> Identifier of the node to remove breakpoint from.
'type' (type: DO... | [
"def",
"DOMDebugger_removeDOMBreakpoint",
"(",
"self",
",",
"nodeId",
",",
"type",
")",
":",
"subdom_funcs",
"=",
"self",
".",
"synchronous_command",
"(",
"'DOMDebugger.removeDOMBreakpoint'",
",",
"nodeId",
"=",
"nodeId",
",",
"type",
"=",
"type",
")",
"return",
... | Function path: DOMDebugger.removeDOMBreakpoint
Domain: DOMDebugger
Method name: removeDOMBreakpoint
Parameters:
Required arguments:
'nodeId' (type: DOM.NodeId) -> Identifier of the node to remove breakpoint from.
'type' (type: DOMBreakpointType) -> Type of the breakpoint to remove.
No retur... | [
"Function",
"path",
":",
"DOMDebugger",
".",
"removeDOMBreakpoint",
"Domain",
":",
"DOMDebugger",
"Method",
"name",
":",
"removeDOMBreakpoint",
"Parameters",
":",
"Required",
"arguments",
":",
"nodeId",
"(",
"type",
":",
"DOM",
".",
"NodeId",
")",
"-",
">",
"I... | python | train | 35.647059 |
acorg/dark-matter | bin/aa-info.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/aa-info.py#L13-L28 | def findOrDie(s):
"""
Look up an amino acid.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
@return: An C{AminoAcid} instance, if one can be found. Else exit.
"""
aa = find(s)
if aa:
retu... | [
"def",
"findOrDie",
"(",
"s",
")",
":",
"aa",
"=",
"find",
"(",
"s",
")",
"if",
"aa",
":",
"return",
"aa",
"else",
":",
"print",
"(",
"'Unknown amino acid or codon: %s'",
"%",
"s",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"'Valid ar... | Look up an amino acid.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
@return: An C{AminoAcid} instance, if one can be found. Else exit. | [
"Look",
"up",
"an",
"amino",
"acid",
"."
] | python | train | 31.5625 |
dwaiter/django-bcrypt | django_bcrypt/models.py | https://github.com/dwaiter/django-bcrypt/blob/913d86b2ba71334fd54670c6f0050bec02689654/django_bcrypt/models.py#L39-L47 | def is_enabled():
"""Returns ``True`` if bcrypt should be used."""
enabled = getattr(settings, "BCRYPT_ENABLED", True)
if not enabled:
return False
# Are we under a test?
if hasattr(mail, 'outbox'):
return getattr(settings, "BCRYPT_ENABLED_UNDER_TEST", False)
return True | [
"def",
"is_enabled",
"(",
")",
":",
"enabled",
"=",
"getattr",
"(",
"settings",
",",
"\"BCRYPT_ENABLED\"",
",",
"True",
")",
"if",
"not",
"enabled",
":",
"return",
"False",
"# Are we under a test?",
"if",
"hasattr",
"(",
"mail",
",",
"'outbox'",
")",
":",
... | Returns ``True`` if bcrypt should be used. | [
"Returns",
"True",
"if",
"bcrypt",
"should",
"be",
"used",
"."
] | python | train | 33.666667 |
swharden/SWHLab | swhlab/indexing/index_OLD.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/indexing/index_OLD.py#L30-L44 | def filesByCell(fnames,cells):
"""given files and cells, return a dict of files grouped by cell."""
byCell={}
fnames=smartSort(fnames)
days = list(set([elem[:5] for elem in fnames if elem.endswith(".abf")])) # so pythonic!
for day in smartSort(days):
parent=None
for i,fname in enumer... | [
"def",
"filesByCell",
"(",
"fnames",
",",
"cells",
")",
":",
"byCell",
"=",
"{",
"}",
"fnames",
"=",
"smartSort",
"(",
"fnames",
")",
"days",
"=",
"list",
"(",
"set",
"(",
"[",
"elem",
"[",
":",
"5",
"]",
"for",
"elem",
"in",
"fnames",
"if",
"ele... | given files and cells, return a dict of files grouped by cell. | [
"given",
"files",
"and",
"cells",
"return",
"a",
"dict",
"of",
"files",
"grouped",
"by",
"cell",
"."
] | python | valid | 43.8 |
fmfn/BayesianOptimization | bayes_opt/util.py | https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/util.py#L130-L156 | def load_logs(optimizer, logs):
"""Load previous ...
"""
import json
if isinstance(logs, str):
logs = [logs]
for log in logs:
with open(log, "r") as j:
while True:
try:
iteration = next(j)
except StopIteration:
... | [
"def",
"load_logs",
"(",
"optimizer",
",",
"logs",
")",
":",
"import",
"json",
"if",
"isinstance",
"(",
"logs",
",",
"str",
")",
":",
"logs",
"=",
"[",
"logs",
"]",
"for",
"log",
"in",
"logs",
":",
"with",
"open",
"(",
"log",
",",
"\"r\"",
")",
"... | Load previous ... | [
"Load",
"previous",
"..."
] | python | train | 23.37037 |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2122-L2141 | def get_revoked(self):
"""
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tup... | [
"def",
"get_revoked",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"revoked_stack",
"=",
"_lib",
".",
"X509_CRL_get_REVOKED",
"(",
"self",
".",
"_crl",
")",
"for",
"i",
"in",
"range",
"(",
"_lib",
".",
"sk_X509_REVOKED_num",
"(",
"revoked_stack",
")",
... | Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tuple` of :class:`Revocation` | [
"Return",
"the",
"revocations",
"in",
"this",
"certificate",
"revocation",
"list",
"."
] | python | test | 41.6 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L892-L929 | def _InternalUnpackAny(msg):
"""Unpacks Any message and returns the unpacked message.
This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
... | [
"def",
"_InternalUnpackAny",
"(",
"msg",
")",
":",
"# TODO(amauryfa): Don't use the factory of generated messages.",
"# To make Any work with custom factories, use the message factory of the",
"# parent message.",
"# pylint: disable=g-import-not-at-top",
"from",
"google",
".",
"protobuf",
... | Unpacks Any message and returns the unpacked message.
This internal method is different from public Any Unpack method which takes
the target message as argument. _InternalUnpackAny method does not have
target message type and need to find the message type in descriptor pool.
Args:
msg: An Any message to b... | [
"Unpacks",
"Any",
"message",
"and",
"returns",
"the",
"unpacked",
"message",
"."
] | python | train | 28.631579 |
msmbuilder/osprey | osprey/fit_estimator.py | https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/fit_estimator.py#L22-L93 | def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None,
iid=True, n_jobs=1, verbose=1,
pre_dispatch='2*n_jobs'):
"""Fit and score an estimator with cross-validation
This function is basically a copy of sklearn's
model_selection... | [
"def",
"fit_and_score_estimator",
"(",
"estimator",
",",
"parameters",
",",
"cv",
",",
"X",
",",
"y",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"iid",
"=",
"True",
",",
"n_jobs",
"=",
"1",
",",
"verbose",
"=",
"1",
",",
"pre_dispatch",
"=",
"'2*... | Fit and score an estimator with cross-validation
This function is basically a copy of sklearn's
model_selection._BaseSearchCV._fit(), which is the core of the GridSearchCV
fit() method. Unfortunately, that class does _not_ return the training
set scores, which we want to save in the database, and becau... | [
"Fit",
"and",
"score",
"an",
"estimator",
"with",
"cross",
"-",
"validation"
] | python | valid | 44.888889 |
saltstack/salt | salt/modules/freebsdkmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdkmod.py#L110-L127 | def available():
'''
Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available
'''
ret = []
for path in __salt__['file.find']('/boot/kernel', name='*.ko$'):
bpath = os.path.basename(path)
comps = bpath.split('.')
... | [
"def",
"available",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"path",
"in",
"__salt__",
"[",
"'file.find'",
"]",
"(",
"'/boot/kernel'",
",",
"name",
"=",
"'*.ko$'",
")",
":",
"bpath",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"co... | Return a list of all available kernel modules
CLI Example:
.. code-block:: bash
salt '*' kmod.available | [
"Return",
"a",
"list",
"of",
"all",
"available",
"kernel",
"modules"
] | python | train | 26.222222 |
bradmontgomery/django-redis-metrics | redis_metrics/utils.py | https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/utils.py#L18-L20 | def set_metric(slug, value, category=None, expire=None, date=None):
"""Create/Increment a metric."""
get_r().set_metric(slug, value, category=category, expire=expire, date=date) | [
"def",
"set_metric",
"(",
"slug",
",",
"value",
",",
"category",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"get_r",
"(",
")",
".",
"set_metric",
"(",
"slug",
",",
"value",
",",
"category",
"=",
"category",
",",
"e... | Create/Increment a metric. | [
"Create",
"/",
"Increment",
"a",
"metric",
"."
] | python | train | 61 |
bxlab/bx-python | lib/bx_extras/fpconst.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/fpconst.py#L45-L50 | def _double_as_bytes(dval):
"Use struct.unpack to decode a double precision float into eight bytes"
tmp = list(struct.unpack('8B',struct.pack('d', dval)))
if not _big_endian:
tmp.reverse()
return tmp | [
"def",
"_double_as_bytes",
"(",
"dval",
")",
":",
"tmp",
"=",
"list",
"(",
"struct",
".",
"unpack",
"(",
"'8B'",
",",
"struct",
".",
"pack",
"(",
"'d'",
",",
"dval",
")",
")",
")",
"if",
"not",
"_big_endian",
":",
"tmp",
".",
"reverse",
"(",
")",
... | Use struct.unpack to decode a double precision float into eight bytes | [
"Use",
"struct",
".",
"unpack",
"to",
"decode",
"a",
"double",
"precision",
"float",
"into",
"eight",
"bytes"
] | python | train | 36.333333 |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L378-L386 | def routing(name, **kwargs):
"""
Show information about the requested routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('routing', **{
'name': name,
'locator': ctx.locator,
}) | [
"def",
"routing",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'routing'",
",",
"*",
"*",
"{",
"'name'",
":",
"name",
",",
"'locator'",
":",
"ctx",
".",
"... | Show information about the requested routing group. | [
"Show",
"information",
"about",
"the",
"requested",
"routing",
"group",
"."
] | python | train | 24.333333 |
openvax/isovar | isovar/protein_sequences.py | https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/protein_sequences.py#L163-L180 | def ascending_sort_key(self):
"""
Sort protein sequences lexicographically by three criteria:
- number of unique supporting reads
- minimum mismatch versus a supporting reference transcript before variant
- minimum mismatch versus a supporting reference transcript aft... | [
"def",
"ascending_sort_key",
"(",
"self",
")",
":",
"return",
"(",
"len",
"(",
"self",
".",
"alt_reads_supporting_protein_sequence",
")",
",",
"min",
"(",
"t",
".",
"number_mismatches_before_variant",
"for",
"t",
"in",
"self",
".",
"translations",
")",
",",
"m... | Sort protein sequences lexicographically by three criteria:
- number of unique supporting reads
- minimum mismatch versus a supporting reference transcript before variant
- minimum mismatch versus a supporting reference transcript after variant
- number of supporting refe... | [
"Sort",
"protein",
"sequences",
"lexicographically",
"by",
"three",
"criteria",
":",
"-",
"number",
"of",
"unique",
"supporting",
"reads",
"-",
"minimum",
"mismatch",
"versus",
"a",
"supporting",
"reference",
"transcript",
"before",
"variant",
"-",
"minimum",
"mis... | python | train | 46 |
riga/law | law/workflow/base.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/workflow/base.py#L78-L85 | def requires(self):
"""
Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method.
"""
reqs = OrderedDict()
reqs.update(self.task.workflow_requires())
return reqs | [
"def",
"requires",
"(",
"self",
")",
":",
"reqs",
"=",
"OrderedDict",
"(",
")",
"reqs",
".",
"update",
"(",
"self",
".",
"task",
".",
"workflow_requires",
"(",
")",
")",
"return",
"reqs"
] | Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method. | [
"Returns",
"the",
"default",
"workflow",
"requirements",
"in",
"an",
"ordered",
"dictionary",
"which",
"is",
"updated",
"with",
"the",
"return",
"value",
"of",
"the",
"task",
"s",
"*",
"workflow_requires",
"*",
"method",
"."
] | python | train | 37.625 |
rodluger/everest | everest/basecamp.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/basecamp.py#L57-L70 | def show(self):
"""Show the overfitting PDF summary."""
try:
if platform.system().lower().startswith('darwin'):
subprocess.call(['open', self.pdf])
elif os.name == 'nt':
os.startfile(self.pdf)
elif os.name == 'posix':
su... | [
"def",
"show",
"(",
"self",
")",
":",
"try",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'darwin'",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'open'",
",",
"self",
".",
"pdf",
"]",
")",
... | Show the overfitting PDF summary. | [
"Show",
"the",
"overfitting",
"PDF",
"summary",
"."
] | python | train | 37.428571 |
encode/uvicorn | uvicorn/protocols/websockets/websockets_impl.py | https://github.com/encode/uvicorn/blob/b4c138910bb63475efd028627e10adda722e4937/uvicorn/protocols/websockets/websockets_impl.py#L140-L167 | async def run_asgi(self):
"""
Wrapper around the ASGI callable, handling exceptions and unexpected
termination states.
"""
try:
result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
except BaseException as exc:
self.closed_event.se... | [
"async",
"def",
"run_asgi",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"await",
"self",
".",
"app",
"(",
"self",
".",
"scope",
",",
"self",
".",
"asgi_receive",
",",
"self",
".",
"asgi_send",
")",
"except",
"BaseException",
"as",
"exc",
":",
"... | Wrapper around the ASGI callable, handling exceptions and unexpected
termination states. | [
"Wrapper",
"around",
"the",
"ASGI",
"callable",
"handling",
"exceptions",
"and",
"unexpected",
"termination",
"states",
"."
] | python | train | 41.785714 |
Metatab/metapack | metapack/jupyter/magic.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/magic.py#L41-L59 | def fill_categorical_na(df, nan_cat='NA'):
"""Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks """
for col in df.columns[df.isna().any()].tolist():
if df[col].dtype.name != 'category':
# If not categorical, fill with a blank, which creates a... | [
"def",
"fill_categorical_na",
"(",
"df",
",",
"nan_cat",
"=",
"'NA'",
")",
":",
"for",
"col",
"in",
"df",
".",
"columns",
"[",
"df",
".",
"isna",
"(",
")",
".",
"any",
"(",
")",
"]",
".",
"tolist",
"(",
")",
":",
"if",
"df",
"[",
"col",
"]",
... | Fill categoricals with 'NA', possibly creating a new category,
and fill other NaNa with blanks | [
"Fill",
"categoricals",
"with",
"NA",
"possibly",
"creating",
"a",
"new",
"category",
"and",
"fill",
"other",
"NaNa",
"with",
"blanks"
] | python | train | 31.157895 |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/tree.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L190-L215 | def tags(self):
""" Yields a list of all the token tags as they appeared when the word was parsed.
For example: ["was", "VBD", "B-VP", "O", "VP-1", "A1", "be"]
"""
# See also. Sentence.__repr__().
ch, I,O,B = self.chunk, INSIDE+"-", OUTSIDE, BEGIN+"-"
tags = [OUTSIDE ... | [
"def",
"tags",
"(",
"self",
")",
":",
"# See also. Sentence.__repr__().",
"ch",
",",
"I",
",",
"O",
",",
"B",
"=",
"self",
".",
"chunk",
",",
"INSIDE",
"+",
"\"-\"",
",",
"OUTSIDE",
",",
"BEGIN",
"+",
"\"-\"",
"tags",
"=",
"[",
"OUTSIDE",
"for",
"i",... | Yields a list of all the token tags as they appeared when the word was parsed.
For example: ["was", "VBD", "B-VP", "O", "VP-1", "A1", "be"] | [
"Yields",
"a",
"list",
"of",
"all",
"the",
"token",
"tags",
"as",
"they",
"appeared",
"when",
"the",
"word",
"was",
"parsed",
".",
"For",
"example",
":",
"[",
"was",
"VBD",
"B",
"-",
"VP",
"O",
"VP",
"-",
"1",
"A1",
"be",
"]"
] | python | train | 52.153846 |
tBuLi/symfit | symfit/core/minimizers.py | https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/core/minimizers.py#L566-L584 | def _get_jacobian_hessian_strategy(self):
"""
Figure out how to calculate the jacobian and hessian. Will return a
tuple describing how best to calculate the jacobian and hessian,
repectively. If None, it should be calculated using the available
analytical method.
:return... | [
"def",
"_get_jacobian_hessian_strategy",
"(",
"self",
")",
":",
"if",
"self",
".",
"jacobian",
"is",
"not",
"None",
"and",
"self",
".",
"hessian",
"is",
"None",
":",
"jacobian",
"=",
"None",
"hessian",
"=",
"'cs'",
"elif",
"self",
".",
"jacobian",
"is",
... | Figure out how to calculate the jacobian and hessian. Will return a
tuple describing how best to calculate the jacobian and hessian,
repectively. If None, it should be calculated using the available
analytical method.
:return: tuple of jacobian_method, hessian_method | [
"Figure",
"out",
"how",
"to",
"calculate",
"the",
"jacobian",
"and",
"hessian",
".",
"Will",
"return",
"a",
"tuple",
"describing",
"how",
"best",
"to",
"calculate",
"the",
"jacobian",
"and",
"hessian",
"repectively",
".",
"If",
"None",
"it",
"should",
"be",
... | python | train | 38.315789 |
data-8/datascience | datascience/maps.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/maps.py#L191-L196 | def format(self, **kwargs):
"""Apply formatting."""
attrs = self._attrs.copy()
attrs.update({'width': self._width, 'height': self._height})
attrs.update(kwargs)
return Map(self._features, **attrs) | [
"def",
"format",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"self",
".",
"_attrs",
".",
"copy",
"(",
")",
"attrs",
".",
"update",
"(",
"{",
"'width'",
":",
"self",
".",
"_width",
",",
"'height'",
":",
"self",
".",
"_height",
"}... | Apply formatting. | [
"Apply",
"formatting",
"."
] | python | train | 38.5 |
google/dotty | efilter/scope.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/scope.py#L172-L186 | def reflect_runtime_member(self, name):
"""Reflect 'name' using ONLY runtime reflection.
You most likely want to use ScopeStack.reflect instead.
Returns:
Type of 'name', or protocol.AnyType.
"""
for scope in reversed(self.scopes):
try:
re... | [
"def",
"reflect_runtime_member",
"(",
"self",
",",
"name",
")",
":",
"for",
"scope",
"in",
"reversed",
"(",
"self",
".",
"scopes",
")",
":",
"try",
":",
"return",
"structured",
".",
"reflect_runtime_member",
"(",
"scope",
",",
"name",
")",
"except",
"(",
... | Reflect 'name' using ONLY runtime reflection.
You most likely want to use ScopeStack.reflect instead.
Returns:
Type of 'name', or protocol.AnyType. | [
"Reflect",
"name",
"using",
"ONLY",
"runtime",
"reflection",
"."
] | python | train | 32.2 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L1147-L1178 | def install(self, install_options, global_options=()):
"""Install everything in this set (after having downloaded and unpacked the packages)"""
to_install = [r for r in self.requirements.values()
if not r.satisfied_by]
if to_install:
logger.notify('Installing c... | [
"def",
"install",
"(",
"self",
",",
"install_options",
",",
"global_options",
"=",
"(",
")",
")",
":",
"to_install",
"=",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"requirements",
".",
"values",
"(",
")",
"if",
"not",
"r",
".",
"satisfied_by",
"]",
"i... | Install everything in this set (after having downloaded and unpacked the packages) | [
"Install",
"everything",
"in",
"this",
"set",
"(",
"after",
"having",
"downloaded",
"and",
"unpacked",
"the",
"packages",
")"
] | python | test | 46.9375 |
libtcod/python-tcod | tcod/libtcodpy.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L3992-L4006 | def sys_save_screenshot(name: Optional[str] = None) -> None:
"""Save a screenshot to a file.
By default this will automatically save screenshots in the working
directory.
The automatic names are formatted as screenshotNNN.png. For example:
screenshot000.png, screenshot001.png, etc. Whichever is ... | [
"def",
"sys_save_screenshot",
"(",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_bytes",
"(",
"name",
")",
"if",
"name",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
")... | Save a screenshot to a file.
By default this will automatically save screenshots in the working
directory.
The automatic names are formatted as screenshotNNN.png. For example:
screenshot000.png, screenshot001.png, etc. Whichever is available first.
Args:
file Optional[AnyStr]: File path... | [
"Save",
"a",
"screenshot",
"to",
"a",
"file",
"."
] | python | train | 33.133333 |
marcomusy/vtkplotter | vtkplotter/colors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L360-L383 | def makePalette(color1, color2, N, hsv=True):
"""
Generate N colors starting from `color1` to `color2`
by linear interpolation HSV in or RGB spaces.
:param int N: number of output colors.
:param color1: first rgb color.
:param color2: second rgb color.
:param bool hsv: if `False`, interpola... | [
"def",
"makePalette",
"(",
"color1",
",",
"color2",
",",
"N",
",",
"hsv",
"=",
"True",
")",
":",
"if",
"hsv",
":",
"color1",
"=",
"rgb2hsv",
"(",
"color1",
")",
"color2",
"=",
"rgb2hsv",
"(",
"color2",
")",
"c1",
"=",
"np",
".",
"array",
"(",
"ge... | Generate N colors starting from `color1` to `color2`
by linear interpolation HSV in or RGB spaces.
:param int N: number of output colors.
:param color1: first rgb color.
:param color2: second rgb color.
:param bool hsv: if `False`, interpolation is calculated in RGB space.
.. hint:: Example: |... | [
"Generate",
"N",
"colors",
"starting",
"from",
"color1",
"to",
"color2",
"by",
"linear",
"interpolation",
"HSV",
"in",
"or",
"RGB",
"spaces",
"."
] | python | train | 30.166667 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1020-L1066 | def get_hdu(uri, cutout=None):
"""Get a at the given uri from VOSpace, possibly doing a cutout.
If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the
datasec to reflect the cutout area being used.
@param uri: The URI in VOSpace of the image to HDU to r... | [
"def",
"get_hdu",
"(",
"uri",
",",
"cutout",
"=",
"None",
")",
":",
"try",
":",
"# the filename is based on the Simple FITS images file.",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"uri",
")",
"if",
"os",
".",
"access",
"(",
"filename",
",",
... | Get a at the given uri from VOSpace, possibly doing a cutout.
If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the
datasec to reflect the cutout area being used.
@param uri: The URI in VOSpace of the image to HDU to retrieve.
@param cutout: A CADC dat... | [
"Get",
"a",
"at",
"the",
"given",
"uri",
"from",
"VOSpace",
"possibly",
"doing",
"a",
"cutout",
"."
] | python | train | 44.723404 |
3ll3d00d/vibe | backend/src/recorder/resources/measurements.py | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/recorder/resources/measurements.py#L84-L95 | def delete(self, deviceId, measurementId):
"""
Deletes a stored measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was deleted, 400 if no such measurement (or device).
"""
record = self.measur... | [
"def",
"delete",
"(",
"self",
",",
"deviceId",
",",
"measurementId",
")",
":",
"record",
"=",
"self",
".",
"measurements",
".",
"get",
"(",
"deviceId",
")",
"if",
"record",
"is",
"not",
"None",
":",
"popped",
"=",
"record",
".",
"pop",
"(",
"measuremen... | Deletes a stored measurement.
:param deviceId: the device to measure.
:param measurementId: the name of the measurement.
:return: 200 if it was deleted, 400 if no such measurement (or device). | [
"Deletes",
"a",
"stored",
"measurement",
".",
":",
"param",
"deviceId",
":",
"the",
"device",
"to",
"measure",
".",
":",
"param",
"measurementId",
":",
"the",
"name",
"of",
"the",
"measurement",
".",
":",
"return",
":",
"200",
"if",
"it",
"was",
"deleted... | python | train | 40.666667 |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L562-L567 | def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser()) | [
"def",
"xmltreefromfile",
"(",
"filename",
")",
":",
"try",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"filename",
",",
"ElementTree",
".",
"XMLParser",
"(",
"collect_ids",
"=",
"False",
")",
")",
"except",
"TypeError",
":",
"return",
"ElementTree",
".... | Internal function to read an XML file | [
"Internal",
"function",
"to",
"read",
"an",
"XML",
"file"
] | python | train | 42.833333 |
pydata/xarray | xarray/core/dataset.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L1251-L1323 | def to_netcdf(self, path=None, mode='w', format=None, group=None,
engine=None, encoding=None, unlimited_dims=None,
compute=True):
"""Write dataset contents to a netCDF file.
Parameters
----------
path : str, Path or file-like object, optional
... | [
"def",
"to_netcdf",
"(",
"self",
",",
"path",
"=",
"None",
",",
"mode",
"=",
"'w'",
",",
"format",
"=",
"None",
",",
"group",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"unlimited_dims",
"=",
"None",
",",
"compute",
... | Write dataset contents to a netCDF file.
Parameters
----------
path : str, Path or file-like object, optional
Path to which to save this dataset. File-like objects are only
supported by the scipy engine. If no path is provided, this
function returns the resul... | [
"Write",
"dataset",
"contents",
"to",
"a",
"netCDF",
"file",
"."
] | python | train | 53.232877 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.