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 |
|---|---|---|---|---|---|---|---|---|---|
shapiromatron/bmds | bmds/drunner.py | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/drunner.py#L41-L87 | def execute_job(self, obj):
"""
Execute the BMDS model and parse outputs if successful.
"""
# get executable path
exe = session.BMDS.get_model(obj["bmds_version"], obj["model_name"]).get_exe_path()
# write dfile
dfile = self.tempfiles.get_tempfile(prefix="bmds-d... | [
"def",
"execute_job",
"(",
"self",
",",
"obj",
")",
":",
"# get executable path",
"exe",
"=",
"session",
".",
"BMDS",
".",
"get_model",
"(",
"obj",
"[",
"\"bmds_version\"",
"]",
",",
"obj",
"[",
"\"model_name\"",
"]",
")",
".",
"get_exe_path",
"(",
")",
... | Execute the BMDS model and parse outputs if successful. | [
"Execute",
"the",
"BMDS",
"model",
"and",
"parse",
"outputs",
"if",
"successful",
"."
] | python | train | 31 |
googledatalab/pydatalab | google/datalab/contrib/mlworkbench/_prediction_explainer.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L103-L128 | def _preprocess_data_for_tabular_explain(self, df, categories):
"""Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be nu... | [
"def",
"_preprocess_data_for_tabular_explain",
"(",
"self",
",",
"df",
",",
"categories",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"# Remove non tabular columns (text, image).",
"for",
"col",
"in",
"list",
"(",
"df",
".",
"columns",
")",
":",
"if",
... | Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be numpy arrays, with all categorical values
converted to indices. It al... | [
"Get",
"preprocessed",
"training",
"set",
"in",
"numpy",
"array",
"and",
"categorical",
"names",
"from",
"raw",
"training",
"data",
"."
] | python | train | 46.769231 |
mwouts/jupytext | demo/Matplotlib example.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/demo/Matplotlib example.py#L84-L178 | def stack_hist(ax, stacked_data, sty_cycle, bottoms=None,
hist_func=None, labels=None,
plot_func=None, plot_kwargs=None):
"""
ax : axes.Axes
The axes to add artists too
stacked_data : array or Mapping
A (N, M) shaped array. The first dimension will be iterated... | [
"def",
"stack_hist",
"(",
"ax",
",",
"stacked_data",
",",
"sty_cycle",
",",
"bottoms",
"=",
"None",
",",
"hist_func",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"plot_func",
"=",
"None",
",",
"plot_kwargs",
"=",
"None",
")",
":",
"# deal with default bi... | ax : axes.Axes
The axes to add artists too
stacked_data : array or Mapping
A (N, M) shaped array. The first dimension will be iterated over to
compute histograms row-wise
sty_cycle : Cycler or operable of dict
Style to apply to each set
bottoms : array, optional
T... | [
"ax",
":",
"axes",
".",
"Axes",
"The",
"axes",
"to",
"add",
"artists",
"too"
] | python | train | 30.189474 |
gwastro/pycbc | pycbc/inference/models/base.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/models/base.py#L397-L407 | def sampling_params(self):
"""Returns the sampling parameters.
If ``sampling_transforms`` is None, this is the same as the
``variable_params``.
"""
if self.sampling_transforms is None:
sampling_params = self.variable_params
else:
sampling_params =... | [
"def",
"sampling_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"sampling_transforms",
"is",
"None",
":",
"sampling_params",
"=",
"self",
".",
"variable_params",
"else",
":",
"sampling_params",
"=",
"self",
".",
"sampling_transforms",
".",
"sampling_params",
... | Returns the sampling parameters.
If ``sampling_transforms`` is None, this is the same as the
``variable_params``. | [
"Returns",
"the",
"sampling",
"parameters",
"."
] | python | train | 34.727273 |
djaodjin/djaodjin-deployutils | deployutils/apps/django/backends/jwt_session_store.py | https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/backends/jwt_session_store.py#L71-L102 | def load(self):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
"""
session_data = {}
try:
session_data = decode(self.session_key,
... | [
"def",
"load",
"(",
"self",
")",
":",
"session_data",
"=",
"{",
"}",
"try",
":",
"session_data",
"=",
"decode",
"(",
"self",
".",
"session_key",
",",
"settings",
".",
"DJAODJIN_SECRET_KEY",
")",
"self",
".",
"_session_key_data",
".",
"update",
"(",
"sessio... | We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails. | [
"We",
"load",
"the",
"data",
"from",
"the",
"key",
"itself",
"instead",
"of",
"fetching",
"from",
"some",
"external",
"data",
"store",
".",
"Opposite",
"of",
"_get_session_key",
"()",
"raises",
"BadSignature",
"if",
"signature",
"fails",
"."
] | python | train | 46.375 |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L1349-L1380 | def dispatch_to_index_op(op, left, right, index_class):
"""
Wrap Series left in the given index_class to delegate the operation op
to the index implementation. DatetimeIndex and TimedeltaIndex perform
type checking, timezone handling, overflow checks, etc.
Parameters
----------
op : binary... | [
"def",
"dispatch_to_index_op",
"(",
"op",
",",
"left",
",",
"right",
",",
"index_class",
")",
":",
"left_idx",
"=",
"index_class",
"(",
"left",
")",
"# avoid accidentally allowing integer add/sub. For datetime64[tz] dtypes,",
"# left_idx may inherit a freq from a cached Dateti... | Wrap Series left in the given index_class to delegate the operation op
to the index implementation. DatetimeIndex and TimedeltaIndex perform
type checking, timezone handling, overflow checks, etc.
Parameters
----------
op : binary operator (operator.add, operator.sub, ...)
left : Series
ri... | [
"Wrap",
"Series",
"left",
"in",
"the",
"given",
"index_class",
"to",
"delegate",
"the",
"operation",
"op",
"to",
"the",
"index",
"implementation",
".",
"DatetimeIndex",
"and",
"TimedeltaIndex",
"perform",
"type",
"checking",
"timezone",
"handling",
"overflow",
"ch... | python | train | 38.375 |
census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L473-L496 | def add_gauge(self, gauge):
"""Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
... | [
"def",
"add_gauge",
"(",
"self",
",",
"gauge",
")",
":",
"if",
"gauge",
"is",
"None",
":",
"raise",
"ValueError",
"name",
"=",
"gauge",
".",
"descriptor",
".",
"name",
"with",
"self",
".",
"_gauges_lock",
":",
"if",
"name",
"in",
"self",
".",
"gauges",... | Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
:class:`opencensus.metrics.export.cu... | [
"Add",
"gauge",
"to",
"the",
"registry",
"."
] | python | train | 42.166667 |
cloudtools/stacker | stacker/lookups/handlers/file.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/lookups/handlers/file.py#L119-L146 | def _parameterize_string(raw):
"""Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: ... | [
"def",
"_parameterize_string",
"(",
"raw",
")",
":",
"parts",
"=",
"[",
"]",
"s_index",
"=",
"0",
"for",
"match",
"in",
"_PARAMETER_PATTERN",
".",
"finditer",
"(",
"raw",
")",
":",
"parts",
".",
"append",
"(",
"raw",
"[",
"s_index",
":",
"match",
".",
... | Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: An expression with
placeho... | [
"Substitute",
"placeholders",
"in",
"a",
"string",
"using",
"CloudFormation",
"references"
] | python | train | 34.785714 |
IdentityPython/pysaml2 | src/saml2/client.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L485-L538 | def handle_logout_request(self, request, name_id, binding, sign=False,
sign_alg=None, relay_state=""):
"""
Deal with a LogoutRequest
:param request: The request as text string
:param name_id: The id of the current user
:param binding: Which binding ... | [
"def",
"handle_logout_request",
"(",
"self",
",",
"request",
",",
"name_id",
",",
"binding",
",",
"sign",
"=",
"False",
",",
"sign_alg",
"=",
"None",
",",
"relay_state",
"=",
"\"\"",
")",
":",
"logger",
".",
"info",
"(",
"\"logout request: %s\"",
",",
"req... | Deal with a LogoutRequest
:param request: The request as text string
:param name_id: The id of the current user
:param binding: Which binding the message came in over
:param sign: Whether the response will be signed or not
:return: Keyword arguments which can be used to send the... | [
"Deal",
"with",
"a",
"LogoutRequest"
] | python | train | 44.703704 |
saltstack/salt | salt/modules/zabbix.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zabbix.py#L108-L127 | def _frontend_url():
'''
Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0
'''
hostname = socket.gethostname()
frontend_url = 'http://' + hostname + '/zabbix/api_jsonrpc.php'
try:
try:
response = salt.utils.http.query(frontend_url)
error =... | [
"def",
"_frontend_url",
"(",
")",
":",
"hostname",
"=",
"socket",
".",
"gethostname",
"(",
")",
"frontend_url",
"=",
"'http://'",
"+",
"hostname",
"+",
"'/zabbix/api_jsonrpc.php'",
"try",
":",
"try",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
... | Tries to guess the url of zabbix frontend.
.. versionadded:: 2016.3.0 | [
"Tries",
"to",
"guess",
"the",
"url",
"of",
"zabbix",
"frontend",
"."
] | python | train | 28.85 |
dead-beef/markovchain | markovchain/cli/image.py | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/image.py#L286-L325 | def cmd_generate(args):
"""Generate images.
Parameters
----------
args : `argparse.Namespace`
Command arguments.
"""
check_output_format(args.output, args.count)
markov = load(MarkovImage, args.state, args)
if args.size is None:
if markov.scanner.resize is None:
... | [
"def",
"cmd_generate",
"(",
"args",
")",
":",
"check_output_format",
"(",
"args",
".",
"output",
",",
"args",
".",
"count",
")",
"markov",
"=",
"load",
"(",
"MarkovImage",
",",
"args",
".",
"state",
",",
"args",
")",
"if",
"args",
".",
"size",
"is",
... | Generate images.
Parameters
----------
args : `argparse.Namespace`
Command arguments. | [
"Generate",
"images",
"."
] | python | train | 25.525 |
saltstack/salt | salt/modules/pkg_resource.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L308-L335 | def format_pkg_list(packages, versions_as_list, attr):
'''
Formats packages according to parameters for list_pkgs.
'''
ret = copy.deepcopy(packages)
if attr:
requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'}
if attr != 'all':
... | [
"def",
"format_pkg_list",
"(",
"packages",
",",
"versions_as_list",
",",
"attr",
")",
":",
"ret",
"=",
"copy",
".",
"deepcopy",
"(",
"packages",
")",
"if",
"attr",
":",
"requested_attr",
"=",
"{",
"'epoch'",
",",
"'version'",
",",
"'release'",
",",
"'arch'... | Formats packages according to parameters for list_pkgs. | [
"Formats",
"packages",
"according",
"to",
"parameters",
"for",
"list_pkgs",
"."
] | python | train | 32.357143 |
sivy/pystatsd | pystatsd/statsd.py | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L89-L110 | def send(self, data, sample_rate=1):
"""
Squirt the metrics over UDP
"""
if self.prefix:
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.items())
if sample_rate < 1:
if random.random() > sample_rate:
return
... | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"sample_rate",
"=",
"1",
")",
":",
"if",
"self",
".",
"prefix",
":",
"data",
"=",
"dict",
"(",
"(",
"\".\"",
".",
"join",
"(",
"(",
"self",
".",
"prefix",
",",
"stat",
")",
")",
",",
"value",
")",
... | Squirt the metrics over UDP | [
"Squirt",
"the",
"metrics",
"over",
"UDP"
] | python | train | 34.5 |
googlefonts/ufo2ft | Lib/ufo2ft/featureCompiler.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureCompiler.py#L213-L231 | def setupFeatures(self):
"""
Make the features source.
**This should not be called externally.** Subclasses
may override this method to handle the file creation
in a different way if desired.
"""
if self.featureWriters:
featureFile = parseLayoutFeatur... | [
"def",
"setupFeatures",
"(",
"self",
")",
":",
"if",
"self",
".",
"featureWriters",
":",
"featureFile",
"=",
"parseLayoutFeatures",
"(",
"self",
".",
"ufo",
")",
"for",
"writer",
"in",
"self",
".",
"featureWriters",
":",
"writer",
".",
"write",
"(",
"self"... | Make the features source.
**This should not be called externally.** Subclasses
may override this method to handle the file creation
in a different way if desired. | [
"Make",
"the",
"features",
"source",
"."
] | python | train | 37.473684 |
pantsbuild/pants | src/python/pants/engine/goal.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/goal.py#L126-L151 | def line_oriented(cls, line_oriented_options, console):
"""Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively.
The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`.
"""
if type(line_oriented_options) != cls.Options:
... | [
"def",
"line_oriented",
"(",
"cls",
",",
"line_oriented_options",
",",
"console",
")",
":",
"if",
"type",
"(",
"line_oriented_options",
")",
"!=",
"cls",
".",
"Options",
":",
"raise",
"AssertionError",
"(",
"'Expected Options for `{}`, got: {}'",
".",
"format",
"(... | Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively.
The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`. | [
"Given",
"Goal",
".",
"Options",
"and",
"a",
"Console",
"yields",
"functions",
"for",
"writing",
"to",
"stdout",
"and",
"stderr",
"respectively",
"."
] | python | train | 36.692308 |
buguroo/pyknow | pyknow/matchers/rete/nodes.py | https://github.com/buguroo/pyknow/blob/48818336f2e9a126f1964f2d8dc22d37ff800fe8/pyknow/matchers/rete/nodes.py#L36-L41 | def add(self, fact):
"""Create a VALID token and send it to all children."""
token = Token.valid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | [
"def",
"add",
"(",
"self",
",",
"fact",
")",
":",
"token",
"=",
"Token",
".",
"valid",
"(",
"fact",
")",
"MATCHER",
".",
"debug",
"(",
"\"<BusNode> added %r\"",
",",
"token",
")",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"cal... | Create a VALID token and send it to all children. | [
"Create",
"a",
"VALID",
"token",
"and",
"send",
"it",
"to",
"all",
"children",
"."
] | python | train | 39 |
etcher-be/elib_config | elib_config/_utils.py | https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_utils.py#L28-L39 | def friendly_type_name(raw_type: typing.Type) -> str:
"""
Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string
"""
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error('unmanaged value type: %s', raw... | [
"def",
"friendly_type_name",
"(",
"raw_type",
":",
"typing",
".",
"Type",
")",
"->",
"str",
":",
"try",
":",
"return",
"_TRANSLATE_TYPE",
"[",
"raw_type",
"]",
"except",
"KeyError",
":",
"LOGGER",
".",
"error",
"(",
"'unmanaged value type: %s'",
",",
"raw_type... | Returns a user-friendly type name
:param raw_type: raw type (str, int, ...)
:return: user friendly type as string | [
"Returns",
"a",
"user",
"-",
"friendly",
"type",
"name"
] | python | train | 28.666667 |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/egstore.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/egstore.py#L85-L130 | def restore(self):
"""
Set the values of whatever attributes are recoverable
from the pickle file.
Populate the attributes (the __dict__) of the EgStore object
from the attributes (the __dict__) of the pickled object.
If the pickled object has attributes that have b... | [
"def",
"restore",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"filename",
")",
":",
"return",
"self",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"filename",
")",
":",
"return",
"se... | Set the values of whatever attributes are recoverable
from the pickle file.
Populate the attributes (the __dict__) of the EgStore object
from the attributes (the __dict__) of the pickled object.
If the pickled object has attributes that have been initialized
in the EgStore ... | [
"Set",
"the",
"values",
"of",
"whatever",
"attributes",
"are",
"recoverable",
"from",
"the",
"pickle",
"file",
"."
] | python | train | 35.130435 |
aumayr/beancount-pygments-lexer | beancount_pygments_lexer/util/version.py | https://github.com/aumayr/beancount-pygments-lexer/blob/49ab7754a41fe850ebe88cb879ec0a78e1e06ef0/beancount_pygments_lexer/util/version.py#L1-L13 | def get_version(version=None):
"""Returns a tuple of the django version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version[4] > 0: # 0.2.1-alpha.1
return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4])
elif v... | [
"def",
"get_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"[",
"4",
"]",
">",
"0",
":",
"# 0.2.1-alpha.1",
"return",
"\"%s.%s.%s-%s.%s\"",
"%",
"(",
"version",
"[",
"0",
"]",
",",
"version",
"[",
"1",
"]",
",",
"version",
"[",
"2"... | Returns a tuple of the django version. If version argument is non-empty,
then checks for correctness of the tuple provided. | [
"Returns",
"a",
"tuple",
"of",
"the",
"django",
"version",
".",
"If",
"version",
"argument",
"is",
"non",
"-",
"empty",
"then",
"checks",
"for",
"correctness",
"of",
"the",
"tuple",
"provided",
"."
] | python | train | 45 |
karan/TPB | tpb/tpb.py | https://github.com/karan/TPB/blob/f424a73a10d4bcf4e363d7e7e8cb915a3a057671/tpb/tpb.py#L141-L164 | def items(self):
"""
Request URL and parse response. Yield a ``Torrent`` for every torrent
on page. If in multipage mode, Torrents from next pages are
automatically chained.
"""
if self._multipage:
while True:
# Pool for more torrents
... | [
"def",
"items",
"(",
"self",
")",
":",
"if",
"self",
".",
"_multipage",
":",
"while",
"True",
":",
"# Pool for more torrents",
"items",
"=",
"super",
"(",
"Paginated",
",",
"self",
")",
".",
"items",
"(",
")",
"# Stop if no more torrents",
"first",
"=",
"n... | Request URL and parse response. Yield a ``Torrent`` for every torrent
on page. If in multipage mode, Torrents from next pages are
automatically chained. | [
"Request",
"URL",
"and",
"parse",
"response",
".",
"Yield",
"a",
"Torrent",
"for",
"every",
"torrent",
"on",
"page",
".",
"If",
"in",
"multipage",
"mode",
"Torrents",
"from",
"next",
"pages",
"are",
"automatically",
"chained",
"."
] | python | train | 34.583333 |
finklabs/banana | banana/template.py | https://github.com/finklabs/banana/blob/bc416b5a3971fba0b0a90644760ccaddb95b0149/banana/template.py#L34-L42 | def copy_wildcard(src_folder, dst_folder, glob):
"""copy
"""
create_dir(dst_folder)
for sname in iglob(os.path.join(src_folder, glob)):
rname = os.path.relpath(sname, src_folder)
dname = os.path.join(dst_folder, rname)
create_dir(dname)
shutil.copy(sname, dname) | [
"def",
"copy_wildcard",
"(",
"src_folder",
",",
"dst_folder",
",",
"glob",
")",
":",
"create_dir",
"(",
"dst_folder",
")",
"for",
"sname",
"in",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"src_folder",
",",
"glob",
")",
")",
":",
"rname",
"=",
... | copy | [
"copy"
] | python | train | 33.555556 |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L1245-L1265 | def get_server(self, datacenter_id, server_id, depth=1):
"""
Retrieves a server by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
... | [
"def",
"get_server",
"(",
"self",
",",
"datacenter_id",
",",
"server_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s/servers/%s?depth=%s'",
"%",
"(",
"datacenter_id",
",",
"server_id",
",",
"str",
... | Retrieves a server by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
:param depth: The depth of the response data.
:type ... | [
"Retrieves",
"a",
"server",
"by",
"its",
"ID",
"."
] | python | valid | 29.285714 |
lago-project/lago | lago/workdir.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L338-L404 | def resolve_workdir_path(cls, start_path=os.curdir):
"""
Look for an existing workdir in the given path, in a path/.lago dir,
or in a .lago dir under any of it's parent directories
Args:
start_path (str): path to start the search from, if None passed, it
will... | [
"def",
"resolve_workdir_path",
"(",
"cls",
",",
"start_path",
"=",
"os",
".",
"curdir",
")",
":",
"if",
"start_path",
"==",
"'auto'",
":",
"start_path",
"=",
"os",
".",
"curdir",
"cur_path",
"=",
"start_path",
"LOGGER",
".",
"debug",
"(",
"'Checking if %s is... | Look for an existing workdir in the given path, in a path/.lago dir,
or in a .lago dir under any of it's parent directories
Args:
start_path (str): path to start the search from, if None passed, it
will use the current dir
Returns:
str: path to the found... | [
"Look",
"for",
"an",
"existing",
"workdir",
"in",
"the",
"given",
"path",
"in",
"a",
"path",
"/",
".",
"lago",
"dir",
"or",
"in",
"a",
".",
"lago",
"dir",
"under",
"any",
"of",
"it",
"s",
"parent",
"directories"
] | python | train | 39.432836 |
lpantano/seqcluster | seqcluster/libs/read.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/read.py#L76-L80 | def precursor_sequence(loci, reference):
"""Get sequence from genome"""
region = "%s\t%s\t%s\t.\t.\t%s" % (loci[1], loci[2], loci[3], loci[4])
precursor = pybedtools.BedTool(str(region), from_string=True).sequence(fi=reference, s=True)
return open(precursor.seqfn).read().split("\n")[1] | [
"def",
"precursor_sequence",
"(",
"loci",
",",
"reference",
")",
":",
"region",
"=",
"\"%s\\t%s\\t%s\\t.\\t.\\t%s\"",
"%",
"(",
"loci",
"[",
"1",
"]",
",",
"loci",
"[",
"2",
"]",
",",
"loci",
"[",
"3",
"]",
",",
"loci",
"[",
"4",
"]",
")",
"precursor... | Get sequence from genome | [
"Get",
"sequence",
"from",
"genome"
] | python | train | 59.6 |
helixyte/everest | everest/utils.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/utils.py#L108-L123 | def id_generator(start=0):
"""
Generator for sequential numeric numbers.
"""
count = start
while True:
send_value = (yield count)
if not send_value is None:
if send_value < count:
raise ValueError('Values from ID generator must increase '
... | [
"def",
"id_generator",
"(",
"start",
"=",
"0",
")",
":",
"count",
"=",
"start",
"while",
"True",
":",
"send_value",
"=",
"(",
"yield",
"count",
")",
"if",
"not",
"send_value",
"is",
"None",
":",
"if",
"send_value",
"<",
"count",
":",
"raise",
"ValueErr... | Generator for sequential numeric numbers. | [
"Generator",
"for",
"sequential",
"numeric",
"numbers",
"."
] | python | train | 34.125 |
pantsbuild/pants | src/python/pants/reporting/reporting_server.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/reporting_server.py#L195-L216 | def _handle_poll(self, relpath, params):
"""Handle poll requests for raw file contents."""
request = json.loads(params.get('q')[0])
ret = {}
# request is a polling request for multiple files. For each file:
# - id is some identifier assigned by the client, used to differentiate the results.
# ... | [
"def",
"_handle_poll",
"(",
"self",
",",
"relpath",
",",
"params",
")",
":",
"request",
"=",
"json",
".",
"loads",
"(",
"params",
".",
"get",
"(",
"'q'",
")",
"[",
"0",
"]",
")",
"ret",
"=",
"{",
"}",
"# request is a polling request for multiple files. For... | Handle poll requests for raw file contents. | [
"Handle",
"poll",
"requests",
"for",
"raw",
"file",
"contents",
"."
] | python | train | 41.772727 |
bcbio/bcbio-nextgen | bcbio/rnaseq/dexseq.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/dexseq.py#L27-L65 | def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = ... | [
"def",
"run_count",
"(",
"bam_file",
",",
"dexseq_gff",
",",
"stranded",
",",
"out_file",
",",
"data",
")",
":",
"assert",
"file_exists",
"(",
"bam_file",
")",
",",
"\"%s does not exist.\"",
"%",
"bam_file",
"sort_order",
"=",
"bam",
".",
"_get_sort_order",
"(... | run dexseq_count on a BAM file | [
"run",
"dexseq_count",
"on",
"a",
"BAM",
"file"
] | python | train | 40.948718 |
jxtech/wechatpy | wechatpy/client/api/invoice.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/invoice.py#L151-L170 | def reject_insert(self, s_pappid, order_id, reason, redirect_url=None):
"""
拒绝用户的开发票请求
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2
:param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供
:param order_id: 订单id,在商户内单笔开票请求的唯一识别号
:param reason: 拒绝原因
:param red... | [
"def",
"reject_insert",
"(",
"self",
",",
"s_pappid",
",",
"order_id",
",",
"reason",
",",
"redirect_url",
"=",
"None",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'rejectinsert'",
",",
"data",
"=",
"{",
"'s_pappid'",
":",
"s_pappid",
",",
"'order_id'"... | 拒绝用户的开发票请求
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2
:param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供
:param order_id: 订单id,在商户内单笔开票请求的唯一识别号
:param reason: 拒绝原因
:param redirect_url: 跳转链接 | [
"拒绝用户的开发票请求",
"详情请参考",
"https",
":",
"//",
"mp",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki?id",
"=",
"mp1497082828_r1cI2"
] | python | train | 28.7 |
O365/python-o365 | O365/sharepoint.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/sharepoint.py#L429-L445 | def get_subsites(self):
""" Returns a list of subsites defined for this site
:rtype: list[Site]
"""
url = self.build_url(
self._endpoints.get('get_subsites').format(id=self.object_id))
response = self.con.get(url)
if not response:
return []
... | [
"def",
"get_subsites",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_subsites'",
")",
".",
"format",
"(",
"id",
"=",
"self",
".",
"object_id",
")",
")",
"response",
"=",
"self",
".... | Returns a list of subsites defined for this site
:rtype: list[Site] | [
"Returns",
"a",
"list",
"of",
"subsites",
"defined",
"for",
"this",
"site"
] | python | train | 31.647059 |
mediawiki-utilities/python-mwtypes | mwtypes/files/functions.py | https://github.com/mediawiki-utilities/python-mwtypes/blob/d996562e40437a7fff39a1c00fb5544b5708b5ed/mwtypes/files/functions.py#L32-L46 | def extract_extension(path):
"""
Reads a file path and returns the extension or None if the path
contains no extension.
:Parameters:
path : str
A filesystem path
"""
filename = os.path.basename(path)
parts = filename.split(".")
if len(parts) == 1:
return file... | [
"def",
"extract_extension",
"(",
"path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"parts",
"=",
"filename",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"filename",... | Reads a file path and returns the extension or None if the path
contains no extension.
:Parameters:
path : str
A filesystem path | [
"Reads",
"a",
"file",
"path",
"and",
"returns",
"the",
"extension",
"or",
"None",
"if",
"the",
"path",
"contains",
"no",
"extension",
"."
] | python | train | 24.866667 |
silver-castle/mach9 | mach9/timer.py | https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/timer.py#L8-L17 | def update_current_time(loop):
"""Cache the current time, since it is needed at the end of every
keep-alive request to update the request timeout time
:param loop:
:return:
"""
global current_time
current_time = time()
loop.call_later(1, partial(update_current_time, loop)) | [
"def",
"update_current_time",
"(",
"loop",
")",
":",
"global",
"current_time",
"current_time",
"=",
"time",
"(",
")",
"loop",
".",
"call_later",
"(",
"1",
",",
"partial",
"(",
"update_current_time",
",",
"loop",
")",
")"
] | Cache the current time, since it is needed at the end of every
keep-alive request to update the request timeout time
:param loop:
:return: | [
"Cache",
"the",
"current",
"time",
"since",
"it",
"is",
"needed",
"at",
"the",
"end",
"of",
"every",
"keep",
"-",
"alive",
"request",
"to",
"update",
"the",
"request",
"timeout",
"time"
] | python | train | 29.7 |
materialsproject/pymatgen | pymatgen/electronic_structure/boltztrap.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/boltztrap.py#L2013-L2076 | def from_files(path_dir, dos_spin=1):
"""
get a BoltztrapAnalyzer object from a set of files
Args:
path_dir: directory where the boltztrap files are
dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down
Returns:
a BoltztrapAnalyzer object
... | [
"def",
"from_files",
"(",
"path_dir",
",",
"dos_spin",
"=",
"1",
")",
":",
"run_type",
",",
"warning",
",",
"efermi",
",",
"gap",
",",
"doping_levels",
"=",
"BoltztrapAnalyzer",
".",
"parse_outputtrans",
"(",
"path_dir",
")",
"vol",
"=",
"BoltztrapAnalyzer",
... | get a BoltztrapAnalyzer object from a set of files
Args:
path_dir: directory where the boltztrap files are
dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down
Returns:
a BoltztrapAnalyzer object | [
"get",
"a",
"BoltztrapAnalyzer",
"object",
"from",
"a",
"set",
"of",
"files"
] | python | train | 40.453125 |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L584-L586 | def in_range(x: int, minimum: int, maximum: int) -> bool:
""" Return True if x is >= minimum and <= maximum. """
return (x >= minimum and x <= maximum) | [
"def",
"in_range",
"(",
"x",
":",
"int",
",",
"minimum",
":",
"int",
",",
"maximum",
":",
"int",
")",
"->",
"bool",
":",
"return",
"(",
"x",
">=",
"minimum",
"and",
"x",
"<=",
"maximum",
")"
] | Return True if x is >= minimum and <= maximum. | [
"Return",
"True",
"if",
"x",
"is",
">",
"=",
"minimum",
"and",
"<",
"=",
"maximum",
"."
] | python | train | 52.333333 |
waqasbhatti/astrobase | astrobase/lcfit/transits.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcfit/transits.py#L528-L568 | def _log_likelihood_transit(theta, params, model, t, flux, err_flux,
priorbounds):
'''
Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
Note: the priorbound... | [
"def",
"_log_likelihood_transit",
"(",
"theta",
",",
"params",
",",
"model",
",",
"t",
",",
"flux",
",",
"err_flux",
",",
"priorbounds",
")",
":",
"u",
"=",
"[",
"]",
"for",
"ix",
",",
"key",
"in",
"enumerate",
"(",
"sorted",
"(",
"priorbounds",
".",
... | Given a batman TransitModel and its proposed parameters (theta), update the
batman params object with the proposed parameters and evaluate the gaussian
likelihood.
Note: the priorbounds are only needed to parse theta. | [
"Given",
"a",
"batman",
"TransitModel",
"and",
"its",
"proposed",
"parameters",
"(",
"theta",
")",
"update",
"the",
"batman",
"params",
"object",
"with",
"the",
"proposed",
"parameters",
"and",
"evaluate",
"the",
"gaussian",
"likelihood",
"."
] | python | valid | 28.634146 |
frictionlessdata/datapackage-pipelines | datapackage_pipelines/utilities/dirtools.py | https://github.com/frictionlessdata/datapackage-pipelines/blob/3a34bbdf042d13c3bec5eef46ff360ee41403874/datapackage_pipelines/utilities/dirtools.py#L195-L210 | def itersubdirs(self, pattern=None, abspath=False):
""" Generator for all subdirs (except excluded).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
"""
if pattern is not None:
globster = Globster([pattern])
for root, dirs, f... | [
"def",
"itersubdirs",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"abspath",
"=",
"False",
")",
":",
"if",
"pattern",
"is",
"not",
"None",
":",
"globster",
"=",
"Globster",
"(",
"[",
"pattern",
"]",
")",
"for",
"root",
",",
"dirs",
",",
"files",
... | Generator for all subdirs (except excluded).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern | [
"Generator",
"for",
"all",
"subdirs",
"(",
"except",
"excluded",
")",
"."
] | python | train | 38.1875 |
openego/eDisGo | edisgo/grid/components.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/components.py#L923-L968 | def curtailment(self):
"""
Parameters
----------
curtailment_ts : :pandas:`pandas.Series<series>`
See class definition for details.
Returns
-------
:pandas:`pandas.Series<series>`
If self._curtailment is set it returns that. Otherwise, if
... | [
"def",
"curtailment",
"(",
"self",
")",
":",
"if",
"self",
".",
"_curtailment",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_curtailment",
"elif",
"isinstance",
"(",
"self",
".",
"grid",
".",
"network",
".",
"timeseries",
".",
"_curtailment",
",",
... | Parameters
----------
curtailment_ts : :pandas:`pandas.Series<series>`
See class definition for details.
Returns
-------
:pandas:`pandas.Series<series>`
If self._curtailment is set it returns that. Otherwise, if
curtailment in :class:`~.grid.n... | [
"Parameters",
"----------",
"curtailment_ts",
":",
":",
"pandas",
":",
"pandas",
".",
"Series<series",
">",
"See",
"class",
"definition",
"for",
"details",
"."
] | python | train | 42.23913 |
senaite/senaite.core | bika/lims/content/abstractanalysis.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/abstractanalysis.py#L204-L213 | def getVerificators(self):
"""Returns the user ids of the users that verified this analysis
"""
verifiers = list()
actions = ["verify", "multi_verify"]
for event in wf.getReviewHistory(self):
if event['action'] in actions:
verifiers.append(event['actor... | [
"def",
"getVerificators",
"(",
"self",
")",
":",
"verifiers",
"=",
"list",
"(",
")",
"actions",
"=",
"[",
"\"verify\"",
",",
"\"multi_verify\"",
"]",
"for",
"event",
"in",
"wf",
".",
"getReviewHistory",
"(",
"self",
")",
":",
"if",
"event",
"[",
"'action... | Returns the user ids of the users that verified this analysis | [
"Returns",
"the",
"user",
"ids",
"of",
"the",
"users",
"that",
"verified",
"this",
"analysis"
] | python | train | 37.9 |
gholt/swiftly | swiftly/cli/iomanager.py | https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L320-L350 | def with_debug(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a debug-output-suitable file-like
object based on the optional os_path and optionally skipping
any configured sub-command.
:param os_path: Opt... | [
"def",
"with_debug",
"(",
"self",
",",
"os_path",
"=",
"None",
",",
"skip_sub_command",
"=",
"False",
",",
"disk_closed_callback",
"=",
"None",
")",
":",
"sub_command",
"=",
"None",
"if",
"skip_sub_command",
"else",
"self",
".",
"debug_sub_command",
"out",
","... | A context manager yielding a debug-output-suitable file-like
object based on the optional os_path and optionally skipping
any configured sub-command.
:param os_path: Optional path to base the file-like object
on.
:param skip_sub_command: Set True to skip any configured
... | [
"A",
"context",
"manager",
"yielding",
"a",
"debug",
"-",
"output",
"-",
"suitable",
"file",
"-",
"like",
"object",
"based",
"on",
"the",
"optional",
"os_path",
"and",
"optionally",
"skipping",
"any",
"configured",
"sub",
"-",
"command",
"."
] | python | test | 40.322581 |
wandb/client | wandb/git_repo.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/git_repo.py#L105-L149 | def get_upstream_fork_point(self):
"""Get the most recent ancestor of HEAD that occurs on an upstream
branch.
First looks at the current branch's tracking branch, if applicable. If
that doesn't work, looks at every other branch to find the most recent
ancestor of HEAD that occur... | [
"def",
"get_upstream_fork_point",
"(",
"self",
")",
":",
"possible_relatives",
"=",
"[",
"]",
"try",
":",
"if",
"not",
"self",
".",
"repo",
":",
"return",
"None",
"try",
":",
"active_branch",
"=",
"self",
".",
"repo",
".",
"active_branch",
"except",
"(",
... | Get the most recent ancestor of HEAD that occurs on an upstream
branch.
First looks at the current branch's tracking branch, if applicable. If
that doesn't work, looks at every other branch to find the most recent
ancestor of HEAD that occurs on a tracking branch.
Returns:
... | [
"Get",
"the",
"most",
"recent",
"ancestor",
"of",
"HEAD",
"that",
"occurs",
"on",
"an",
"upstream",
"branch",
"."
] | python | train | 41.577778 |
opencobra/memote | memote/experimental/medium.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/experimental/medium.py#L48-L54 | def validate(self, model, checks=[]):
"""Use a defined schema to validate the medium table format."""
custom = [
check_partial(reaction_id_check,
frozenset(r.id for r in model.reactions))
]
super(Medium, self).validate(model=model, checks=checks + cu... | [
"def",
"validate",
"(",
"self",
",",
"model",
",",
"checks",
"=",
"[",
"]",
")",
":",
"custom",
"=",
"[",
"check_partial",
"(",
"reaction_id_check",
",",
"frozenset",
"(",
"r",
".",
"id",
"for",
"r",
"in",
"model",
".",
"reactions",
")",
")",
"]",
... | Use a defined schema to validate the medium table format. | [
"Use",
"a",
"defined",
"schema",
"to",
"validate",
"the",
"medium",
"table",
"format",
"."
] | python | train | 45.571429 |
WZBSocialScienceCenter/tmtoolkit | ClassifierBasedGermanTagger/ClassifierBasedGermanTagger.py | https://github.com/WZBSocialScienceCenter/tmtoolkit/blob/ca8b9d072e37ccc82b533f47d48bd9755722305b/ClassifierBasedGermanTagger/ClassifierBasedGermanTagger.py#L35-L92 | def feature_detector(self, tokens, index, history):
"""Implementing a slightly modified feature detector.
@param tokens: The tokens from the sentence to tag.
@param index: The current token index to tag.
@param history: The previous tagged tokens.
"""
word = tokens[index... | [
"def",
"feature_detector",
"(",
"self",
",",
"tokens",
",",
"index",
",",
"history",
")",
":",
"word",
"=",
"tokens",
"[",
"index",
"]",
"if",
"index",
"==",
"0",
":",
"# At the beginning of the sentence",
"prevword",
"=",
"prevprevword",
"=",
"None",
"prevt... | Implementing a slightly modified feature detector.
@param tokens: The tokens from the sentence to tag.
@param index: The current token index to tag.
@param history: The previous tagged tokens. | [
"Implementing",
"a",
"slightly",
"modified",
"feature",
"detector",
"."
] | python | train | 37.482759 |
SwissDataScienceCenter/renku-python | renku/cli/dataset.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/dataset.py#L296-L317 | def unlink(client, name, include, exclude, yes):
"""Remove matching files from a dataset."""
dataset = client.load_dataset(name=name)
records = _filter(
client, names=[dataset.name], include=include, exclude=exclude
)
if not yes and records:
prompt_text = (
'You are abou... | [
"def",
"unlink",
"(",
"client",
",",
"name",
",",
"include",
",",
"exclude",
",",
"yes",
")",
":",
"dataset",
"=",
"client",
".",
"load_dataset",
"(",
"name",
"=",
"name",
")",
"records",
"=",
"_filter",
"(",
"client",
",",
"names",
"=",
"[",
"datase... | Remove matching files from a dataset. | [
"Remove",
"matching",
"files",
"from",
"a",
"dataset",
"."
] | python | train | 32.954545 |
gwastro/pycbc | pycbc/tmpltbank/em_progenitors.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/em_progenitors.py#L705-L754 | def min_eta_for_em_bright(bh_spin_z, ns_g_mass, mNS_pts, sBH_pts, eta_mins):
"""
Function that uses the end product of generate_em_constraint_data
to swipe over a set of NS-BH binaries and determine the minimum
symmetric mass ratio required by each binary to yield a remnant
disk mass that exceeds a ... | [
"def",
"min_eta_for_em_bright",
"(",
"bh_spin_z",
",",
"ns_g_mass",
",",
"mNS_pts",
",",
"sBH_pts",
",",
"eta_mins",
")",
":",
"f",
"=",
"scipy",
".",
"interpolate",
".",
"RectBivariateSpline",
"(",
"mNS_pts",
",",
"sBH_pts",
",",
"eta_mins",
",",
"kx",
"=",... | Function that uses the end product of generate_em_constraint_data
to swipe over a set of NS-BH binaries and determine the minimum
symmetric mass ratio required by each binary to yield a remnant
disk mass that exceeds a certain threshold. Each binary passed
to this function consists of a NS mass and a B... | [
"Function",
"that",
"uses",
"the",
"end",
"product",
"of",
"generate_em_constraint_data",
"to",
"swipe",
"over",
"a",
"set",
"of",
"NS",
"-",
"BH",
"binaries",
"and",
"determine",
"the",
"minimum",
"symmetric",
"mass",
"ratio",
"required",
"by",
"each",
"binar... | python | train | 43.24 |
openid/python-openid | openid/consumer/consumer.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L989-L1035 | def _verifyDiscoverySingle(self, endpoint, to_match):
"""Verify that the given endpoint matches the information
extracted from the OpenID assertion, and raise an exception if
there is a mismatch.
@type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
@type to_match: open... | [
"def",
"_verifyDiscoverySingle",
"(",
"self",
",",
"endpoint",
",",
"to_match",
")",
":",
"# Every type URI that's in the to_match endpoint has to be",
"# present in the discovered endpoint.",
"for",
"type_uri",
"in",
"to_match",
".",
"type_uris",
":",
"if",
"not",
"endpoin... | Verify that the given endpoint matches the information
extracted from the OpenID assertion, and raise an exception if
there is a mismatch.
@type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@rtype: NoneT... | [
"Verify",
"that",
"the",
"given",
"endpoint",
"matches",
"the",
"information",
"extracted",
"from",
"the",
"OpenID",
"assertion",
"and",
"raise",
"an",
"exception",
"if",
"there",
"is",
"a",
"mismatch",
"."
] | python | train | 48.744681 |
espressif/esptool | esptool.py | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L644-L666 | def flash_defl_begin(self, size, compsize, offset):
""" Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_blocks = ... | [
"def",
"flash_defl_begin",
"(",
"self",
",",
"size",
",",
"compsize",
",",
"offset",
")",
":",
"num_blocks",
"=",
"(",
"compsize",
"+",
"self",
".",
"FLASH_WRITE_SIZE",
"-",
"1",
")",
"//",
"self",
".",
"FLASH_WRITE_SIZE",
"erase_blocks",
"=",
"(",
"size",... | Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write. | [
"Start",
"downloading",
"compressed",
"data",
"to",
"Flash",
"(",
"performs",
"an",
"erase",
")"
] | python | train | 56 |
qba73/circleclient | circleclient/circleclient.py | https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L97-L103 | def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | [
"def",
"list_projects",
"(",
"self",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"'/projects?circle-token={token}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"client",
".",
"api_token",
")",
"json_data",
"=",
"self",
".",
"client",
".",
"request",
... | Return a list of all followed projects. | [
"Return",
"a",
"list",
"of",
"all",
"followed",
"projects",
"."
] | python | train | 38.428571 |
balloob/pychromecast | pychromecast/config.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/config.py#L16-L29 | def get_possible_app_ids():
""" Returns all possible app ids. """
try:
req = requests.get(
"https://clients3.google.com/cast/chromecast/device/baseconfig")
data = json.loads(req.text[4:])
return [app['app_id'] for app in data['applications']] + \
data["enabled_a... | [
"def",
"get_possible_app_ids",
"(",
")",
":",
"try",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"\"https://clients3.google.com/cast/chromecast/device/baseconfig\"",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"req",
".",
"text",
"[",
"4",
":",
"]",
")",
... | Returns all possible app ids. | [
"Returns",
"all",
"possible",
"app",
"ids",
"."
] | python | train | 27.857143 |
the01/python-paps | paps/si/app/sensor.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L339-L372 | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
try:
self._... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"_init_listen_socket",
"(",
")",
"except",
":",
"self",
".",
"exception",
"(",
"u\"Failed to init listen socket ({}:{})\"",
".",
"format",
"(",
"self",
".",
"_list... | Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start | [
"Start",
"the",
"interface"
] | python | train | 32.882353 |
fermiPy/fermipy | fermipy/irfs.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L419-L448 | def interp_bin(self, egy_bins, dtheta, scale_fn=None):
"""Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``.
Parameters
----------
egy_bins : array_like
Energy bin edges in MeV.
dtheta : array_like
Array of angular separations in degr... | [
"def",
"interp_bin",
"(",
"self",
",",
"egy_bins",
",",
"dtheta",
",",
"scale_fn",
"=",
"None",
")",
":",
"npts",
"=",
"4",
"egy_bins",
"=",
"np",
".",
"exp",
"(",
"utils",
".",
"split_bin_edges",
"(",
"np",
".",
"log",
"(",
"egy_bins",
")",
",",
"... | Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``.
Parameters
----------
egy_bins : array_like
Energy bin edges in MeV.
dtheta : array_like
Array of angular separations in degrees.
scale_fn : callable
Function tha... | [
"Evaluate",
"the",
"bin",
"-",
"averaged",
"PSF",
"model",
"over",
"the",
"energy",
"bins",
"egy_bins",
"."
] | python | train | 36.5 |
PlaidWeb/Publ | publ/image/local.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L180-L193 | def _adjust_crop_box(box, crop):
""" Given a fit box and a crop box, adjust one to the other """
if crop and box:
# Both boxes are the same size; just line them up.
return (box[0] + crop[0], box[1] + crop[1],
box[2] + crop[0], box[3] + crop[1])
if cr... | [
"def",
"_adjust_crop_box",
"(",
"box",
",",
"crop",
")",
":",
"if",
"crop",
"and",
"box",
":",
"# Both boxes are the same size; just line them up.",
"return",
"(",
"box",
"[",
"0",
"]",
"+",
"crop",
"[",
"0",
"]",
",",
"box",
"[",
"1",
"]",
"+",
"crop",
... | Given a fit box and a crop box, adjust one to the other | [
"Given",
"a",
"fit",
"box",
"and",
"a",
"crop",
"box",
"adjust",
"one",
"to",
"the",
"other"
] | python | train | 39.428571 |
jason-weirather/py-seq-tools | seqtools/format/sam/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/__init__.py#L279-L290 | def target_range(self):
"""Get the range on the target strand
:return: target range
:rtype: GenomicRange
"""
if not self.is_aligned(): return None
if self._target_range: return self._target_range # check cache
global _sam_cigar_target_add
tlen = sum([x[0] for x in self.cigar_array if _s... | [
"def",
"target_range",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_aligned",
"(",
")",
":",
"return",
"None",
"if",
"self",
".",
"_target_range",
":",
"return",
"self",
".",
"_target_range",
"# check cache",
"global",
"_sam_cigar_target_add",
"tlen",
... | Get the range on the target strand
:return: target range
:rtype: GenomicRange | [
"Get",
"the",
"range",
"on",
"the",
"target",
"strand"
] | python | train | 39.25 |
aws/chalice | chalice/local.py | https://github.com/aws/chalice/blob/10d7fb52e68bd1c52aae251c97e3939fc0190412/chalice/local.py#L113-L147 | def match_route(self, url):
# type: (str) -> MatchResult
"""Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes can
use param substitution corresponding to API gateway patterns.
For exam... | [
"def",
"match_route",
"(",
"self",
",",
"url",
")",
":",
"# type: (str) -> MatchResult",
"# Otherwise we need to check for param substitution",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"parsed_qs",
"=",
"parse_qs",
"(",
"parsed_url",
".",
"query",
",",
"keep_bl... | Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes can
use param substitution corresponding to API gateway patterns.
For example::
match_route('/foo/bar') -> '/foo/{name}' | [
"Match",
"the",
"url",
"against",
"known",
"routes",
"."
] | python | train | 41.485714 |
Cornices/cornice.ext.swagger | cornice_swagger/views.py | https://github.com/Cornices/cornice.ext.swagger/blob/c31a5cc8d5dd112b11dc41ccb6d09b423b537abc/cornice_swagger/views.py#L47-L58 | def open_api_json_view(request):
"""
:param request:
:return:
Generates JSON representation of Swagger spec
"""
doc = cornice_swagger.CorniceSwagger(
cornice.service.get_services(), pyramid_registry=request.registry)
kwargs = request.registry.settings['cornice_swagger.spec_kwargs']
... | [
"def",
"open_api_json_view",
"(",
"request",
")",
":",
"doc",
"=",
"cornice_swagger",
".",
"CorniceSwagger",
"(",
"cornice",
".",
"service",
".",
"get_services",
"(",
")",
",",
"pyramid_registry",
"=",
"request",
".",
"registry",
")",
"kwargs",
"=",
"request",... | :param request:
:return:
Generates JSON representation of Swagger spec | [
":",
"param",
"request",
":",
":",
"return",
":"
] | python | valid | 30.333333 |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1505-L1515 | def mapCellsToPoints(self):
"""
Transform cell data (i.e., data specified per cell)
into point data (i.e., data specified at cell points).
The method of transformation is based on averaging the data values
of all cells using a particular point.
"""
c2p = vtk.vtkCe... | [
"def",
"mapCellsToPoints",
"(",
"self",
")",
":",
"c2p",
"=",
"vtk",
".",
"vtkCellDataToPointData",
"(",
")",
"c2p",
".",
"SetInputData",
"(",
"self",
".",
"polydata",
"(",
"False",
")",
")",
"c2p",
".",
"Update",
"(",
")",
"return",
"self",
".",
"upda... | Transform cell data (i.e., data specified per cell)
into point data (i.e., data specified at cell points).
The method of transformation is based on averaging the data values
of all cells using a particular point. | [
"Transform",
"cell",
"data",
"(",
"i",
".",
"e",
".",
"data",
"specified",
"per",
"cell",
")",
"into",
"point",
"data",
"(",
"i",
".",
"e",
".",
"data",
"specified",
"at",
"cell",
"points",
")",
".",
"The",
"method",
"of",
"transformation",
"is",
"ba... | python | train | 40.454545 |
wandb/client | wandb/fastai/__init__.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/fastai/__init__.py#L80-L91 | def on_train_begin(self, **kwargs):
"Call watch method to log model topology, gradients & weights"
# Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
super().on_train_begin()
# Ensure we don't call "watch" multiple times
if not WandbCallback.watch_c... | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set self.best, method inherited from \"TrackerCallback\" by \"SaveModelCallback\"",
"super",
"(",
")",
".",
"on_train_begin",
"(",
")",
"# Ensure we don't call \"watch\" multiple times",
"if",
"not",
... | Call watch method to log model topology, gradients & weights | [
"Call",
"watch",
"method",
"to",
"log",
"model",
"topology",
"gradients",
"&",
"weights"
] | python | train | 40.75 |
onicagroup/runway | runway/tfenv.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/tfenv.py#L98-L124 | def find_min_required(path):
"""Inspect terraform files and find minimum version."""
found_min_required = ''
for filename in glob.glob(os.path.join(path, '*.tf')):
with open(filename, 'r') as stream:
tf_config = hcl.load(stream)
if tf_config.get('terraform', {}).get('required... | [
"def",
"find_min_required",
"(",
"path",
")",
":",
"found_min_required",
"=",
"''",
"for",
"filename",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'*.tf'",
")",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'... | Inspect terraform files and find minimum version. | [
"Inspect",
"terraform",
"files",
"and",
"find",
"minimum",
"version",
"."
] | python | train | 47.222222 |
google/grr | grr/server/grr_response_server/databases/mysql_paths.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_paths.py#L202-L346 | def _MultiWritePathInfos(self, path_infos, connection=None):
"""Writes a collection of path info records for specified clients."""
query = ""
path_info_count = 0
path_info_values = []
parent_path_info_count = 0
parent_path_info_values = []
has_stat_entries = False
has_hash_entries = F... | [
"def",
"_MultiWritePathInfos",
"(",
"self",
",",
"path_infos",
",",
"connection",
"=",
"None",
")",
":",
"query",
"=",
"\"\"",
"path_info_count",
"=",
"0",
"path_info_values",
"=",
"[",
"]",
"parent_path_info_count",
"=",
"0",
"parent_path_info_values",
"=",
"["... | Writes a collection of path info records for specified clients. | [
"Writes",
"a",
"collection",
"of",
"path",
"info",
"records",
"for",
"specified",
"clients",
"."
] | python | train | 38.910345 |
boriel/zxbasic | arch/zx48k/backend/__init__.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L2210-L2232 | def emit_end(MEMORY=None):
""" This special ending autoinitializes required inits
(mainly alloc.asm) and changes the MEMORY initial address if it is
ORG XXXX to ORG XXXX + heap size
"""
output = []
output.extend(AT_END)
if REQUIRES.intersection(MEMINITS) or '__MEM_INIT' in INITS:
ou... | [
"def",
"emit_end",
"(",
"MEMORY",
"=",
"None",
")",
":",
"output",
"=",
"[",
"]",
"output",
".",
"extend",
"(",
"AT_END",
")",
"if",
"REQUIRES",
".",
"intersection",
"(",
"MEMINITS",
")",
"or",
"'__MEM_INIT'",
"in",
"INITS",
":",
"output",
".",
"append... | This special ending autoinitializes required inits
(mainly alloc.asm) and changes the MEMORY initial address if it is
ORG XXXX to ORG XXXX + heap size | [
"This",
"special",
"ending",
"autoinitializes",
"required",
"inits",
"(",
"mainly",
"alloc",
".",
"asm",
")",
"and",
"changes",
"the",
"MEMORY",
"initial",
"address",
"if",
"it",
"is",
"ORG",
"XXXX",
"to",
"ORG",
"XXXX",
"+",
"heap",
"size"
] | python | train | 37.695652 |
JelteF/PyLaTeX | pylatex/document.py | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L286-L306 | def _select_filepath(self, filepath):
"""Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath
... | [
"def",
"_select_filepath",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"filepath",
"is",
"None",
":",
"return",
"self",
".",
"default_filepath",
"else",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"==",
"''",
":",
"filepath",
... | Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath | [
"Make",
"a",
"choice",
"between",
"filepath",
"and",
"self",
".",
"default_filepath",
"."
] | python | train | 27.571429 |
openstack/monasca-common | monasca_common/kafka_lib/conn.py | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/kafka_lib/conn.py#L138-L157 | def send(self, request_id, payload):
"""
Send a request to Kafka
Arguments::
request_id (int): can be any int (used only for debug logging...)
payload: an encoded kafka packet (see KafkaProtocol)
"""
log.debug("About to send %d bytes to Kafka, request %d... | [
"def",
"send",
"(",
"self",
",",
"request_id",
",",
"payload",
")",
":",
"log",
".",
"debug",
"(",
"\"About to send %d bytes to Kafka, request %d\"",
"%",
"(",
"len",
"(",
"payload",
")",
",",
"request_id",
")",
")",
"# Make sure we have a connection",
"if",
"no... | Send a request to Kafka
Arguments::
request_id (int): can be any int (used only for debug logging...)
payload: an encoded kafka packet (see KafkaProtocol) | [
"Send",
"a",
"request",
"to",
"Kafka"
] | python | train | 30.7 |
harlowja/notifier | notifier/_notifier.py | https://github.com/harlowja/notifier/blob/35bf58e6350b1d3a3e8c4224e9d01178df70d753/notifier/_notifier.py#L113-L125 | def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
... | [
"def",
"dead",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_weak",
":",
"return",
"False",
"cb",
"=",
"self",
".",
"_callback",
"(",
")",
"if",
"cb",
"is",
"None",
":",
"return",
"True",
"return",
"False"
] | Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false. | [
"Whether",
"the",
"callback",
"no",
"longer",
"exists",
"."
] | python | train | 28.615385 |
psd-tools/psd-tools | src/psd_tools/api/layers.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/layers.py#L494-L517 | def descendants(self, include_clip=True):
"""
Return a generator to iterate over all descendant layers.
Example::
# Iterate over all layers
for layer in psd.descendants():
print(layer)
# Iterate over all layers in reverse order
f... | [
"def",
"descendants",
"(",
"self",
",",
"include_clip",
"=",
"True",
")",
":",
"for",
"layer",
"in",
"self",
":",
"yield",
"layer",
"if",
"layer",
".",
"is_group",
"(",
")",
":",
"for",
"child",
"in",
"layer",
".",
"descendants",
"(",
"include_clip",
"... | Return a generator to iterate over all descendant layers.
Example::
# Iterate over all layers
for layer in psd.descendants():
print(layer)
# Iterate over all layers in reverse order
for layer in reversed(list(psd.descendants())):
... | [
"Return",
"a",
"generator",
"to",
"iterate",
"over",
"all",
"descendant",
"layers",
"."
] | python | train | 32.083333 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L6083-L6093 | def getSkeletalBoneDataCompressed(self, action, eMotionRange, pvCompressedData, unCompressedSize):
"""
Reads the state of the skeletal bone data in a compressed form that is suitable for
sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount +... | [
"def",
"getSkeletalBoneDataCompressed",
"(",
"self",
",",
"action",
",",
"eMotionRange",
",",
"pvCompressedData",
",",
"unCompressedSize",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getSkeletalBoneDataCompressed",
"punRequiredCompressedSize",
"=",
"c_uint... | Reads the state of the skeletal bone data in a compressed form that is suitable for
sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount + 2).
Usually the size will be much smaller. | [
"Reads",
"the",
"state",
"of",
"the",
"skeletal",
"bone",
"data",
"in",
"a",
"compressed",
"form",
"that",
"is",
"suitable",
"for",
"sending",
"over",
"the",
"network",
".",
"The",
"required",
"buffer",
"size",
"will",
"never",
"exceed",
"(",
"sizeof",
"("... | python | train | 59.181818 |
wbond/oscrypto | oscrypto/_win/asymmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/asymmetric.py#L874-L971 | def generate_dh_parameters(bit_size):
"""
Generates DH parameters for use with Diffie-Hellman key exchange. Returns
a structure in the format of DHParameter defined in PKCS#3, which is also
used by the OpenSSL dhparam tool.
THIS CAN BE VERY TIME CONSUMING!
:param bit_size:
The integer ... | [
"def",
"generate_dh_parameters",
"(",
"bit_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"bit_size",
",",
"int_types",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n bit_size must be an integer, not %s\n '''",
",",
"type_name",... | Generates DH parameters for use with Diffie-Hellman key exchange. Returns
a structure in the format of DHParameter defined in PKCS#3, which is also
used by the OpenSSL dhparam tool.
THIS CAN BE VERY TIME CONSUMING!
:param bit_size:
The integer bit size of the parameters to generate. Must be be... | [
"Generates",
"DH",
"parameters",
"for",
"use",
"with",
"Diffie",
"-",
"Hellman",
"key",
"exchange",
".",
"Returns",
"a",
"structure",
"in",
"the",
"format",
"of",
"DHParameter",
"defined",
"in",
"PKCS#3",
"which",
"is",
"also",
"used",
"by",
"the",
"OpenSSL"... | python | valid | 33.530612 |
dshean/pygeotools | pygeotools/lib/geolib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/geolib.py#L1940-L1949 | def get_xy_1D(ds, stride=1, getval=False):
"""Return 1D arrays of x and y map coordinates for input GDAL Dataset
"""
gt = ds.GetGeoTransform()
#stride = stride_m/gt[1]
pX = np.arange(0, ds.RasterXSize, stride)
pY = np.arange(0, ds.RasterYSize, stride)
mX, dummy = pixelToMap(pX, pY[0], gt)
... | [
"def",
"get_xy_1D",
"(",
"ds",
",",
"stride",
"=",
"1",
",",
"getval",
"=",
"False",
")",
":",
"gt",
"=",
"ds",
".",
"GetGeoTransform",
"(",
")",
"#stride = stride_m/gt[1]",
"pX",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"ds",
".",
"RasterXSize",
","... | Return 1D arrays of x and y map coordinates for input GDAL Dataset | [
"Return",
"1D",
"arrays",
"of",
"x",
"and",
"y",
"map",
"coordinates",
"for",
"input",
"GDAL",
"Dataset"
] | python | train | 36.9 |
IDSIA/sacred | sacred/utils.py | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L469-L474 | def convert_to_nested_dict(dotted_dict):
"""Convert a dict with dotted path keys to corresponding nested dict."""
nested_dict = {}
for k, v in iterate_flattened(dotted_dict):
set_by_dotted_path(nested_dict, k, v)
return nested_dict | [
"def",
"convert_to_nested_dict",
"(",
"dotted_dict",
")",
":",
"nested_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iterate_flattened",
"(",
"dotted_dict",
")",
":",
"set_by_dotted_path",
"(",
"nested_dict",
",",
"k",
",",
"v",
")",
"return",
"nested_d... | Convert a dict with dotted path keys to corresponding nested dict. | [
"Convert",
"a",
"dict",
"with",
"dotted",
"path",
"keys",
"to",
"corresponding",
"nested",
"dict",
"."
] | python | train | 41.666667 |
istresearch/scrapy-cluster | rest/rest_service.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L236-L242 | def _spawn_kafka_connection_thread(self):
"""Spawns a kafka connection thread"""
self.logger.debug("Spawn kafka connection thread")
self.kafka_connected = False
self._kafka_thread = Thread(target=self._setup_kafka)
self._kafka_thread.setDaemon(True)
self._kafka_thread.sta... | [
"def",
"_spawn_kafka_connection_thread",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Spawn kafka connection thread\"",
")",
"self",
".",
"kafka_connected",
"=",
"False",
"self",
".",
"_kafka_thread",
"=",
"Thread",
"(",
"target",
"=",
"se... | Spawns a kafka connection thread | [
"Spawns",
"a",
"kafka",
"connection",
"thread"
] | python | train | 45.428571 |
jroyal/pyIDS | pyIDS/ids.py | https://github.com/jroyal/pyIDS/blob/3c2d3ff4bdc7bfe116dfd02152dadd26f92f74b5/pyIDS/ids.py#L82-L92 | def get_work_item_by_id(self, wi_id):
'''
Retrieves a single work item based off of the supplied ID
:param wi_id: The work item ID number
:return: Workitem or None
'''
work_items = self.get_work_items(id=wi_id)
if work_items is not None:
return work_i... | [
"def",
"get_work_item_by_id",
"(",
"self",
",",
"wi_id",
")",
":",
"work_items",
"=",
"self",
".",
"get_work_items",
"(",
"id",
"=",
"wi_id",
")",
"if",
"work_items",
"is",
"not",
"None",
":",
"return",
"work_items",
"[",
"0",
"]",
"return",
"None"
] | Retrieves a single work item based off of the supplied ID
:param wi_id: The work item ID number
:return: Workitem or None | [
"Retrieves",
"a",
"single",
"work",
"item",
"based",
"off",
"of",
"the",
"supplied",
"ID"
] | python | train | 30.636364 |
minio/minio-py | minio/helpers.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L61-L83 | def get_s3_region_from_endpoint(endpoint):
"""
Extracts and returns an AWS S3 region from an endpoint
of form `s3-ap-southeast-1.amazonaws.com`
:param endpoint: Endpoint region to be extracted.
"""
# Extract region by regex search.
m = _EXTRACT_REGION_REGEX.search(endpoint)
if m:
... | [
"def",
"get_s3_region_from_endpoint",
"(",
"endpoint",
")",
":",
"# Extract region by regex search.",
"m",
"=",
"_EXTRACT_REGION_REGEX",
".",
"search",
"(",
"endpoint",
")",
"if",
"m",
":",
"# Regex matches, we have found a region.",
"region",
"=",
"m",
".",
"group",
... | Extracts and returns an AWS S3 region from an endpoint
of form `s3-ap-southeast-1.amazonaws.com`
:param endpoint: Endpoint region to be extracted. | [
"Extracts",
"and",
"returns",
"an",
"AWS",
"S3",
"region",
"from",
"an",
"endpoint",
"of",
"form",
"s3",
"-",
"ap",
"-",
"southeast",
"-",
"1",
".",
"amazonaws",
".",
"com"
] | python | train | 30.73913 |
jaywink/federation | federation/protocols/diaspora/magic_envelope.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/magic_envelope.py#L142-L157 | def verify(self):
"""Verify Magic Envelope document against public key."""
if not self.public_key:
self.fetch_public_key()
data = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}data").text
sig = self.doc.find(".//{http://salmon-protocol.org/ns/magic-env}sig").text... | [
"def",
"verify",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"public_key",
":",
"self",
".",
"fetch_public_key",
"(",
")",
"data",
"=",
"self",
".",
"doc",
".",
"find",
"(",
"\".//{http://salmon-protocol.org/ns/magic-env}data\"",
")",
".",
"text",
"sig"... | Verify Magic Envelope document against public key. | [
"Verify",
"Magic",
"Envelope",
"document",
"against",
"public",
"key",
"."
] | python | train | 51.5625 |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/mds/apis/subscriptions_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/mds/apis/subscriptions_api.py#L410-L431 | def delete_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
"""Remove a subscription # noqa: E501
To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{r... | [
"def",
"delete_resource_subscription",
"(",
"self",
",",
"device_id",
",",
"_resource_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
... | Remove a subscription # noqa: E501
To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a ... | [
"Remove",
"a",
"subscription",
"#",
"noqa",
":",
"E501"
] | python | train | 64.681818 |
etingof/pysnmp | pysnmp/proto/rfc1902.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/proto/rfc1902.py#L93-L102 | def withValues(cls, *values):
"""Creates a subclass with discreet values constraint.
"""
class X(cls):
subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(
*values)
X.__name__ = cls.__name__
return X | [
"def",
"withValues",
"(",
"cls",
",",
"*",
"values",
")",
":",
"class",
"X",
"(",
"cls",
")",
":",
"subtypeSpec",
"=",
"cls",
".",
"subtypeSpec",
"+",
"constraint",
".",
"SingleValueConstraint",
"(",
"*",
"values",
")",
"X",
".",
"__name__",
"=",
"cls"... | Creates a subclass with discreet values constraint. | [
"Creates",
"a",
"subclass",
"with",
"discreet",
"values",
"constraint",
"."
] | python | train | 27.3 |
inasafe/inasafe | safe/definitions/hazard_exposure_specifications.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/definitions/hazard_exposure_specifications.py#L93-L108 | def specific_notes(hazard, exposure):
"""Return notes which are specific for a given hazard and exposure.
:param hazard: The hazard definition.
:type hazard: safe.definition.hazard
:param exposure: The exposure definition.
:type hazard: safe.definition.exposure
:return: List of notes specific... | [
"def",
"specific_notes",
"(",
"hazard",
",",
"exposure",
")",
":",
"for",
"item",
"in",
"ITEMS",
":",
"if",
"item",
"[",
"'hazard'",
"]",
"==",
"hazard",
"and",
"item",
"[",
"'exposure'",
"]",
"==",
"exposure",
":",
"return",
"item",
".",
"get",
"(",
... | Return notes which are specific for a given hazard and exposure.
:param hazard: The hazard definition.
:type hazard: safe.definition.hazard
:param exposure: The exposure definition.
:type hazard: safe.definition.exposure
:return: List of notes specific.
:rtype: list | [
"Return",
"notes",
"which",
"are",
"specific",
"for",
"a",
"given",
"hazard",
"and",
"exposure",
"."
] | python | train | 29.9375 |
ismms-himc/clustergrammer2 | clustergrammer2/clustergrammer_fun/normalize_fun.py | https://github.com/ismms-himc/clustergrammer2/blob/5acea9bff7eda546cf0647b9e3647f631eb6f5f5/clustergrammer2/clustergrammer_fun/normalize_fun.py#L5-L23 | def run_norm(net, df=None, norm_type='zscore', axis='row', keep_orig=False):
'''
A dataframe (more accurately a dictionary of dataframes, e.g. mat,
mat_up...) can be passed to run_norm and a normalization will be run (
e.g. zscore) on either the rows or columns
'''
# df here is actually a dictionary of sev... | [
"def",
"run_norm",
"(",
"net",
",",
"df",
"=",
"None",
",",
"norm_type",
"=",
"'zscore'",
",",
"axis",
"=",
"'row'",
",",
"keep_orig",
"=",
"False",
")",
":",
"# df here is actually a dictionary of several dataframes, 'mat', 'mat_orig',",
"# etc",
"if",
"df",
"is"... | A dataframe (more accurately a dictionary of dataframes, e.g. mat,
mat_up...) can be passed to run_norm and a normalization will be run (
e.g. zscore) on either the rows or columns | [
"A",
"dataframe",
"(",
"more",
"accurately",
"a",
"dictionary",
"of",
"dataframes",
"e",
".",
"g",
".",
"mat",
"mat_up",
"...",
")",
"can",
"be",
"passed",
"to",
"run_norm",
"and",
"a",
"normalization",
"will",
"be",
"run",
"(",
"e",
".",
"g",
".",
"... | python | train | 28.315789 |
Duke-GCB/DukeDSClient | ddsc/core/projectuploader.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/projectuploader.py#L321-L330 | def upload_folder_run(upload_context):
"""
Function run by CreateFolderCommand to create the folder.
Runs in a background process.
:param upload_context: UploadContext: contains data service setup and folder details.
"""
data_service = upload_context.make_data_service()
folder_name, parent_k... | [
"def",
"upload_folder_run",
"(",
"upload_context",
")",
":",
"data_service",
"=",
"upload_context",
".",
"make_data_service",
"(",
")",
"folder_name",
",",
"parent_kind",
",",
"parent_remote_id",
"=",
"upload_context",
".",
"params",
"result",
"=",
"data_service",
"... | Function run by CreateFolderCommand to create the folder.
Runs in a background process.
:param upload_context: UploadContext: contains data service setup and folder details. | [
"Function",
"run",
"by",
"CreateFolderCommand",
"to",
"create",
"the",
"folder",
".",
"Runs",
"in",
"a",
"background",
"process",
".",
":",
"param",
"upload_context",
":",
"UploadContext",
":",
"contains",
"data",
"service",
"setup",
"and",
"folder",
"details",
... | python | train | 47.1 |
Kortemme-Lab/pull_into_place | pull_into_place/pipeline.py | https://github.com/Kortemme-Lab/pull_into_place/blob/247f303100a612cc90cf31c86e4fe5052eb28c8d/pull_into_place/pipeline.py#L772-L809 | def workspace_from_dir(directory, recurse=True):
"""
Construct a workspace object from a directory name. If recurse=True, this
function will search down the directory tree and return the first workspace
it finds. If recurse=False, an exception will be raised if the given
directory is not a workspa... | [
"def",
"workspace_from_dir",
"(",
"directory",
",",
"recurse",
"=",
"True",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"pickle_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'workspace.pkl'",
... | Construct a workspace object from a directory name. If recurse=True, this
function will search down the directory tree and return the first workspace
it finds. If recurse=False, an exception will be raised if the given
directory is not a workspace. Workspace identification requires a file
called 'wor... | [
"Construct",
"a",
"workspace",
"object",
"from",
"a",
"directory",
"name",
".",
"If",
"recurse",
"=",
"True",
"this",
"function",
"will",
"search",
"down",
"the",
"directory",
"tree",
"and",
"return",
"the",
"first",
"workspace",
"it",
"finds",
".",
"If",
... | python | train | 41.552632 |
nutechsoftware/alarmdecoder | alarmdecoder/decoder.py | https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/decoder.py#L944-L951 | def _on_open(self, sender, *args, **kwargs):
"""
Internal handler for opening the device.
"""
self.get_config()
self.get_version()
self.on_open() | [
"def",
"_on_open",
"(",
"self",
",",
"sender",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"get_config",
"(",
")",
"self",
".",
"get_version",
"(",
")",
"self",
".",
"on_open",
"(",
")"
] | Internal handler for opening the device. | [
"Internal",
"handler",
"for",
"opening",
"the",
"device",
"."
] | python | train | 23.375 |
openstack/stacktach-winchester | winchester/db/interface.py | https://github.com/openstack/stacktach-winchester/blob/54f3ffc4a8fd84b6fb29ad9b65adb018e8927956/winchester/db/interface.py#L111-L129 | def in_session(self):
"""Provide a session scope around a series of operations."""
session = self.get_session()
try:
yield session
session.commit()
except IntegrityError:
session.rollback()
raise DuplicateError("Duplicate unique value detec... | [
"def",
"in_session",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"get_session",
"(",
")",
"try",
":",
"yield",
"session",
"session",
".",
"commit",
"(",
")",
"except",
"IntegrityError",
":",
"session",
".",
"rollback",
"(",
")",
"raise",
"Duplica... | Provide a session scope around a series of operations. | [
"Provide",
"a",
"session",
"scope",
"around",
"a",
"series",
"of",
"operations",
"."
] | python | train | 33.473684 |
StorjOld/pyp2p | pyp2p/nat_pmp.py | https://github.com/StorjOld/pyp2p/blob/7024208c3af20511496a652ff212f54c420e0464/pyp2p/nat_pmp.py#L384-L418 | def map_port(protocol, public_port, private_port, lifetime=3600,
gateway_ip=None, retry=9, use_exception=True):
"""A function to map public_port to private_port of protocol.
Returns the complete response on success.
protocol - NATPMP_PROTOCOL_UDP or NATPMP_PROTOCOL_TCP
... | [
"def",
"map_port",
"(",
"protocol",
",",
"public_port",
",",
"private_port",
",",
"lifetime",
"=",
"3600",
",",
"gateway_ip",
"=",
"None",
",",
"retry",
"=",
"9",
",",
"use_exception",
"=",
"True",
")",
":",
"if",
"protocol",
"not",
"in",
"[",
"NATPMP_PR... | A function to map public_port to private_port of protocol.
Returns the complete response on success.
protocol - NATPMP_PROTOCOL_UDP or NATPMP_PROTOCOL_TCP
public_port - the public port of the mapping requested
private_port - the private port of the mapping request... | [
"A",
"function",
"to",
"map",
"public_port",
"to",
"private_port",
"of",
"protocol",
".",
"Returns",
"the",
"complete",
"response",
"on",
"success",
".",
"protocol",
"-",
"NATPMP_PROTOCOL_UDP",
"or",
"NATPMP_PROTOCOL_TCP",
"public_port",
"-",
"the",
"public",
"por... | python | train | 55.057143 |
neovim/pynvim | pynvim/plugin/decorators.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L167-L175 | def encoding(encoding=True):
"""DEPRECATED: use pynvim.decode()."""
if isinstance(encoding, str):
encoding = True
def dec(f):
f._nvim_decode = encoding
return f
return dec | [
"def",
"encoding",
"(",
"encoding",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"encoding",
",",
"str",
")",
":",
"encoding",
"=",
"True",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_decode",
"=",
"encoding",
"return",
"f",
"return",
"dec"... | DEPRECATED: use pynvim.decode(). | [
"DEPRECATED",
":",
"use",
"pynvim",
".",
"decode",
"()",
"."
] | python | train | 22.666667 |
erigones/zabbix-api | zabbix_api.py | https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L268-L312 | def do_request(self, json_obj):
"""Perform one HTTP request to Zabbix API"""
self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers)
self.debug('Request: body=%s', json_obj)
self.r_query.append(json_obj)
request = urllib2.Request(url=self._api_url, data=jso... | [
"def",
"do_request",
"(",
"self",
",",
"json_obj",
")",
":",
"self",
".",
"debug",
"(",
"'Request: url=\"%s\" headers=%s'",
",",
"self",
".",
"_api_url",
",",
"self",
".",
"_http_headers",
")",
"self",
".",
"debug",
"(",
"'Request: body=%s'",
",",
"json_obj",
... | Perform one HTTP request to Zabbix API | [
"Perform",
"one",
"HTTP",
"request",
"to",
"Zabbix",
"API"
] | python | train | 36.6 |
aestrivex/bctpy | bct/algorithms/similarity.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/similarity.py#L103-L164 | def gtom(adj, nr_steps):
'''
The m-th step generalized topological overlap measure (GTOM) quantifies
the extent to which a pair of nodes have similar m-th step neighbors.
Mth-step neighbors are nodes that are reachable by a path of at most
length m.
This function computes the the M x M generali... | [
"def",
"gtom",
"(",
"adj",
",",
"nr_steps",
")",
":",
"bm",
"=",
"binarize",
"(",
"adj",
",",
"copy",
"=",
"True",
")",
"bm_aux",
"=",
"bm",
".",
"copy",
"(",
")",
"nr_nodes",
"=",
"len",
"(",
"adj",
")",
"if",
"nr_steps",
">",
"nr_nodes",
":",
... | The m-th step generalized topological overlap measure (GTOM) quantifies
the extent to which a pair of nodes have similar m-th step neighbors.
Mth-step neighbors are nodes that are reachable by a path of at most
length m.
This function computes the the M x M generalized topological overlap
measure (... | [
"The",
"m",
"-",
"th",
"step",
"generalized",
"topological",
"overlap",
"measure",
"(",
"GTOM",
")",
"quantifies",
"the",
"extent",
"to",
"which",
"a",
"pair",
"of",
"nodes",
"have",
"similar",
"m",
"-",
"th",
"step",
"neighbors",
".",
"Mth",
"-",
"step"... | python | train | 34.741935 |
briancappello/flask-unchained | flask_unchained/bundles/security/services/security_service.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L249-L263 | def confirm_user(self, user):
"""
Confirms the specified user. Returns False if the user has already been
confirmed, True otherwise.
:param user: The user to confirm.
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = self.security... | [
"def",
"confirm_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
".",
"confirmed_at",
"is",
"not",
"None",
":",
"return",
"False",
"user",
".",
"confirmed_at",
"=",
"self",
".",
"security",
".",
"datetime_factory",
"(",
")",
"user",
".",
"active"... | Confirms the specified user. Returns False if the user has already been
confirmed, True otherwise.
:param user: The user to confirm. | [
"Confirms",
"the",
"specified",
"user",
".",
"Returns",
"False",
"if",
"the",
"user",
"has",
"already",
"been",
"confirmed",
"True",
"otherwise",
"."
] | python | train | 31.733333 |
mjg59/python-broadlink | broadlink/__init__.py | https://github.com/mjg59/python-broadlink/blob/1d6d8d2aee6e221aa3383e4078b19b7b95397f43/broadlink/__init__.py#L300-L318 | def set_power_mask(self, sid_mask, state):
"""Sets the power state of the smart power strip."""
packet = bytearray(16)
packet[0x00] = 0x0d
packet[0x02] = 0xa5
packet[0x03] = 0xa5
packet[0x04] = 0x5a
packet[0x05] = 0x5a
packet[0x06] = 0xb2 + ((sid_mask<<1) if state else sid_mask)
pac... | [
"def",
"set_power_mask",
"(",
"self",
",",
"sid_mask",
",",
"state",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0x00",
"]",
"=",
"0x0d",
"packet",
"[",
"0x02",
"]",
"=",
"0xa5",
"packet",
"[",
"0x03",
"]",
"=",
"0xa5",
"p... | Sets the power state of the smart power strip. | [
"Sets",
"the",
"power",
"state",
"of",
"the",
"smart",
"power",
"strip",
"."
] | python | train | 28.157895 |
dougalsutherland/skl-groups | skl_groups/divergences/knn.py | https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L867-L883 | def quadratic(Ks, dim, rhos, required=None):
r'''
Estimates \int p^2 based on kNN distances.
In here because it's used in the l2 distance, above.
Returns array of shape (num_Ks,).
'''
# Estimated with alpha=1, beta=0:
# B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()
# and the ful... | [
"def",
"quadratic",
"(",
"Ks",
",",
"dim",
",",
"rhos",
",",
"required",
"=",
"None",
")",
":",
"# Estimated with alpha=1, beta=0:",
"# B_{k,d,1,0} is the same as B_{k,d,0,1} in linear()",
"# and the full estimator is",
"# B / (n - 1) * mean(rho ^ -dim)",
"N",
"=",
"rhos"... | r'''
Estimates \int p^2 based on kNN distances.
In here because it's used in the l2 distance, above.
Returns array of shape (num_Ks,). | [
"r",
"Estimates",
"\\",
"int",
"p^2",
"based",
"on",
"kNN",
"distances",
"."
] | python | valid | 32.588235 |
spyder-ide/spyder | spyder/widgets/comboboxes.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/comboboxes.py#L227-L238 | def focusOutEvent(self, event):
"""Handle focus out event restoring the last valid selected path."""
# Calling asynchronously the 'add_current_text' to avoid crash
# https://groups.google.com/group/spyderlib/browse_thread/thread/2257abf530e210bd
if not self.is_valid():
l... | [
"def",
"focusOutEvent",
"(",
"self",
",",
"event",
")",
":",
"# Calling asynchronously the 'add_current_text' to avoid crash\r",
"# https://groups.google.com/group/spyderlib/browse_thread/thread/2257abf530e210bd\r",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"lineedit",... | Handle focus out event restoring the last valid selected path. | [
"Handle",
"focus",
"out",
"event",
"restoring",
"the",
"last",
"valid",
"selected",
"path",
"."
] | python | train | 49.083333 |
Blueqat/Blueqat | blueqat/pauli.py | https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/pauli.py#L481-L513 | def get_time_evolution(self):
"""Get the function to append the time evolution of this term.
Returns:
function(circuit: Circuit, t: float):
Add gates for time evolution to `circuit` with time `t`
"""
term = self.simplify()
coeff = term.coeff
i... | [
"def",
"get_time_evolution",
"(",
"self",
")",
":",
"term",
"=",
"self",
".",
"simplify",
"(",
")",
"coeff",
"=",
"term",
".",
"coeff",
"if",
"coeff",
".",
"imag",
":",
"raise",
"ValueError",
"(",
"\"Not a real coefficient.\"",
")",
"ops",
"=",
"term",
"... | Get the function to append the time evolution of this term.
Returns:
function(circuit: Circuit, t: float):
Add gates for time evolution to `circuit` with time `t` | [
"Get",
"the",
"function",
"to",
"append",
"the",
"time",
"evolution",
"of",
"this",
"term",
"."
] | python | train | 34.30303 |
hydraplatform/hydra-base | hydra_base/lib/network.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/network.py#L771-L835 | def _get_all_resourcescenarios(network_id, user_id):
"""
Get all the resource scenarios in a network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
"""
rs_qry = db.DBSession.query(
Dataset.type,
Dataset.unit_id,
... | [
"def",
"_get_all_resourcescenarios",
"(",
"network_id",
",",
"user_id",
")",
":",
"rs_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dataset",
".",
"type",
",",
"Dataset",
".",
"unit_id",
",",
"Dataset",
".",
"name",
",",
"Dataset",
".",
"hash",
... | Get all the resource scenarios in a network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id | [
"Get",
"all",
"the",
"resource",
"scenarios",
"in",
"a",
"network",
"across",
"all",
"scenarios",
"returns",
"a",
"dictionary",
"of",
"dict",
"objects",
"keyed",
"on",
"scenario_id"
] | python | train | 34.892308 |
openstack/horizon | horizon/workflows/views.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L170-L219 | def post(self, request, *args, **kwargs):
"""Handler for HTTP POST requests."""
context = self.get_context_data(**kwargs)
workflow = context[self.context_object_name]
try:
# Check for the VALIDATE_STEP* headers, if they are present
# and valid integers, return val... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"workflow",
"=",
"context",
"[",
"self",
".",
"context_object_name",
"]",
... | Handler for HTTP POST requests. | [
"Handler",
"for",
"HTTP",
"POST",
"requests",
"."
] | python | train | 48.24 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/utils/tree_view_controller.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L203-L211 | def copy_action_callback(self, *event):
"""Callback method for copy action"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
sm_selection, sm_selected_model_list = self.get_state_machine_selection()
# only list specific elements are copi... | [
"def",
"copy_action_callback",
"(",
"self",
",",
"*",
"event",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"tree_view",
",",
"event",
")",
"and",
"self",
".",
"active_entry_widget",
"is",
"None",
":",
"sm_selection",
",",
... | Callback method for copy action | [
"Callback",
"method",
"for",
"copy",
"action"
] | python | train | 55.777778 |
avinassh/haxor | hackernews/__init__.py | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L204-L221 | def get_items_by_ids(self, item_ids, item_type=None):
"""Given a list of item ids, return all the Item objects
Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with
Returns:
List of `Item` objects for gi... | [
"def",
"get_items_by_ids",
"(",
"self",
",",
"item_ids",
",",
"item_type",
"=",
"None",
")",
":",
"urls",
"=",
"[",
"urljoin",
"(",
"self",
".",
"item_url",
",",
"F\"{i}.json\"",
")",
"for",
"i",
"in",
"item_ids",
"]",
"result",
"=",
"self",
".",
"_run... | Given a list of item ids, return all the Item objects
Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with
Returns:
List of `Item` objects for given item IDs and given item type | [
"Given",
"a",
"list",
"of",
"item",
"ids",
"return",
"all",
"the",
"Item",
"objects"
] | python | train | 35.888889 |
andrewramsay/sk8-drivers | pysk8/pysk8/core.py | https://github.com/andrewramsay/sk8-drivers/blob/67347a71762fb421f5ae65a595def5c7879e8b0c/pysk8/pysk8/core.py#L1176-L1206 | def begin_scan(self, callback=None, interval=DEF_SCAN_INTERVAL, window=DEF_SCAN_WINDOW):
"""Begins a BLE scan and returns immediately.
Using this method you can begin a BLE scan and leave the dongle in scanning
mode in the background. It will remain in scanning mode until you call the
:... | [
"def",
"begin_scan",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"interval",
"=",
"DEF_SCAN_INTERVAL",
",",
"window",
"=",
"DEF_SCAN_WINDOW",
")",
":",
"# TODO validate params and current state",
"logger",
".",
"debug",
"(",
"'configuring scan parameters'",
")",
... | Begins a BLE scan and returns immediately.
Using this method you can begin a BLE scan and leave the dongle in scanning
mode in the background. It will remain in scanning mode until you call the
:meth:`end_scan` method or the :meth:`reset` method.
Args:
callback (callbable)... | [
"Begins",
"a",
"BLE",
"scan",
"and",
"returns",
"immediately",
"."
] | python | train | 44.322581 |
jonfaustman/django-frontend | djfrontend/templatetags/djfrontend.py | https://github.com/jonfaustman/django-frontend/blob/897934d593fade0eb1998f8fadd18c91a89e5b9a/djfrontend/templatetags/djfrontend.py#L222-L236 | def djfrontend_jquery_smoothscroll(version=None):
"""
Returns the jQuery Smooth Scroll plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file.
"""
if version is None:
version = getattr(settings, 'DJFRONTEND_JQUERY_SMOOTHSCROLL', DJFRONTEND_... | [
"def",
"djfrontend_jquery_smoothscroll",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"getattr",
"(",
"settings",
",",
"'DJFRONTEND_JQUERY_SMOOTHSCROLL'",
",",
"DJFRONTEND_JQUERY_SMOOTHSCROLL_DEFAULT",
")",
"if",
"getattr"... | Returns the jQuery Smooth Scroll plugin file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file. | [
"Returns",
"the",
"jQuery",
"Smooth",
"Scroll",
"plugin",
"file",
"according",
"to",
"version",
"number",
".",
"TEMPLATE_DEBUG",
"returns",
"full",
"file",
"otherwise",
"returns",
"minified",
"file",
"."
] | python | test | 61.333333 |
google/grr | grr/core/grr_response_core/lib/rdfvalues/structs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L1049-L1052 | def ConvertToWireFormat(self, value):
"""Encode the nested protobuf into wire format."""
data = value.SerializeToString()
return (self.encoded_tag, VarintEncode(len(data)), data) | [
"def",
"ConvertToWireFormat",
"(",
"self",
",",
"value",
")",
":",
"data",
"=",
"value",
".",
"SerializeToString",
"(",
")",
"return",
"(",
"self",
".",
"encoded_tag",
",",
"VarintEncode",
"(",
"len",
"(",
"data",
")",
")",
",",
"data",
")"
] | Encode the nested protobuf into wire format. | [
"Encode",
"the",
"nested",
"protobuf",
"into",
"wire",
"format",
"."
] | python | train | 46.75 |
pypa/pipenv | pipenv/vendor/urllib3/util/request.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/request.py#L95-L118 | def rewind_body(body, body_pos):
"""
Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file.
"""
body_seek = getattr(body, 'seek', None)
... | [
"def",
"rewind_body",
"(",
"body",
",",
"body_pos",
")",
":",
"body_seek",
"=",
"getattr",
"(",
"body",
",",
"'seek'",
",",
"None",
")",
"if",
"body_seek",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"body_pos",
",",
"integer_types",
")",
":",
"try",
... | Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file. | [
"Attempt",
"to",
"rewind",
"body",
"to",
"a",
"certain",
"position",
".",
"Primarily",
"used",
"for",
"request",
"redirects",
"and",
"retries",
"."
] | python | train | 38.625 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1808-L1819 | def help_center_incremental_articles_list(self, start_time=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path = "/api/v2/help_center/incremental/articles.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update... | [
"def",
"help_center_incremental_articles_list",
"(",
"self",
",",
"start_time",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/incremental/articles.json\"",
"api_query",
"=",
"{",
"}",
"if",
"\"query\"",
"in",
"kwargs",
".",
... | https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"help_center",
"/",
"articles#list",
"-",
"articles"
] | python | train | 44.25 |
B2W-BIT/aiologger | aiologger/formatters/json.py | https://github.com/B2W-BIT/aiologger/blob/0b366597a8305d5577a267305e81d5e4784cd398/aiologger/formatters/json.py#L111-L130 | def format(self, record) -> str:
"""
:type record: aiologger.loggers.json.LogRecord
"""
msg = dict(self.formatter_fields_for_record(record))
if record.flatten and isinstance(record.msg, dict):
msg.update(record.msg)
else:
msg[MSG_FIELDNAME] = recor... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
"->",
"str",
":",
"msg",
"=",
"dict",
"(",
"self",
".",
"formatter_fields_for_record",
"(",
"record",
")",
")",
"if",
"record",
".",
"flatten",
"and",
"isinstance",
"(",
"record",
".",
"msg",
",",
"dict... | :type record: aiologger.loggers.json.LogRecord | [
":",
"type",
"record",
":",
"aiologger",
".",
"loggers",
".",
"json",
".",
"LogRecord"
] | python | train | 31.75 |
aaugustin/websockets | src/websockets/extensions/permessage_deflate.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/extensions/permessage_deflate.py#L313-L323 | def get_request_params(self) -> List[ExtensionParameter]:
"""
Build request parameters.
"""
return _build_parameters(
self.server_no_context_takeover,
self.client_no_context_takeover,
self.server_max_window_bits,
self.client_max_window_bit... | [
"def",
"get_request_params",
"(",
"self",
")",
"->",
"List",
"[",
"ExtensionParameter",
"]",
":",
"return",
"_build_parameters",
"(",
"self",
".",
"server_no_context_takeover",
",",
"self",
".",
"client_no_context_takeover",
",",
"self",
".",
"server_max_window_bits",... | Build request parameters. | [
"Build",
"request",
"parameters",
"."
] | python | train | 29.272727 |
gabstopper/smc-python | smc/elements/situations.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/situations.py#L205-L217 | def situation_parameters(self):
"""
Situation parameters defining detection logic for the context.
This will return a list of SituationParameter indicating how
the detection is made, i.e. regular expression, integer value,
etc.
:rtype: list(SituationParameter)
... | [
"def",
"situation_parameters",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"data",
".",
"get",
"(",
"'situation_parameters'",
",",
"[",
"]",
")",
":",
"cache",
"=",
"ElementCache",
"(",
"data",
"=",
"self",
".",
"make_request",
"(",
"href",... | Situation parameters defining detection logic for the context.
This will return a list of SituationParameter indicating how
the detection is made, i.e. regular expression, integer value,
etc.
:rtype: list(SituationParameter) | [
"Situation",
"parameters",
"defining",
"detection",
"logic",
"for",
"the",
"context",
".",
"This",
"will",
"return",
"a",
"list",
"of",
"SituationParameter",
"indicating",
"how",
"the",
"detection",
"is",
"made",
"i",
".",
"e",
".",
"regular",
"expression",
"i... | python | train | 46 |
spacetelescope/drizzlepac | drizzlepac/hlautils/astrometric_utils.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L891-L932 | def within_footprint(img, wcs, x, y):
"""Determine whether input x, y fall in the science area of the image.
Parameters
----------
img : ndarray
ndarray of image where non-science areas are marked with value of NaN.
wcs : `stwcs.wcsutil.HSTWCS`
HSTWCS or WCS object with naxis terms... | [
"def",
"within_footprint",
"(",
"img",
",",
"wcs",
",",
"x",
",",
"y",
")",
":",
"# start with limits of WCS shape",
"if",
"hasattr",
"(",
"wcs",
",",
"'naxis1'",
")",
":",
"naxis1",
"=",
"wcs",
".",
"naxis1",
"naxis2",
"=",
"wcs",
".",
"naxis2",
"elif",... | Determine whether input x, y fall in the science area of the image.
Parameters
----------
img : ndarray
ndarray of image where non-science areas are marked with value of NaN.
wcs : `stwcs.wcsutil.HSTWCS`
HSTWCS or WCS object with naxis terms defined.
x, y : ndarray
arrays ... | [
"Determine",
"whether",
"input",
"x",
"y",
"fall",
"in",
"the",
"science",
"area",
"of",
"the",
"image",
"."
] | python | train | 29.357143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.