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 |
|---|---|---|---|---|---|---|---|---|---|
skulumani/kinematics | kinematics/sphere.py | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L36-L64 | def tan_rand(q, seed=9):
"""Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere ... | [
"def",
"tan_rand",
"(",
"q",
",",
"seed",
"=",
"9",
")",
":",
"# probably need a check in case we get a parallel vector",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"... | Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere and also random | [
"Find",
"a",
"random",
"vector",
"in",
"the",
"tangent",
"space",
"of",
"the",
"n",
"sphere"
] | python | train | 22.655172 |
ArangoDB-Community/pyArango | pyArango/connection.py | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/connection.py#L129-L132 | def resetSession(self, username=None, password=None, verify=True) :
"""resets the session"""
self.disconnectSession()
self.session = AikidoSession(username, password, verify) | [
"def",
"resetSession",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"self",
".",
"disconnectSession",
"(",
")",
"self",
".",
"session",
"=",
"AikidoSession",
"(",
"username",
",",
"passwor... | resets the session | [
"resets",
"the",
"session"
] | python | train | 48.75 |
emory-libraries/eulfedora | eulfedora/api.py | https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/api.py#L745-L771 | def purgeRelationship(self, pid, subject, predicate, object, isLiteral=False,
datatype=None):
'''Remove a relationship from an object.
Wrapper function for
`Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>... | [
"def",
"purgeRelationship",
"(",
"self",
",",
"pid",
",",
"subject",
",",
"predicate",
",",
"object",
",",
"isLiteral",
"=",
"False",
",",
"datatype",
"=",
"None",
")",
":",
"http_args",
"=",
"{",
"'subject'",
":",
"subject",
",",
"'predicate'",
":",
"pr... | Remove a relationship from an object.
Wrapper function for
`Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>`_
:param pid: object pid
:param subject: relationship subject
:param predicate: relationship predicate
... | [
"Remove",
"a",
"relationship",
"from",
"an",
"object",
"."
] | python | train | 44.185185 |
pyQode/pyqode.core | pyqode/core/widgets/filesystem_treeview.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/filesystem_treeview.py#L279-L287 | def fileInfo(self, index):
"""
Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo
"""
return self._fs_model_source.fileInfo(
self._fs_model_proxy.mapToSource(index)) | [
"def",
"fileInfo",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"_fs_model_source",
".",
"fileInfo",
"(",
"self",
".",
"_fs_model_proxy",
".",
"mapToSource",
"(",
"index",
")",
")"
] | Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo | [
"Gets",
"the",
"file",
"info",
"of",
"the",
"item",
"at",
"the",
"specified",
"index",
"."
] | python | train | 31.555556 |
mongolab/dex | dex/dex.py | https://github.com/mongolab/dex/blob/f6dc27321028ef1ffdb3d4b1165fdcce7c8f20aa/dex/dex.py#L316-L326 | def _tail_file(self, file, interval):
"""Tails a file"""
file.seek(0,2)
while True:
where = file.tell()
line = file.readline()
if not line:
time.sleep(interval)
file.seek(where)
else:
yield line | [
"def",
"_tail_file",
"(",
"self",
",",
"file",
",",
"interval",
")",
":",
"file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"while",
"True",
":",
"where",
"=",
"file",
".",
"tell",
"(",
")",
"line",
"=",
"file",
".",
"readline",
"(",
")",
"if",
"no... | Tails a file | [
"Tails",
"a",
"file"
] | python | train | 27.636364 |
saltstack/salt | salt/modules/xfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xfs.py#L71-L90 | def _xfs_info_get_kv(serialized):
'''
Parse one line of the XFS info output.
'''
# No need to know sub-elements here
if serialized.startswith("="):
serialized = serialized[1:].strip()
serialized = serialized.replace(" = ", "=*** ").replace(" =", "=")
# Keywords has no spaces, value... | [
"def",
"_xfs_info_get_kv",
"(",
"serialized",
")",
":",
"# No need to know sub-elements here",
"if",
"serialized",
".",
"startswith",
"(",
"\"=\"",
")",
":",
"serialized",
"=",
"serialized",
"[",
"1",
":",
"]",
".",
"strip",
"(",
")",
"serialized",
"=",
"seria... | Parse one line of the XFS info output. | [
"Parse",
"one",
"line",
"of",
"the",
"XFS",
"info",
"output",
"."
] | python | train | 28.65 |
moluwole/Bast | bast/route.py | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/route.py#L27-L34 | def middleware(self, args):
"""
Appends a Middleware to the route which is to be executed before the route runs
"""
if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)):
self.url.pop()
... | [
"def",
"middleware",
"(",
"self",
",",
"args",
")",
":",
"if",
"self",
".",
"url",
"[",
"(",
"len",
"(",
"self",
".",
"url",
")",
"-",
"1",
")",
"]",
"==",
"(",
"self",
".",
"url_",
",",
"self",
".",
"controller",
",",
"dict",
"(",
"method",
... | Appends a Middleware to the route which is to be executed before the route runs | [
"Appends",
"a",
"Middleware",
"to",
"the",
"route",
"which",
"is",
"to",
"be",
"executed",
"before",
"the",
"route",
"runs"
] | python | train | 57.125 |
dingusdk/PythonIhcSdk | ihcsdk/ihcsslconnection.py | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcsslconnection.py#L47-L55 | def init_poolmanager(self, connections, maxsize,
block=requests.adapters.DEFAULT_POOLBLOCK,
**pool_kwargs):
"""Initialize poolmanager with cipher and Tlsv1"""
context = create_urllib3_context(ciphers=self.CIPHERS,
... | [
"def",
"init_poolmanager",
"(",
"self",
",",
"connections",
",",
"maxsize",
",",
"block",
"=",
"requests",
".",
"adapters",
".",
"DEFAULT_POOLBLOCK",
",",
"*",
"*",
"pool_kwargs",
")",
":",
"context",
"=",
"create_urllib3_context",
"(",
"ciphers",
"=",
"self",... | Initialize poolmanager with cipher and Tlsv1 | [
"Initialize",
"poolmanager",
"with",
"cipher",
"and",
"Tlsv1"
] | python | train | 61 |
gwastro/pycbc | pycbc/conversions.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L375-L379 | def mass1_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)
eta = eta_from_tau0_tau3(tau0, tau3, f_lower)
return mass1_from_mtotal_eta(mtotal, eta) | [
"def",
"mass1_from_tau0_tau3",
"(",
"tau0",
",",
"tau3",
",",
"f_lower",
")",
":",
"mtotal",
"=",
"mtotal_from_tau0_tau3",
"(",
"tau0",
",",
"tau3",
",",
"f_lower",
")",
"eta",
"=",
"eta_from_tau0_tau3",
"(",
"tau0",
",",
"tau3",
",",
"f_lower",
")",
"retu... | r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`. | [
"r",
"Returns",
"the",
"primary",
"mass",
"from",
"the",
"given",
":",
"math",
":",
"\\",
"tau_0",
"\\",
"tau_3",
"."
] | python | train | 53.8 |
edoburu/django-tag-parser | tag_parser/basetags.py | https://github.com/edoburu/django-tag-parser/blob/c24256cfdd0248434f2e3df3444ed9f945d4181f/tag_parser/basetags.py#L364-L373 | def parse(cls, parser, token):
"""
Parse the "as var" syntax.
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs)
# ... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"token",
")",
":",
"bits",
",",
"as_var",
"=",
"parse_as_var",
"(",
"parser",
",",
"token",
")",
"tag_name",
",",
"args",
",",
"kwargs",
"=",
"parse_token_kwargs",
"(",
"parser",
",",
"bits",
",",
"(",
... | Parse the "as var" syntax. | [
"Parse",
"the",
"as",
"var",
"syntax",
"."
] | python | test | 43.5 |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L732-L741 | def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() | [
"def",
"add_back_ref",
"(",
"self",
",",
"back_ref",
",",
"attr",
"=",
"None",
")",
":",
"back_ref",
".",
"add_ref",
"(",
"self",
",",
"attr",
")",
"return",
"self",
".",
"fetch",
"(",
")"
] | Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource | [
"Add",
"reference",
"from",
"back_ref",
"to",
"self"
] | python | train | 26 |
aboSamoor/polyglot | polyglot/tag/base.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/tag/base.py#L62-L80 | def annotate(self, sent):
"""Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words.
"""
preds = []
words = []
for word, fv in self.sent2examples(sent):
probs = self.predictor(fv)
tags = probs.argsort()
tag = self.ID_TAG[tags[-1]]
word... | [
"def",
"annotate",
"(",
"self",
",",
"sent",
")",
":",
"preds",
"=",
"[",
"]",
"words",
"=",
"[",
"]",
"for",
"word",
",",
"fv",
"in",
"self",
".",
"sent2examples",
"(",
"sent",
")",
":",
"probs",
"=",
"self",
".",
"predictor",
"(",
"fv",
")",
... | Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words. | [
"Annotate",
"a",
"squence",
"of",
"words",
"with",
"entity",
"tags",
"."
] | python | train | 22.315789 |
openid/python-openid | openid/extensions/draft/pape5.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L172-L184 | def fromOpenIDRequest(cls, request):
"""Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message
"""
self = cls()
args = request.message.getArgs(self.ns_uri)
is_openid1 = request.message.isOpenID1()
if args == {}:
return None
... | [
"def",
"fromOpenIDRequest",
"(",
"cls",
",",
"request",
")",
":",
"self",
"=",
"cls",
"(",
")",
"args",
"=",
"request",
".",
"message",
".",
"getArgs",
"(",
"self",
".",
"ns_uri",
")",
"is_openid1",
"=",
"request",
".",
"message",
".",
"isOpenID1",
"("... | Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message | [
"Instantiate",
"a",
"Request",
"object",
"from",
"the",
"arguments",
"in",
"a",
"C",
"{",
"checkid_",
"*",
"}",
"OpenID",
"message"
] | python | train | 29 |
PyCQA/astroid | astroid/brain/brain_gi.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_gi.py#L33-L128 | def _gi_build_stub(parent):
"""
Inspect the passed module recursively and build stubs for functions,
classes, etc.
"""
classes = {}
functions = {}
constants = {}
methods = {}
for name in dir(parent):
if name.startswith("__"):
continue
# Check if this is a... | [
"def",
"_gi_build_stub",
"(",
"parent",
")",
":",
"classes",
"=",
"{",
"}",
"functions",
"=",
"{",
"}",
"constants",
"=",
"{",
"}",
"methods",
"=",
"{",
"}",
"for",
"name",
"in",
"dir",
"(",
"parent",
")",
":",
"if",
"name",
".",
"startswith",
"(",... | Inspect the passed module recursively and build stubs for functions,
classes, etc. | [
"Inspect",
"the",
"passed",
"module",
"recursively",
"and",
"build",
"stubs",
"for",
"functions",
"classes",
"etc",
"."
] | python | train | 27.40625 |
archman/beamline | beamline/mathutils.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/mathutils.py#L237-L261 | def transRbend(theta=None, rho=None, gamma=None, incsym=-1):
""" Transport matrix of rectangle dipole
:param theta: bending angle in [RAD]
:param incsym: incident symmetry, -1 by default,
available options:
* -1: left half symmetry,
* 0: full symmetry,
* 1: right... | [
"def",
"transRbend",
"(",
"theta",
"=",
"None",
",",
"rho",
"=",
"None",
",",
"gamma",
"=",
"None",
",",
"incsym",
"=",
"-",
"1",
")",
":",
"if",
"None",
"in",
"(",
"theta",
",",
"rho",
",",
"gamma",
")",
":",
"print",
"(",
"\"warning: 'theta', 'rh... | Transport matrix of rectangle dipole
:param theta: bending angle in [RAD]
:param incsym: incident symmetry, -1 by default,
available options:
* -1: left half symmetry,
* 0: full symmetry,
* 1: right half symmetry
:param rho: bending radius in [m]
:param gamma... | [
"Transport",
"matrix",
"of",
"rectangle",
"dipole"
] | python | train | 38.68 |
saltstack/salt | salt/modules/nxos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos.py#L195-L228 | def cmd(command, *args, **kwargs):
'''
NOTE: This function is preserved for backwards compatibilty. This allows
commands to be executed using either of the following syntactic forms.
salt '*' nxos.cmd <function>
or
salt '*' nxos.<function>
command
function from `salt.modules.nxo... | [
"def",
"cmd",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
"in",
"list",
"(",
"kwargs",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'__pub_'",
")",
":",
"kwargs",
".",
"pop",
"(",
"k",
")",
"local_command",
... | NOTE: This function is preserved for backwards compatibilty. This allows
commands to be executed using either of the following syntactic forms.
salt '*' nxos.cmd <function>
or
salt '*' nxos.<function>
command
function from `salt.modules.nxos` to run
args
positional args to ... | [
"NOTE",
":",
"This",
"function",
"is",
"preserved",
"for",
"backwards",
"compatibilty",
".",
"This",
"allows",
"commands",
"to",
"be",
"executed",
"using",
"either",
"of",
"the",
"following",
"syntactic",
"forms",
"."
] | python | train | 27.882353 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/task_agent/task_agent_client.py#L28-L39 | def add_agent_cloud(self, agent_cloud):
"""AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>`
"""
content = ... | [
"def",
"add_agent_cloud",
"(",
"self",
",",
"agent_cloud",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"agent_cloud",
",",
"'TaskAgentCloud'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'POST'",
",",
"l... | AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` | [
"AddAgentCloud",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
":",
"class",
":",
"<TaskAgentCloud",
">",
"<azure",
".",
"devops",
".",
"v5_0",
".",
"task_agent",
".",
"models",
".",
"TaskAgentCloud",
">",
"agent_cloud",
":",
":",
"rtype",
":",
":",
"cl... | python | train | 54.583333 |
Opentrons/opentrons | api/src/opentrons/main.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/main.py#L201-L219 | def main():
""" The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server.http`
- initializes the hardware interaction... | [
"def",
"main",
"(",
")",
":",
"arg_parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Opentrons robot software\"",
",",
"parents",
"=",
"[",
"build_arg_parser",
"(",
")",
"]",
")",
"args",
"=",
"arg_parser",
".",
"parse_args",
"(",
")",
"run",
"(",
... | The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server.http`
- initializes the hardware interaction handled by either
... | [
"The",
"main",
"entrypoint",
"for",
"the",
"Opentrons",
"robot",
"API",
"server",
"stack",
"."
] | python | train | 36.421053 |
networks-lab/metaknowledge | metaknowledge/medline/recordMedline.py | https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/medline/recordMedline.py#L90-L127 | def medlineRecordParser(record):
"""The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRecord`.
# Parameters
... | [
"def",
"medlineRecordParser",
"(",
"record",
")",
":",
"tagDict",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"tag",
"=",
"'PMID'",
"mostRecentAuthor",
"=",
"None",
"for",
"lineNum",
",",
"line",
"in",
"record",
":",
"tmptag",
"=",
"line",
"[",
":",
... | The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRecord`.
# Parameters
_record_ : `enumerate object`
> a f... | [
"The",
"parser",
"[",
"MedlineRecord",
"]",
"(",
"..",
"/",
"classes",
"/",
"MedlineRecord",
".",
"html#metaknowledge",
".",
"medline",
".",
"MedlineRecord",
")",
"use",
".",
"This",
"takes",
"an",
"entry",
"from",
"[",
"medlineParser",
"()",
"]",
"(",
"#m... | python | train | 34.368421 |
facelessuser/pyspelling | pyspelling/__init__.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/__init__.py#L327-L370 | def compile_dictionary(self, lang, wordlists, encoding, output):
"""Compile user dictionary."""
cmd = [
self.binary,
'--lang', lang,
'--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name,
'create',
'ma... | [
"def",
"compile_dictionary",
"(",
"self",
",",
"lang",
",",
"wordlists",
",",
"encoding",
",",
"output",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"binary",
",",
"'--lang'",
",",
"lang",
",",
"'--encoding'",
",",
"codecs",
".",
"lookup",
"(",
"filters",
... | Compile user dictionary. | [
"Compile",
"user",
"dictionary",
"."
] | python | train | 33.954545 |
merll/docker-fabric | dockerfabric/apiclient.py | https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/apiclient.py#L173-L180 | def cleanup_containers(self, include_initial=False, exclude=None, **kwargs):
"""
Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.cleanup_containers` with additional logging.
"""
self.push_log("Generating list of stopped containers.")
set_raise_on_error(kwargs,... | [
"def",
"cleanup_containers",
"(",
"self",
",",
"include_initial",
"=",
"False",
",",
"exclude",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"push_log",
"(",
"\"Generating list of stopped containers.\"",
")",
"set_raise_on_error",
"(",
"kwargs",
... | Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.cleanup_containers` with additional logging. | [
"Identical",
"to",
":",
"meth",
":",
"dockermap",
".",
"client",
".",
"docker_util",
".",
"DockerUtilityMixin",
".",
"cleanup_containers",
"with",
"additional",
"logging",
"."
] | python | train | 64 |
GemHQ/round-py | round/wallets.py | https://github.com/GemHQ/round-py/blob/d0838f849cd260b1eb5df67ed3c6f2fe56c91c21/round/wallets.py#L242-L254 | def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
... | [
"def",
"account",
"(",
"self",
",",
"key",
"=",
"None",
",",
"address",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"key",
":",
"return",
"self",
".",
"client",
".",
"account",
"(",
"key",
",",
"wallet",
"=",
"self",
")",
"if",
"addres... | Query for an account by key, address, or name. | [
"Query",
"for",
"an",
"account",
"by",
"key",
"address",
"or",
"name",
"."
] | python | train | 36.923077 |
materialsproject/pymatgen | pymatgen/electronic_structure/boltztrap2.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/boltztrap2.py#L575-L706 | def plot_props(self, prop_y, prop_x, prop_z='temp',
output='avg_eigs', dop_type='n', doping=None,
temps=None, xlim=(-2, 2), ax=None):
"""
Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity... | [
"def",
"plot_props",
"(",
"self",
",",
"prop_y",
",",
"prop_x",
",",
"prop_z",
"=",
"'temp'",
",",
"output",
"=",
"'avg_eigs'",
",",
"dop_type",
"=",
"'n'",
",",
"doping",
"=",
"None",
",",
"temps",
"=",
"None",
",",
"xlim",
"=",
"(",
"-",
"2",
","... | Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity","Seebeck","Kappa","Carrier_conc","Hall_carrier_conc_trace"). Abbreviations are possible, like "S" for "Seebeck"
prop_x: independent variable in the x-axis among ('mu','doping','te... | [
"Function",
"to",
"plot",
"the",
"transport",
"properties",
"."
] | python | train | 44.469697 |
opendatateam/udata | udata/commands/fixtures.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/fixtures.py#L24-L38 | def generate_fixtures(datasets, reuses):
'''Build sample fixture data (users, datasets and reuses).'''
user = UserFactory()
log.info('Generated user "{user.email}".'.format(user=user))
organization = OrganizationFactory(members=[Member(user=user)])
log.info('Generated organization "{org.name}".'.fo... | [
"def",
"generate_fixtures",
"(",
"datasets",
",",
"reuses",
")",
":",
"user",
"=",
"UserFactory",
"(",
")",
"log",
".",
"info",
"(",
"'Generated user \"{user.email}\".'",
".",
"format",
"(",
"user",
"=",
"user",
")",
")",
"organization",
"=",
"OrganizationFact... | Build sample fixture data (users, datasets and reuses). | [
"Build",
"sample",
"fixture",
"data",
"(",
"users",
"datasets",
"and",
"reuses",
")",
"."
] | python | train | 44.4 |
desbma/sacad | sacad/cover.py | https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L114-L157 | async def get(self, target_format, target_size, size_tolerance_prct, out_filepath):
""" Download cover and process it. """
if self.source_quality.value <= CoverSourceQuality.LOW.value:
logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search")
... | [
"async",
"def",
"get",
"(",
"self",
",",
"target_format",
",",
"target_size",
",",
"size_tolerance_prct",
",",
"out_filepath",
")",
":",
"if",
"self",
".",
"source_quality",
".",
"value",
"<=",
"CoverSourceQuality",
".",
"LOW",
".",
"value",
":",
"logging",
... | Download cover and process it. | [
"Download",
"cover",
"and",
"process",
"it",
"."
] | python | train | 45.636364 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/debug.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/debug.py#L211-L264 | def attach(self, dwProcessId):
"""
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally yo... | [
"def",
"attach",
"(",
"self",
",",
"dwProcessId",
")",
":",
"# Get the Process object from the snapshot,",
"# if missing create a new one.",
"try",
":",
"aProcess",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"except",
"KeyError",
":",
"... | Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best t... | [
"Attaches",
"to",
"an",
"existing",
"process",
"for",
"debugging",
"."
] | python | train | 36.944444 |
Azure/azure-sdk-for-python | azure-keyvault/azure/keyvault/v2016_10_01/key_vault_client.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-keyvault/azure/keyvault/v2016_10_01/key_vault_client.py#L311-L393 | def update_key(
self, vault_base_url, key_name, key_version, key_ops=None, key_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config):
"""The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored i... | [
"def",
"update_key",
"(",
"self",
",",
"vault_base_url",
",",
"key_name",
",",
"key_version",
",",
"key_ops",
"=",
"None",
",",
"key_attributes",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*... | The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored in Azure Key
Vault.
In order to perform this operation, the key must already exist in the
Key Vault. Note: The cryptographic material of a key itself cannot be... | [
"The",
"update",
"key",
"operation",
"changes",
"specified",
"attributes",
"of",
"a",
"stored",
"key",
"and",
"can",
"be",
"applied",
"to",
"any",
"key",
"type",
"and",
"key",
"version",
"stored",
"in",
"Azure",
"Key",
"Vault",
"."
] | python | test | 46.590361 |
neelkamath/hclib | hclib.py | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L147-L198 | def _on_message(self, _, msg):
"""Sends and receives data to the callback function."""
result = json.loads(msg)
if result["cmd"] == "chat":
data = {"type": "message", "nick": result["nick"],
"text": result["text"]}
if "trip" in result:
... | [
"def",
"_on_message",
"(",
"self",
",",
"_",
",",
"msg",
")",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"msg",
")",
"if",
"result",
"[",
"\"cmd\"",
"]",
"==",
"\"chat\"",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"message\"",
",",
"\"nick\"",
... | Sends and receives data to the callback function. | [
"Sends",
"and",
"receives",
"data",
"to",
"the",
"callback",
"function",
"."
] | python | train | 51.326923 |
bmcfee/pumpp | pumpp/task/base.py | https://github.com/bmcfee/pumpp/blob/06a17b888271dd1f6cd41bddb22b0eb04d494056/pumpp/task/base.py#L131-L170 | def encode_events(self, duration, events, values, dtype=np.bool):
'''Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ... | [
"def",
"encode_events",
"(",
"self",
",",
"duration",
",",
"events",
",",
"values",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
":",
"frames",
"=",
"time_to_frames",
"(",
"events",
",",
"sr",
"=",
"self",
".",
"sr",
",",
"hop_length",
"=",
"self",
"."... | Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ndarray, shape=(n, m)
Values array. Must have the same first ind... | [
"Encode",
"labeled",
"events",
"as",
"a",
"time",
"-",
"series",
"matrix",
"."
] | python | train | 28.65 |
crunchyroll/ef-open | efopen/ef_aws_resolver.py | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_aws_resolver.py#L358-L371 | def elbv2_load_balancer_arn_suffix(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*`
"""
try:
elb = self._elbv2_load_ba... | [
"def",
"elbv2_load_balancer_arn_suffix",
"(",
"self",
",",
"lookup",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"elb",
"=",
"self",
".",
"_elbv2_load_balancer",
"(",
"lookup",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r'.+?(app\\/[^\\/]+\\/[^\\/]+)$'",... | Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*` | [
"Args",
":",
"lookup",
":",
"the",
"friendly",
"name",
"of",
"the",
"v2",
"elb",
"to",
"look",
"up",
"default",
":",
"value",
"to",
"return",
"in",
"case",
"of",
"no",
"match",
"Returns",
":",
"The",
"shorthand",
"fragment",
"of",
"the",
"ALB",
"s",
... | python | train | 33.142857 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_func.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_func.py#L149-L208 | def upgrade_database(
alembic_config_filename: str,
alembic_base_dir: str = None,
starting_revision: str = None,
destination_revision: str = "head",
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,
as_sql: bool = False) -> None:
"""
Use Alembic to upgrade our d... | [
"def",
"upgrade_database",
"(",
"alembic_config_filename",
":",
"str",
",",
"alembic_base_dir",
":",
"str",
"=",
"None",
",",
"starting_revision",
":",
"str",
"=",
"None",
",",
"destination_revision",
":",
"str",
"=",
"\"head\"",
",",
"version_table",
":",
"str"... | Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
alembic_base_dir:
directory to start in, so relative... | [
"Use",
"Alembic",
"to",
"upgrade",
"our",
"database",
"."
] | python | train | 34.1 |
contentful/contentful-management.py | contentful_management/content_type_field.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type_field.py#L38-L60 | def to_json(self):
"""
Returns the JSON Representation of the content type field.
"""
result = {
'name': self.name,
'id': self._real_id(),
'type': self.type,
'localized': self.localized,
'omitted': self.omitted,
're... | [
"def",
"to_json",
"(",
"self",
")",
":",
"result",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'id'",
":",
"self",
".",
"_real_id",
"(",
")",
",",
"'type'",
":",
"self",
".",
"type",
",",
"'localized'",
":",
"self",
".",
"localized",
",",
... | Returns the JSON Representation of the content type field. | [
"Returns",
"the",
"JSON",
"Representation",
"of",
"the",
"content",
"type",
"field",
"."
] | python | train | 26.782609 |
python-visualization/branca | branca/colormap.py | https://github.com/python-visualization/branca/blob/4e89e88a5a7ff3586f0852249c2c125f72316da8/branca/colormap.py#L195-L213 | def rgba_floats_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1.
"""
if x <= self.index[0]:
return self.colors[0]
if x >= self.index[-1]:
return self.colors[-1]
i... | [
"def",
"rgba_floats_tuple",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"<=",
"self",
".",
"index",
"[",
"0",
"]",
":",
"return",
"self",
".",
"colors",
"[",
"0",
"]",
"if",
"x",
">=",
"self",
".",
"index",
"[",
"-",
"1",
"]",
":",
"return",
... | Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1. | [
"Provides",
"the",
"color",
"corresponding",
"to",
"value",
"x",
"in",
"the",
"form",
"of",
"a",
"tuple",
"(",
"R",
"G",
"B",
"A",
")",
"with",
"float",
"values",
"between",
"0",
".",
"and",
"1",
"."
] | python | train | 38.157895 |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1985-L2007 | def smartResizeColumnsToContents( self ):
"""
Resizes the columns to the contents based on the user preferences.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
header = self.header()
header.blockSignals(True)
columns ... | [
"def",
"smartResizeColumnsToContents",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"header",
"=",
"self",
".",
"header",
"(",
")",
"header",
".",
"blockSignals",
"(",
"True",
")... | Resizes the columns to the contents based on the user preferences. | [
"Resizes",
"the",
"columns",
"to",
"the",
"contents",
"based",
"on",
"the",
"user",
"preferences",
"."
] | python | train | 32.217391 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_video.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_video.py#L383-L390 | def ffmpeg_works():
"""Tries to encode images with ffmpeg to check if it works."""
images = np.zeros((2, 32, 32, 3), dtype=np.uint8)
try:
_encode_gif(images, 2)
return True
except (IOError, OSError):
return False | [
"def",
"ffmpeg_works",
"(",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"32",
",",
"32",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"try",
":",
"_encode_gif",
"(",
"images",
",",
"2",
")",
"return",
"True",
... | Tries to encode images with ffmpeg to check if it works. | [
"Tries",
"to",
"encode",
"images",
"with",
"ffmpeg",
"to",
"check",
"if",
"it",
"works",
"."
] | python | train | 28.125 |
mjirik/io3d | io3d/misc.py | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/misc.py#L61-L93 | def obj_from_file(filename='annotation.yaml', filetype='auto'):
''' Read object from file '''
if filetype == 'auto':
_, ext = os.path.splitext(filename)
filetype = ext[1:]
if filetype in ('yaml', 'yml'):
from ruamel.yaml import YAML
yaml = YAML(typ="unsafe")
with op... | [
"def",
"obj_from_file",
"(",
"filename",
"=",
"'annotation.yaml'",
",",
"filetype",
"=",
"'auto'",
")",
":",
"if",
"filetype",
"==",
"'auto'",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"filetype",
"=",
"ext",
... | Read object from file | [
"Read",
"object",
"from",
"file"
] | python | train | 32.424242 |
thieman/dagobah | dagobah/core/core.py | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L313-L317 | def commit(self):
""" Store metadata on this Job to the backend. """
logger.debug('Committing job {0}'.format(self.name))
self.backend.commit_job(self._serialize())
self.parent.commit() | [
"def",
"commit",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Committing job {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"backend",
".",
"commit_job",
"(",
"self",
".",
"_serialize",
"(",
")",
")",
"self",
".",
"pa... | Store metadata on this Job to the backend. | [
"Store",
"metadata",
"on",
"this",
"Job",
"to",
"the",
"backend",
"."
] | python | train | 42.6 |
coleifer/walrus | walrus/database.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/database.py#L227-L234 | def graph(self, name, *args, **kwargs):
"""
Creates a :py:class:`Graph` instance.
:param str name: The namespace for the graph metadata.
:returns: a :py:class:`Graph` instance.
"""
return Graph(self, name, *args, **kwargs) | [
"def",
"graph",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Graph",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Creates a :py:class:`Graph` instance.
:param str name: The namespace for the graph metadata.
:returns: a :py:class:`Graph` instance. | [
"Creates",
"a",
":",
"py",
":",
"class",
":",
"Graph",
"instance",
"."
] | python | train | 33 |
eerimoq/bincopy | bincopy.py | https://github.com/eerimoq/bincopy/blob/5e02cd001c3e9b54729425db6bffad5f03e1beac/bincopy.py#L267-L308 | def add_data(self, minimum_address, maximum_address, data, overwrite):
"""Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown.
"""
if minimum_address == self.maximum_address:
self.maximum_address = ma... | [
"def",
"add_data",
"(",
"self",
",",
"minimum_address",
",",
"maximum_address",
",",
"data",
",",
"overwrite",
")",
":",
"if",
"minimum_address",
"==",
"self",
".",
"maximum_address",
":",
"self",
".",
"maximum_address",
"=",
"maximum_address",
"self",
".",
"d... | Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown. | [
"Add",
"given",
"data",
"to",
"this",
"segment",
".",
"The",
"added",
"data",
"must",
"be",
"adjacent",
"to",
"the",
"current",
"segment",
"data",
"otherwise",
"an",
"exception",
"is",
"thrown",
"."
] | python | train | 39.642857 |
glitchassassin/lackey | lackey/InputEmulation.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L30-L47 | def move(self, loc, yoff=None):
""" Moves cursor to specified location. Accepts the following arguments:
* ``move(loc)`` - Move cursor to ``Location``
* ``move(xoff, yoff)`` - Move cursor to offset from current location
"""
from .Geometry import Location
self._lock.acqu... | [
"def",
"move",
"(",
"self",
",",
"loc",
",",
"yoff",
"=",
"None",
")",
":",
"from",
".",
"Geometry",
"import",
"Location",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"if",
"isinstance",
"(",
"loc",
",",
"Location",
")",
":",
"mouse",
".",
"mov... | Moves cursor to specified location. Accepts the following arguments:
* ``move(loc)`` - Move cursor to ``Location``
* ``move(xoff, yoff)`` - Move cursor to offset from current location | [
"Moves",
"cursor",
"to",
"specified",
"location",
".",
"Accepts",
"the",
"following",
"arguments",
":"
] | python | train | 35.888889 |
twaddington/django-gravatar | django_gravatar/helpers.py | https://github.com/twaddington/django-gravatar/blob/c4849d93ed43b419eceff0ff2de83d4265597629/django_gravatar/helpers.py#L90-L108 | def get_gravatar_profile_url(email, secure=GRAVATAR_DEFAULT_SECURE):
"""
Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http
"""
if secure:
url_base = GRAVATAR_SECURE_URL
e... | [
"def",
"get_gravatar_profile_url",
"(",
"email",
",",
"secure",
"=",
"GRAVATAR_DEFAULT_SECURE",
")",
":",
"if",
"secure",
":",
"url_base",
"=",
"GRAVATAR_SECURE_URL",
"else",
":",
"url_base",
"=",
"GRAVATAR_URL",
"# Calculate the email hash",
"email_hash",
"=",
"calcu... | Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http | [
"Builds",
"a",
"url",
"to",
"a",
"gravatar",
"profile",
"from",
"an",
"email",
"address",
"."
] | python | test | 27.105263 |
Erotemic/utool | utool/util_profile.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L191-L213 | def clean_line_profile_text(text):
"""
Sorts the output from line profile by execution time
Removes entries which were not run
"""
#
profile_block_list = parse_rawprofile_blocks(text)
#profile_block_list = fix_rawprofile_blocks(profile_block_list)
#---
# FIXME can be written much nic... | [
"def",
"clean_line_profile_text",
"(",
"text",
")",
":",
"#",
"profile_block_list",
"=",
"parse_rawprofile_blocks",
"(",
"text",
")",
"#profile_block_list = fix_rawprofile_blocks(profile_block_list)",
"#---",
"# FIXME can be written much nicer",
"prefix_list",
",",
"timemap",
"... | Sorts the output from line profile by execution time
Removes entries which were not run | [
"Sorts",
"the",
"output",
"from",
"line",
"profile",
"by",
"execution",
"time",
"Removes",
"entries",
"which",
"were",
"not",
"run"
] | python | train | 34.478261 |
facetoe/zenpy | zenpy/lib/api_objects/__init__.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/__init__.py#L1275-L1280 | def group(self):
"""
| Comment: The id of a group
"""
if self.api and self.group_id:
return self.api._get_group(self.group_id) | [
"def",
"group",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"group_id",
":",
"return",
"self",
".",
"api",
".",
"_get_group",
"(",
"self",
".",
"group_id",
")"
] | | Comment: The id of a group | [
"|",
"Comment",
":",
"The",
"id",
"of",
"a",
"group"
] | python | train | 27.666667 |
mlperf/training | translation/tensorflow/transformer/model/transformer.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/transformer.py#L106-L135 | def encode(self, inputs, attention_bias):
"""Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch_size, input_length,... | [
"def",
"encode",
"(",
"self",
",",
"inputs",
",",
"attention_bias",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"encode\"",
")",
":",
"# Prepare inputs to the layer stack by adding positional encodings and",
"# applying dropout.",
"embedded_inputs",
"=",
"self",
"... | Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch_size, input_length, hidden_size] | [
"Generate",
"continuous",
"representation",
"for",
"inputs",
"."
] | python | train | 39.633333 |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/annealingmodel/quantum_monte_carlo.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/annealingmodel/quantum_monte_carlo.py#L112-L127 | def annealing(self):
'''
Annealing.
'''
self.__predicted_log_list = []
for cycle in range(self.__cycles_num):
for mc_step in range(self.__mc_step):
self.__move()
self.__gammma *= self.__fractional_reduction
if isinstance(self._... | [
"def",
"annealing",
"(",
"self",
")",
":",
"self",
".",
"__predicted_log_list",
"=",
"[",
"]",
"for",
"cycle",
"in",
"range",
"(",
"self",
".",
"__cycles_num",
")",
":",
"for",
"mc_step",
"in",
"range",
"(",
"self",
".",
"__mc_step",
")",
":",
"self",
... | Annealing. | [
"Annealing",
"."
] | python | train | 38.3125 |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/waves/alignWaves.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/waves/alignWaves.py#L7-L77 | def align(w,signals,mode):
""" Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other wa... | [
"def",
"align",
"(",
"w",
",",
"signals",
",",
"mode",
")",
":",
"nw",
"=",
"[",
"]",
"if",
"len",
"(",
"shape",
"(",
"signals",
")",
")",
"==",
"1",
":",
"signals",
"=",
"[",
"signals",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"signa... | Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other waves,
we have the amount of sam... | [
"Align",
"various",
"waves",
"in",
"a",
"specific",
"point",
".",
"Given",
"a",
"mode",
"of",
"alignment",
"this",
"function",
"computes",
"the",
"specific",
"time",
"point",
"of",
"a",
"wave",
"where",
"all",
"the",
"waves",
"would",
"be",
"aligned",
".",... | python | train | 34.267606 |
fermiPy/fermipy | fermipy/scripts/merit_skimmer.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/scripts/merit_skimmer.py#L103-L129 | def load_friend_chains(chain, friend_chains, txt, nfiles=None):
"""Load a list of trees from a file and add them as friends to the
chain."""
if re.search('.root?', txt) is not None:
c = ROOT.TChain(chain.GetName())
c.SetDirectory(0)
c.Add(txt)
friend_chains.append(c)
... | [
"def",
"load_friend_chains",
"(",
"chain",
",",
"friend_chains",
",",
"txt",
",",
"nfiles",
"=",
"None",
")",
":",
"if",
"re",
".",
"search",
"(",
"'.root?'",
",",
"txt",
")",
"is",
"not",
"None",
":",
"c",
"=",
"ROOT",
".",
"TChain",
"(",
"chain",
... | Load a list of trees from a file and add them as friends to the
chain. | [
"Load",
"a",
"list",
"of",
"trees",
"from",
"a",
"file",
"and",
"add",
"them",
"as",
"friends",
"to",
"the",
"chain",
"."
] | python | train | 27 |
phoebe-project/phoebe2 | phoebe/parameters/system.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/system.py#L7-L30 | def system(**kwargs):
"""
Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class... | [
"def",
"system",
"(",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"]",
"params",
"+=",
"[",
"FloatParameter",
"(",
"qualifier",
"=",
"'t0'",
",",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'t0'",
",",
"0.0",
")",
",",
"default_unit",
"=",
"u",... | Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Par... | [
"Generally",
"this",
"will",
"automatically",
"be",
"added",
"to",
"a",
"newly",
"initialized",
":",
"class",
":",
"phoebe",
".",
"frontend",
".",
"bundle",
".",
"Bundle"
] | python | train | 68.666667 |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Parser.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Parser.py#L1120-L1139 | def reindex(self, newIndexIDs=None, newIndexNames=None, newIndexClassNames=None, newIndexTagNames=None):
'''
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
... | [
"def",
"reindex",
"(",
"self",
",",
"newIndexIDs",
"=",
"None",
",",
"newIndexNames",
"=",
"None",
",",
"newIndexClassNames",
"=",
"None",
",",
"newIndexTagNames",
"=",
"None",
")",
":",
"if",
"newIndexIDs",
"is",
"not",
"None",
":",
"self",
".",
"indexIDs... | reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
@parma newIndexNames <bool/None> - None to leave same, otherwise new value to index names
@param newI... | [
"reindex",
"-",
"reindex",
"the",
"tree",
".",
"Optionally",
"change",
"what",
"fields",
"are",
"indexed",
"."
] | python | train | 53.85 |
MeaningCloud/meaningcloud-python | meaningcloud/Request.py | https://github.com/MeaningCloud/meaningcloud-python/blob/1dd76ecabeedd80c9bb14a1716d39657d645775f/meaningcloud/Request.py#L51-L67 | def setContent(self, type_, value):
"""
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
"""
if type_ in [self.CONTENT_TYPE_TXT, sel... | [
"def",
"setContent",
"(",
"self",
",",
"type_",
",",
"value",
")",
":",
"if",
"type_",
"in",
"[",
"self",
".",
"CONTENT_TYPE_TXT",
",",
"self",
".",
"CONTENT_TYPE_URL",
",",
"self",
".",
"CONTENT_TYPE_FILE",
"]",
":",
"if",
"type_",
"==",
"self",
".",
... | Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content | [
"Sets",
"the",
"content",
"that",
"s",
"going",
"to",
"be",
"sent",
"to",
"analyze",
"according",
"to",
"its",
"type"
] | python | train | 33.352941 |
benedictpaten/sonLib | bioio.py | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L586-L603 | def listFiles(self):
"""Gets all files in the temp file tree (which may be dirs).
"""
def fn(dirName, level, files):
if level == self.levelNo-1:
for fileName in os.listdir(dirName):
if fileName != "lock":
absFileName = os.pa... | [
"def",
"listFiles",
"(",
"self",
")",
":",
"def",
"fn",
"(",
"dirName",
",",
"level",
",",
"files",
")",
":",
"if",
"level",
"==",
"self",
".",
"levelNo",
"-",
"1",
":",
"for",
"fileName",
"in",
"os",
".",
"listdir",
"(",
"dirName",
")",
":",
"if... | Gets all files in the temp file tree (which may be dirs). | [
"Gets",
"all",
"files",
"in",
"the",
"temp",
"file",
"tree",
"(",
"which",
"may",
"be",
"dirs",
")",
"."
] | python | train | 41.277778 |
PierreRust/apigpio | apigpio/apigpio.py | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L559-L573 | def connect(self, address):
"""
Connect to a remote or local gpiod daemon.
:param address: a pair (address, port), the address must be already
resolved (for example an ip address)
:return:
"""
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self... | [
"def",
"connect",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"s",
".",
"setblocking",
"(",
"False",
")",
"# Disable the Nagl... | Connect to a remote or local gpiod daemon.
:param address: a pair (address, port), the address must be already
resolved (for example an ip address)
:return: | [
"Connect",
"to",
"a",
"remote",
"or",
"local",
"gpiod",
"daemon",
".",
":",
"param",
"address",
":",
"a",
"pair",
"(",
"address",
"port",
")",
"the",
"address",
"must",
"be",
"already",
"resolved",
"(",
"for",
"example",
"an",
"ip",
"address",
")",
":"... | python | train | 36.466667 |
senaite/senaite.core | bika/lims/browser/widgets/analysisspecificationwidget.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/analysisspecificationwidget.py#L253-L309 | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
"""Return a list of dictionaries fit for AnalysisSpecsResultsField
consumption.
If neither hidemin nor hidemax are specified, only services which have
float()able entries ... | [
"def",
"process_form",
"(",
"self",
",",
"instance",
",",
"field",
",",
"form",
",",
"empty_marker",
"=",
"None",
",",
"emptyReturnsMarker",
"=",
"False",
")",
":",
"values",
"=",
"[",
"]",
"# selected services",
"service_uids",
"=",
"form",
".",
"get",
"(... | Return a list of dictionaries fit for AnalysisSpecsResultsField
consumption.
If neither hidemin nor hidemax are specified, only services which have
float()able entries in result,min and max field will be included. If
hidemin and/or hidemax specified, results might contain empty min
... | [
"Return",
"a",
"list",
"of",
"dictionaries",
"fit",
"for",
"AnalysisSpecsResultsField",
"consumption",
"."
] | python | train | 43.438596 |
peri-source/peri | peri/util.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/util.py#L61-L91 | def delistify(a, b=None):
"""
If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delisti... | [
"def",
"delistify",
"(",
"a",
",",
"b",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".... | If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delistify(np.array([1.0]))
1.0
>>> d... | [
"If",
"a",
"single",
"element",
"list",
"extract",
"the",
"element",
"as",
"an",
"object",
"otherwise",
"leave",
"as",
"it",
"is",
"."
] | python | valid | 21.354839 |
byt3bl33d3r/CrackMapExec | cme/protocols/smb/db_navigator.py | https://github.com/byt3bl33d3r/CrackMapExec/blob/333f1c4e06884e85b2776459963ef85d182aba8e/cme/protocols/smb/db_navigator.py#L255-L262 | def complete_hosts(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = ["add", "remove", "dc"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)] | [
"def",
"complete_hosts",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"commands",
"=",
"[",
"\"add\"",
",",
"\"remove\"",
",",
"\"dc\"",
"]",
"mline",
"=",
"line",
".",
"partition",
"(",
"' '",
")",
"[",
"2",
"]",
... | Tab-complete 'creds' commands. | [
"Tab",
"-",
"complete",
"creds",
"commands",
"."
] | python | train | 34.5 |
kwikteam/phy | phy/cluster/views/feature.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/feature.py#L317-L344 | def on_channel_click(self, channel_id=None, key=None, button=None):
"""Respond to the click on a channel."""
channels = self.channel_ids
if channels is None:
return
if len(channels) == 1:
self.on_select()
return
assert len(channels) >= 2
... | [
"def",
"on_channel_click",
"(",
"self",
",",
"channel_id",
"=",
"None",
",",
"key",
"=",
"None",
",",
"button",
"=",
"None",
")",
":",
"channels",
"=",
"self",
".",
"channel_ids",
"if",
"channels",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"channe... | Respond to the click on a channel. | [
"Respond",
"to",
"the",
"click",
"on",
"a",
"channel",
"."
] | python | train | 39.142857 |
pytroll/pyorbital | pyorbital/astronomy.py | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/astronomy.py#L147-L152 | def sun_zenith_angle(utc_time, lon, lat):
"""Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees
"""
return np.rad2deg(np.arccos(cos_zen(utc_time, lon, lat))) | [
"def",
"sun_zenith_angle",
"(",
"utc_time",
",",
"lon",
",",
"lat",
")",
":",
"return",
"np",
".",
"rad2deg",
"(",
"np",
".",
"arccos",
"(",
"cos_zen",
"(",
"utc_time",
",",
"lon",
",",
"lat",
")",
")",
")"
] | Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees | [
"Sun",
"-",
"zenith",
"angle",
"for",
"*",
"lon",
"*",
"*",
"lat",
"*",
"at",
"*",
"utc_time",
"*",
".",
"lon",
"lat",
"in",
"degrees",
".",
"The",
"angle",
"returned",
"is",
"given",
"in",
"degrees"
] | python | train | 38.166667 |
pypa/pipenv | pipenv/vendor/distlib/manifest.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L209-L254 | def _parse_directive(self, directive):
"""
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
"""
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
... | [
"def",
"_parse_directive",
"(",
"self",
",",
"directive",
")",
":",
"words",
"=",
"directive",
".",
"split",
"(",
")",
"if",
"len",
"(",
"words",
")",
"==",
"1",
"and",
"words",
"[",
"0",
"]",
"not",
"in",
"(",
"'include'",
",",
"'exclude'",
",",
"... | Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns | [
"Validate",
"a",
"directive",
".",
":",
"param",
"directive",
":",
"The",
"directive",
"to",
"validate",
".",
":",
"return",
":",
"A",
"tuple",
"of",
"action",
"patterns",
"thedir",
"dir_patterns"
] | python | train | 38.826087 |
bxlab/bx-python | scripts/maf_tile_2.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/scripts/maf_tile_2.py#L139-L272 | def do_interval( sources, index, out, ref_src, start, end, seq_db, missing_data, strand ):
"""
Join together alignment blocks to create a semi human projected local
alignment (small reference sequence deletions are kept as supported by
the local alignment).
"""
ref_src_size = None
# Make s... | [
"def",
"do_interval",
"(",
"sources",
",",
"index",
",",
"out",
",",
"ref_src",
",",
"start",
",",
"end",
",",
"seq_db",
",",
"missing_data",
",",
"strand",
")",
":",
"ref_src_size",
"=",
"None",
"# Make sure the reference component is also the first in the source l... | Join together alignment blocks to create a semi human projected local
alignment (small reference sequence deletions are kept as supported by
the local alignment). | [
"Join",
"together",
"alignment",
"blocks",
"to",
"create",
"a",
"semi",
"human",
"projected",
"local",
"alignment",
"(",
"small",
"reference",
"sequence",
"deletions",
"are",
"kept",
"as",
"supported",
"by",
"the",
"local",
"alignment",
")",
"."
] | python | train | 52.059701 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_system.py#L199-L224 | def GetTSKFileByPathSpec(self, path_spec):
"""Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location.
"""
# O... | [
"def",
"GetTSKFileByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"# Opening a file by inode number is faster than opening a file",
"# by location.",
"inode",
"=",
"getattr",
"(",
"path_spec",
",",
"'inode'",
",",
"None",
")",
"location",
"=",
"getattr",
"(",
"p... | Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location. | [
"Retrieves",
"the",
"SleuthKit",
"file",
"object",
"for",
"a",
"path",
"specification",
"."
] | python | train | 29.615385 |
eyurtsev/fcsparser | fcsparser/api.py | https://github.com/eyurtsev/fcsparser/blob/710e8e31d4b09ff6e73d47d86770be6ca2f4282c/fcsparser/api.py#L153-L195 | def read_header(self, file_handle, nextdata_offset=0):
"""Read the header of the FCS file.
The header specifies where the annotation, data and analysis are located inside the binary
file.
Args:
file_handle: buffer containing FCS file.
nextdata_offset: byte offse... | [
"def",
"read_header",
"(",
"self",
",",
"file_handle",
",",
"nextdata_offset",
"=",
"0",
")",
":",
"header",
"=",
"{",
"'FCS format'",
":",
"file_handle",
".",
"read",
"(",
"6",
")",
"}",
"file_handle",
".",
"read",
"(",
"4",
")",
"# 4 space characters aft... | Read the header of the FCS file.
The header specifies where the annotation, data and analysis are located inside the binary
file.
Args:
file_handle: buffer containing FCS file.
nextdata_offset: byte offset of a set header from file start specified by $NEXTDATA | [
"Read",
"the",
"header",
"of",
"the",
"FCS",
"file",
"."
] | python | train | 42.534884 |
DataBiosphere/dsub | dsub/commands/dsub.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/commands/dsub.py#L1155-L1193 | def _name_for_command(command):
r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the caller should just
specify a "--name... | [
"def",
"_name_for_command",
"(",
"command",
")",
":",
"lines",
"=",
"command",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"and",
"not",
"line",
".",
"startswith",
"(",
"'... | r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the caller should just
specify a "--name" on the command-line.
For exam... | [
"r",
"Craft",
"a",
"simple",
"command",
"name",
"from",
"the",
"command",
"."
] | python | valid | 29.641026 |
BerkeleyAutomation/autolab_core | autolab_core/rigid_transformations.py | https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/rigid_transformations.py#L1224-L1237 | def inverse(self):
"""Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform.
"""
inv_rot = np.linalg.inv(self.rotation)
inv_scale = 1.0 / self.scale
inv_trans = -inv_sc... | [
"def",
"inverse",
"(",
"self",
")",
":",
"inv_rot",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"self",
".",
"rotation",
")",
"inv_scale",
"=",
"1.0",
"/",
"self",
".",
"scale",
"inv_trans",
"=",
"-",
"inv_scale",
"*",
"inv_rot",
".",
"dot",
"(",
"s... | Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform. | [
"Take",
"the",
"inverse",
"of",
"the",
"similarity",
"transform",
"."
] | python | train | 38 |
python-beaver/python-beaver | beaver/worker/tail.py | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L130-L184 | def _buffer_extract(self, data):
"""
Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |enti... | [
"def",
"_buffer_extract",
"(",
"self",
",",
"data",
")",
":",
"# Extract token-delimited entities from the input string with the split command.",
"# There's a bit of craftiness here with the -1 parameter. Normally split would",
"# behave no differently regardless of if the token lies at the ver... | Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |entity| Decode(entity) }.each do ... | [
"Extract",
"takes",
"an",
"arbitrary",
"string",
"of",
"input",
"data",
"and",
"returns",
"an",
"array",
"of",
"tokenized",
"entities",
"provided",
"there",
"were",
"any",
"available",
"to",
"extract",
".",
"This",
"makes",
"for",
"easy",
"processing",
"of",
... | python | train | 52.981818 |
dwavesystems/dwave_networkx | dwave_networkx/algorithms/elimination_ordering.py | https://github.com/dwavesystems/dwave_networkx/blob/9ea1223ddbc7e86db2f90b8b23e250e6642c3d68/dwave_networkx/algorithms/elimination_ordering.py#L677-L700 | def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
"""
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
... | [
"def",
"_graph_reduction",
"(",
"adj",
",",
"x",
",",
"g",
",",
"f",
")",
":",
"as_list",
"=",
"set",
"(",
")",
"as_nodes",
"=",
"{",
"v",
"for",
"v",
"in",
"adj",
"if",
"len",
"(",
"adj",
"[",
"v",
"]",
")",
"<=",
"f",
"and",
"is_almost_simpli... | we can go ahead and remove any simplicial or almost-simplicial vertices from adj. | [
"we",
"can",
"go",
"ahead",
"and",
"remove",
"any",
"simplicial",
"or",
"almost",
"-",
"simplicial",
"vertices",
"from",
"adj",
"."
] | python | train | 28.75 |
pandas-dev/pandas | pandas/core/apply.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/apply.py#L183-L198 | def apply_raw(self):
""" apply to the values as a numpy array """
try:
result = reduction.reduce(self.values, self.f, axis=self.axis)
except Exception:
result = np.apply_along_axis(self.f, self.axis, self.values)
# TODO: mixed type case
if result.ndim ==... | [
"def",
"apply_raw",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"reduction",
".",
"reduce",
"(",
"self",
".",
"values",
",",
"self",
".",
"f",
",",
"axis",
"=",
"self",
".",
"axis",
")",
"except",
"Exception",
":",
"result",
"=",
"np",
".",
... | apply to the values as a numpy array | [
"apply",
"to",
"the",
"values",
"as",
"a",
"numpy",
"array"
] | python | train | 38.625 |
craffel/mir_eval | mir_eval/sonify.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/sonify.py#L14-L60 | def clicks(times, fs, click=None, length=None):
"""Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
cli... | [
"def",
"clicks",
"(",
"times",
",",
"fs",
",",
"click",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"# Create default click signal",
"if",
"click",
"is",
"None",
":",
"# 1 kHz tone, 100ms",
"click",
"=",
"np",
".",
"sin",
"(",
"2",
"*",
"np",
".... | Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
click signal, defaults to a 1 kHz blip
length : int
... | [
"Returns",
"a",
"signal",
"with",
"the",
"signal",
"click",
"placed",
"at",
"each",
"specified",
"time"
] | python | train | 30.170213 |
commonsense/metanl | metanl/nltk_morphy.py | https://github.com/commonsense/metanl/blob/4b9ae8353489cc409bebd7e1fe10ab5b527b078e/metanl/nltk_morphy.py#L103-L116 | def _morphy_best(word, pos=None):
"""
Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem().
"""
results = []
if pos is None:
pos = 'nvar'
for pos_item in pos:
results.extend(morphy(word, pos_item))
if not results:
... | [
"def",
"_morphy_best",
"(",
"word",
",",
"pos",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"pos",
"is",
"None",
":",
"pos",
"=",
"'nvar'",
"for",
"pos_item",
"in",
"pos",
":",
"results",
".",
"extend",
"(",
"morphy",
"(",
"word",
",",
... | Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem(). | [
"Get",
"the",
"most",
"likely",
"stem",
"for",
"a",
"word",
"using",
"Morphy",
"once",
"the",
"input",
"has",
"been",
"pre",
"-",
"processed",
"by",
"morphy_stem",
"()",
"."
] | python | train | 27.928571 |
DataONEorg/d1_python | lib_common/src/d1_common/xml.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/xml.py#L426-L442 | def format_diff_pyxb(a_pyxb, b_pyxb):
"""Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta
"""
return '\n'.join(
difflib.ndiff(
serialize_to_xml_str(a_pyxb).splitlines(),
seri... | [
"def",
"format_diff_pyxb",
"(",
"a_pyxb",
",",
"b_pyxb",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"serialize_to_xml_str",
"(",
"a_pyxb",
")",
".",
"splitlines",
"(",
")",
",",
"serialize_to_xml_str",
"(",
"b_pyxb",
")",
... | Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta | [
"Create",
"a",
"diff",
"between",
"two",
"PyXB",
"objects",
"."
] | python | train | 21.058824 |
googleapis/google-cloud-python | irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L1964-L2066 | def send_shift_handoff(
self,
parent,
recipients,
subject,
cc=None,
notes_content_type=None,
notes_content=None,
incidents=None,
preview_only=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.meth... | [
"def",
"send_shift_handoff",
"(",
"self",
",",
"parent",
",",
"recipients",
",",
"subject",
",",
"cc",
"=",
"None",
",",
"notes_content_type",
"=",
"None",
",",
"notes_content",
"=",
"None",
",",
"incidents",
"=",
"None",
",",
"preview_only",
"=",
"None",
... | Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initial... | [
"Sends",
"a",
"summary",
"of",
"the",
"shift",
"for",
"oncall",
"handoff",
"."
] | python | train | 42.776699 |
ivankorobkov/python-inject | src/inject.py | https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L108-L114 | def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with _INJECTOR_LOCK:
if _INJECTOR:
return _INJECTOR
return configure(config, bind_in_runtime=bind_in_runtime) | [
"def",
"configure_once",
"(",
"config",
"=",
"None",
",",
"bind_in_runtime",
"=",
"True",
")",
":",
"with",
"_INJECTOR_LOCK",
":",
"if",
"_INJECTOR",
":",
"return",
"_INJECTOR",
"return",
"configure",
"(",
"config",
",",
"bind_in_runtime",
"=",
"bind_in_runtime"... | Create an injector with a callable config if not present, otherwise, do nothing. | [
"Create",
"an",
"injector",
"with",
"a",
"callable",
"config",
"if",
"not",
"present",
"otherwise",
"do",
"nothing",
"."
] | python | train | 40.285714 |
rstoneback/pysat | pysat/instruments/supermag_magnetometer.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/supermag_magnetometer.py#L485-L544 | def format_baseline_list(baseline_list):
"""Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG file
Returns
--... | [
"def",
"format_baseline_list",
"(",
"baseline_list",
")",
":",
"uniq_base",
"=",
"dict",
"(",
")",
"uniq_delta",
"=",
"dict",
"(",
")",
"for",
"bline",
"in",
"baseline_list",
":",
"bsplit",
"=",
"bline",
".",
"split",
"(",
")",
"bdate",
"=",
"\" \"",
"."... | Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG file
Returns
---------
base_string : (str)
Single s... | [
"Format",
"the",
"list",
"of",
"baseline",
"information",
"from",
"the",
"loaded",
"files",
"into",
"a",
"cohesive",
"informative",
"string"
] | python | train | 30.9 |
tensorflow/probability | tensorflow_probability/python/distributions/linear_gaussian_ssm.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1522-L1532 | def kalman_transition(filtered_mean, filtered_cov,
transition_matrix, transition_noise):
"""Propagate a filtered distribution through a transition model."""
predicted_mean = _propagate_mean(filtered_mean,
transition_matrix,
... | [
"def",
"kalman_transition",
"(",
"filtered_mean",
",",
"filtered_cov",
",",
"transition_matrix",
",",
"transition_noise",
")",
":",
"predicted_mean",
"=",
"_propagate_mean",
"(",
"filtered_mean",
",",
"transition_matrix",
",",
"transition_noise",
")",
"predicted_cov",
"... | Propagate a filtered distribution through a transition model. | [
"Propagate",
"a",
"filtered",
"distribution",
"through",
"a",
"transition",
"model",
"."
] | python | test | 47 |
SwissDataScienceCenter/renku-python | renku/cli/_exc.py | https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L183-L189 | def _format_issue_url(self):
"""Format full issue URL."""
query = urlencode({
'title': self._format_issue_title(),
'body': self._format_issue_body(),
})
return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query | [
"def",
"_format_issue_url",
"(",
"self",
")",
":",
"query",
"=",
"urlencode",
"(",
"{",
"'title'",
":",
"self",
".",
"_format_issue_title",
"(",
")",
",",
"'body'",
":",
"self",
".",
"_format_issue_body",
"(",
")",
",",
"}",
")",
"return",
"self",
".",
... | Format full issue URL. | [
"Format",
"full",
"issue",
"URL",
"."
] | python | train | 36.714286 |
475Cumulus/TBone | tbone/resources/resources.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/resources/resources.py#L245-L258 | async def _wrap_http(self, handler, *args, **kwargs):
''' wraps a handler with an HTTP request-response cycle'''
try:
method = self.request_method()
# support preflight requests when CORS is enabled
if method == 'OPTIONS':
return self.build_http_respon... | [
"async",
"def",
"_wrap_http",
"(",
"self",
",",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"=",
"self",
".",
"request_method",
"(",
")",
"# support preflight requests when CORS is enabled",
"if",
"method",
"==",
"'O... | wraps a handler with an HTTP request-response cycle | [
"wraps",
"a",
"handler",
"with",
"an",
"HTTP",
"request",
"-",
"response",
"cycle"
] | python | train | 48.428571 |
openstack/networking-hyperv | networking_hyperv/neutron/trunk_driver.py | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/trunk_driver.py#L61-L85 | def handle_subports(self, subports, event_type):
"""Subport data model change from the server."""
LOG.debug("Subports event received: %(event_type)s. "
"Subports: %(subports)s",
{'event_type': event_type, 'subports': subports})
# update the cache.
if... | [
"def",
"handle_subports",
"(",
"self",
",",
"subports",
",",
"event_type",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Subports event received: %(event_type)s. \"",
"\"Subports: %(subports)s\"",
",",
"{",
"'event_type'",
":",
"event_type",
",",
"'subports'",
":",
"subports... | Subport data model change from the server. | [
"Subport",
"data",
"model",
"change",
"from",
"the",
"server",
"."
] | python | train | 40.48 |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L26-L37 | def chebyshev(point1, point2):
"""Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return max(abs(point1[0] - point2[0]),... | [
"def",
"chebyshev",
"(",
"point1",
",",
"point2",
")",
":",
"return",
"max",
"(",
"abs",
"(",
"point1",
"[",
"0",
"]",
"-",
"point2",
"[",
"0",
"]",
")",
",",
"abs",
"(",
"point1",
"[",
"1",
"]",
"-",
"point2",
"[",
"1",
"]",
")",
")"
] | Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float | [
"Computes",
"distance",
"between",
"2D",
"points",
"using",
"chebyshev",
"metric"
] | python | train | 28.083333 |
LonamiWebs/Telethon | telethon/extensions/messagepacker.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/messagepacker.py#L40-L112 | async def get(self):
"""
Returns (batch, data) if one or more items could be retrieved.
If the cancellation occurs or only invalid items were in the
queue, (None, None) will be returned instead.
"""
if not self._deque:
self._ready.clear()
await se... | [
"async",
"def",
"get",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_deque",
":",
"self",
".",
"_ready",
".",
"clear",
"(",
")",
"await",
"self",
".",
"_ready",
".",
"wait",
"(",
")",
"buffer",
"=",
"io",
".",
"BytesIO",
"(",
")",
"batch",
... | Returns (batch, data) if one or more items could be retrieved.
If the cancellation occurs or only invalid items were in the
queue, (None, None) will be returned instead. | [
"Returns",
"(",
"batch",
"data",
")",
"if",
"one",
"or",
"more",
"items",
"could",
"be",
"retrieved",
"."
] | python | train | 38.630137 |
datajoint/datajoint-python | datajoint/errors.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/errors.py#L18-L23 | def is_connection_error(e):
"""
Checks if error e pertains to a connection issue
"""
return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
(isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values()) | [
"def",
"is_connection_error",
"(",
"e",
")",
":",
"return",
"(",
"isinstance",
"(",
"e",
",",
"err",
".",
"InterfaceError",
")",
"and",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"\"(0, '')\"",
")",
"or",
"(",
"isinstance",
"(",
"e",
",",
"err",
".",
"... | Checks if error e pertains to a connection issue | [
"Checks",
"if",
"error",
"e",
"pertains",
"to",
"a",
"connection",
"issue"
] | python | train | 43.833333 |
saltstack/salt | salt/modules/keystoneng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystoneng.py#L648-L660 | def endpoint_delete(auth=None, **kwargs):
'''
Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_endpoint(**kwarg... | [
"def",
"endpoint_delete",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"delete_endpoint",
"(",
"*"... | Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9 | [
"Delete",
"an",
"endpoint"
] | python | train | 23.846154 |
mitsei/dlkit | dlkit/json_/utilities.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/utilities.py#L847-L858 | def get_effective_agent_id_with_proxy(proxy):
"""Given a Proxy, returns the Id of the effective Agent"""
if is_authenticated_with_proxy(proxy):
if proxy.has_effective_agent():
return proxy.get_effective_agent_id()
else:
return proxy.get_authentication().get_agent_id()
... | [
"def",
"get_effective_agent_id_with_proxy",
"(",
"proxy",
")",
":",
"if",
"is_authenticated_with_proxy",
"(",
"proxy",
")",
":",
"if",
"proxy",
".",
"has_effective_agent",
"(",
")",
":",
"return",
"proxy",
".",
"get_effective_agent_id",
"(",
")",
"else",
":",
"r... | Given a Proxy, returns the Id of the effective Agent | [
"Given",
"a",
"Proxy",
"returns",
"the",
"Id",
"of",
"the",
"effective",
"Agent"
] | python | train | 38 |
ethereum/py_ecc | py_ecc/bls/utils.py | https://github.com/ethereum/py_ecc/blob/2088796c59574b256dc8e18f8c9351bc3688ca71/py_ecc/bls/utils.py#L189-L219 | def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
# b_flag == 1 indicates the infinity point
b_flag1 = (z1 % POW_2_383) // POW_2_382
if b_flag1 == 1:
return Z2
x1 = z1 % POW_2_381
x2 = z... | [
"def",
"decompress_G2",
"(",
"p",
":",
"G2Compressed",
")",
"->",
"G2Uncompressed",
":",
"z1",
",",
"z2",
"=",
"p",
"# b_flag == 1 indicates the infinity point",
"b_flag1",
"=",
"(",
"z1",
"%",
"POW_2_383",
")",
"//",
"POW_2_382",
"if",
"b_flag1",
"==",
"1",
... | Recovers x and y coordinates from the compressed point (z1, z2). | [
"Recovers",
"x",
"and",
"y",
"coordinates",
"from",
"the",
"compressed",
"point",
"(",
"z1",
"z2",
")",
"."
] | python | test | 32.935484 |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1538-L1541 | def list_rbac_policies(self, retrieve_all=True, **_params):
"""Fetch a list of all RBAC policies for a project."""
return self.list('rbac_policies', self.rbac_policies_path,
retrieve_all, **_params) | [
"def",
"list_rbac_policies",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"list",
"(",
"'rbac_policies'",
",",
"self",
".",
"rbac_policies_path",
",",
"retrieve_all",
",",
"*",
"*",
"_params",
")... | Fetch a list of all RBAC policies for a project. | [
"Fetch",
"a",
"list",
"of",
"all",
"RBAC",
"policies",
"for",
"a",
"project",
"."
] | python | train | 59 |
hMatoba/Piexif | piexif/_common.py | https://github.com/hMatoba/Piexif/blob/afd0d232cf05cf530423f4b2a82ab291f150601a/piexif/_common.py#L29-L58 | def read_exif_from_file(filename):
"""Slices JPEG meta data into a list from JPEG binary data.
"""
f = open(filename, "rb")
data = f.read(6)
if data[0:2] != b"\xff\xd8":
raise InvalidImageDataError("Given data isn't JPEG.")
head = data[2:6]
HEAD_LENGTH = 4
exif = None
while... | [
"def",
"read_exif_from_file",
"(",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"data",
"=",
"f",
".",
"read",
"(",
"6",
")",
"if",
"data",
"[",
"0",
":",
"2",
"]",
"!=",
"b\"\\xff\\xd8\"",
":",
"raise",
"InvalidImageD... | Slices JPEG meta data into a list from JPEG binary data. | [
"Slices",
"JPEG",
"meta",
"data",
"into",
"a",
"list",
"from",
"JPEG",
"binary",
"data",
"."
] | python | train | 25.533333 |
markovmodel/PyEMMA | pyemma/_base/parallel.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/parallel.py#L42-L58 | def n_jobs(self):
""" Returns number of jobs/threads to use during assignment of data.
Returns
-------
If None it will return the setting of 'PYEMMA_NJOBS' or
'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables exist,
the number of processor... | [
"def",
"n_jobs",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_n_jobs'",
")",
":",
"self",
".",
"_n_jobs",
"=",
"get_n_jobs",
"(",
"logger",
"=",
"getattr",
"(",
"self",
",",
"'logger'",
")",
")",
"return",
"self",
".",
"_n_jobs... | Returns number of jobs/threads to use during assignment of data.
Returns
-------
If None it will return the setting of 'PYEMMA_NJOBS' or
'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables exist,
the number of processors /or cores is returned.
... | [
"Returns",
"number",
"of",
"jobs",
"/",
"threads",
"to",
"use",
"during",
"assignment",
"of",
"data",
"."
] | python | train | 41.058824 |
DataONEorg/d1_python | dev_tools/src/d1_dev/src-format-docstrings.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-format-docstrings.py#L186-L270 | def unwrap(s, node_indent):
"""Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_li... | [
"def",
"unwrap",
"(",
"s",
",",
"node_indent",
")",
":",
"def",
"get_indent",
"(",
")",
":",
"if",
"line_str",
".",
"startswith",
"(",
"'\"\"\"'",
")",
":",
"return",
"node_indent",
"return",
"len",
"(",
"re",
".",
"match",
"(",
"r\"^( *)\"",
",",
"lin... | Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_list` until a line is encountered tha... | [
"Group",
"lines",
"of",
"a",
"docstring",
"to",
"blocks",
"."
] | python | train | 32.929412 |
gem/oq-engine | openquake/hazardlib/gsim/allen_2012.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/allen_2012.py#L93-L120 | def _compute_mean(self, C, mag, rrup):
"""
Compute mean value according to equation 18, page 32.
"""
# see table 3, page 14
R1 = 90.
R2 = 150.
# see equation 19, page 32
m_ref = mag - 4
r1 = R1 + C['c8'] * m_ref
r2 = R2 + C['c11'] * m_ref
... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"# see table 3, page 14",
"R1",
"=",
"90.",
"R2",
"=",
"150.",
"# see equation 19, page 32",
"m_ref",
"=",
"mag",
"-",
"4",
"r1",
"=",
"R1",
"+",
"C",
"[",
"'c8'",
"]",
... | Compute mean value according to equation 18, page 32. | [
"Compute",
"mean",
"value",
"according",
"to",
"equation",
"18",
"page",
"32",
"."
] | python | train | 31.821429 |
MechanicalSoup/MechanicalSoup | mechanicalsoup/browser.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/browser.py#L142-L226 | def _request(self, form, url=None, **kwargs):
"""Extract input data from the form to pass to a Requests session."""
method = str(form.get("method", "get"))
action = form.get("action")
url = urllib.parse.urljoin(url, action)
if url is None: # This happens when both `action` and `... | [
"def",
"_request",
"(",
"self",
",",
"form",
",",
"url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"str",
"(",
"form",
".",
"get",
"(",
"\"method\"",
",",
"\"get\"",
")",
")",
"action",
"=",
"form",
".",
"get",
"(",
"\"action... | Extract input data from the form to pass to a Requests session. | [
"Extract",
"input",
"data",
"from",
"the",
"form",
"to",
"pass",
"to",
"a",
"Requests",
"session",
"."
] | python | train | 45.541176 |
HewlettPackard/python-hpOneView | hpOneView/resources/servers/server_profiles.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_profiles.py#L253-L270 | def get_available_storage_system(self, **kwargs):
"""
Retrieves a specific storage system and its associated volumes available to the server profile based
on the given server hardware type and enclosure group.
Args:
enclosureGroupUri (str):
The URI of the enclo... | [
"def",
"get_available_storage_system",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"self",
".",
"_helper",
".",
"build_uri_with_query_string",
"(",
"kwargs",
",",
"'/available-storage-system'",
")",
"return",
"self",
".",
"_helper",
".",
"do_get"... | Retrieves a specific storage system and its associated volumes available to the server profile based
on the given server hardware type and enclosure group.
Args:
enclosureGroupUri (str):
The URI of the enclosure group associated with the resource.
serverHardwareType... | [
"Retrieves",
"a",
"specific",
"storage",
"system",
"and",
"its",
"associated",
"volumes",
"available",
"to",
"the",
"server",
"profile",
"based",
"on",
"the",
"given",
"server",
"hardware",
"type",
"and",
"enclosure",
"group",
"."
] | python | train | 42.833333 |
pandas-dev/pandas | pandas/core/arrays/datetimes.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimes.py#L1196-L1230 | def month_name(self, locale=None):
"""
Return the month names of the DateTimeIndex with specified locale.
.. versionadded:: 0.23.0
Parameters
----------
locale : str, optional
Locale determining the language in which to return the month name.
Def... | [
"def",
"month_name",
"(",
"self",
",",
"locale",
"=",
"None",
")",
":",
"if",
"self",
".",
"tz",
"is",
"not",
"None",
"and",
"not",
"timezones",
".",
"is_utc",
"(",
"self",
".",
"tz",
")",
":",
"values",
"=",
"self",
".",
"_local_timestamps",
"(",
... | Return the month names of the DateTimeIndex with specified locale.
.. versionadded:: 0.23.0
Parameters
----------
locale : str, optional
Locale determining the language in which to return the month name.
Default is English locale.
Returns
------... | [
"Return",
"the",
"month",
"names",
"of",
"the",
"DateTimeIndex",
"with",
"specified",
"locale",
"."
] | python | train | 31.714286 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L34-L43 | def convert_other_format(filename, format):
"""
转换为png图片
:param filename: 图片文件名
:return:
"""
img = Image.open(filename)
rp = ReParser()
c_filename = rp.replace(r'\..*$', format, filename)
img.save(c_filename) | [
"def",
"convert_other_format",
"(",
"filename",
",",
"format",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"filename",
")",
"rp",
"=",
"ReParser",
"(",
")",
"c_filename",
"=",
"rp",
".",
"replace",
"(",
"r'\\..*$'",
",",
"format",
",",
"filename",
... | 转换为png图片
:param filename: 图片文件名
:return: | [
"转换为png图片",
":",
"param",
"filename",
":",
"图片文件名",
":",
"return",
":"
] | python | train | 23.5 |
saltstack/salt | salt/utils/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/vmware.py#L2663-L2689 | def get_scsi_address_to_lun_map(host_ref, storage_system=None, hostname=None):
'''
Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
scsi address
host_ref
The vim.HostSystem object representing the host that contains the
requested disks.
storage_system
... | [
"def",
"get_scsi_address_to_lun_map",
"(",
"host_ref",
",",
"storage_system",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"not",
"hostname",
":",
"hostname",
"=",
"get_managed_object_name",
"(",
"host_ref",
")",
"si",
"=",
"get_service_instance_from... | Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
scsi address
host_ref
The vim.HostSystem object representing the host that contains the
requested disks.
storage_system
The host's storage system. Default is None.
hostname
Name of the host. This ar... | [
"Returns",
"a",
"map",
"of",
"all",
"vim",
".",
"ScsiLun",
"objects",
"on",
"a",
"ESXi",
"host",
"keyed",
"by",
"their",
"scsi",
"address"
] | python | train | 38.962963 |
MichaelAquilina/hashedindex | hashedindex/__init__.py | https://github.com/MichaelAquilina/hashedindex/blob/5a84dcd6c697ea04162cf7b2683fa2723845b51c/hashedindex/__init__.py#L98-L112 | def get_term_frequency(self, term, document, normalized=False):
"""
Returns the frequency of the term specified in the document.
"""
if document not in self._documents:
raise IndexError(DOCUMENT_DOES_NOT_EXIST)
if term not in self._terms:
raise IndexError... | [
"def",
"get_term_frequency",
"(",
"self",
",",
"term",
",",
"document",
",",
"normalized",
"=",
"False",
")",
":",
"if",
"document",
"not",
"in",
"self",
".",
"_documents",
":",
"raise",
"IndexError",
"(",
"DOCUMENT_DOES_NOT_EXIST",
")",
"if",
"term",
"not",... | Returns the frequency of the term specified in the document. | [
"Returns",
"the",
"frequency",
"of",
"the",
"term",
"specified",
"in",
"the",
"document",
"."
] | python | train | 32.666667 |
chaoss/grimoirelab-perceval | perceval/backends/core/slack.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/slack.py#L357-L374 | def history(self, channel, oldest=None, latest=None):
"""Fetch the history of a channel."""
resource = self.RCHANNEL_HISTORY
params = {
self.PCHANNEL: channel,
self.PCOUNT: self.max_items
}
if oldest is not None:
params[self.POLDEST] = oldes... | [
"def",
"history",
"(",
"self",
",",
"channel",
",",
"oldest",
"=",
"None",
",",
"latest",
"=",
"None",
")",
":",
"resource",
"=",
"self",
".",
"RCHANNEL_HISTORY",
"params",
"=",
"{",
"self",
".",
"PCHANNEL",
":",
"channel",
",",
"self",
".",
"PCOUNT",
... | Fetch the history of a channel. | [
"Fetch",
"the",
"history",
"of",
"a",
"channel",
"."
] | python | test | 25.111111 |
tradenity/python-sdk | tradenity/resources/country.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/country.py#L500-L520 | def delete_country_by_id(cls, country_id, **kwargs):
"""Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id,... | [
"def",
"delete_country_by_id",
"(",
"cls",
",",
"country_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_country_by_id_w... | Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id, async=True)
>>> result = thread.get()
:param a... | [
"Delete",
"Country"
] | python | train | 40.952381 |
pantsbuild/pex | pex/platforms.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/platforms.py#L72-L83 | def _get_supported_for_any_abi(version=None, platform=None, impl=None, force_manylinux=False):
"""Generates supported tags for unspecified ABI types to support more intuitive cross-platform
resolution."""
unique_tags = {
tag for abi in _gen_all_abis(impl, version)
for tag in _get_supported(version=vers... | [
"def",
"_get_supported_for_any_abi",
"(",
"version",
"=",
"None",
",",
"platform",
"=",
"None",
",",
"impl",
"=",
"None",
",",
"force_manylinux",
"=",
"False",
")",
":",
"unique_tags",
"=",
"{",
"tag",
"for",
"abi",
"in",
"_gen_all_abis",
"(",
"impl",
",",... | Generates supported tags for unspecified ABI types to support more intuitive cross-platform
resolution. | [
"Generates",
"supported",
"tags",
"for",
"unspecified",
"ABI",
"types",
"to",
"support",
"more",
"intuitive",
"cross",
"-",
"platform",
"resolution",
"."
] | python | train | 44.666667 |
aliyun/aliyun-odps-python-sdk | odps/df/expr/merge.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/merge.py#L1048-L1110 | def intersect(left, *rights, **kwargs):
"""
Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(p... | [
"def",
"intersect",
"(",
"left",
",",
"*",
"rights",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"time",
"from",
".",
".",
"utils",
"import",
"output",
"distinct",
"=",
"kwargs",
".",
"get",
"(",
"'distinct'",
",",
"False",
")",
"if",
"isinstance",
... | Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3,... | [
"Calc",
"intersection",
"among",
"datasets"
] | python | train | 30.031746 |
acorg/dark-matter | dark/features.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/features.py#L136-L195 | def add(self, fig, title, minX, maxX, offsetAdjuster=None,
sequenceFetcher=None):
"""
Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib fig... | [
"def",
"add",
"(",
"self",
",",
"fig",
",",
"title",
",",
"minX",
",",
"maxX",
",",
"offsetAdjuster",
"=",
"None",
",",
"sequenceFetcher",
"=",
"None",
")",
":",
"offsetAdjuster",
"=",
"offsetAdjuster",
"or",
"(",
"lambda",
"x",
":",
"x",
")",
"fig",
... | Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011... | [
"Find",
"the",
"features",
"for",
"a",
"sequence",
"title",
".",
"If",
"there",
"aren",
"t",
"too",
"many",
"add",
"the",
"features",
"to",
"C",
"{",
"fig",
"}",
".",
"Return",
"information",
"about",
"the",
"features",
"as",
"described",
"below",
"."
] | python | train | 46.266667 |
Capitains/MyCapytain | MyCapytain/resources/texts/local/capitains/cts.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L376-L384 | def getTextualNode(self, subreference: CtsReference=None):
""" Special GetPassage implementation for SimplePassage (Simple is True by default)
:param subreference:
:return:
"""
if not isinstance(subreference, CtsReference):
subreference = CtsReference(subreference)
... | [
"def",
"getTextualNode",
"(",
"self",
",",
"subreference",
":",
"CtsReference",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"subreference",
",",
"CtsReference",
")",
":",
"subreference",
"=",
"CtsReference",
"(",
"subreference",
")",
"return",
"self... | Special GetPassage implementation for SimplePassage (Simple is True by default)
:param subreference:
:return: | [
"Special",
"GetPassage",
"implementation",
"for",
"SimplePassage",
"(",
"Simple",
"is",
"True",
"by",
"default",
")"
] | python | train | 41.111111 |
Ex-Mente/auxi.0 | auxi/modelling/financial/des.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/financial/des.py#L415-L429 | def balance_sheet(self, end=datetime.max,
format=ReportFormat.printout, output_path=None):
"""
Generate a transaction list report.
:param end: The end date to generate the report for.
:param format: The format of the report.
:param output_path: The path to ... | [
"def",
"balance_sheet",
"(",
"self",
",",
"end",
"=",
"datetime",
".",
"max",
",",
"format",
"=",
"ReportFormat",
".",
"printout",
",",
"output_path",
"=",
"None",
")",
":",
"rpt",
"=",
"BalanceSheet",
"(",
"self",
",",
"end",
",",
"output_path",
")",
... | Generate a transaction list report.
:param end: The end date to generate the report for.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the report is not written to a file.
:returns: The generated repo... | [
"Generate",
"a",
"transaction",
"list",
"report",
"."
] | python | valid | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.