repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
shoebot/shoebot | shoebot/data/img.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/img.py#L135-L140 | def _get_center(self):
'''Returns the center point of the path, disregarding transforms.
'''
x = (self.x + self.width / 2)
y = (self.y + self.height / 2)
return (x, y) | [
"def",
"_get_center",
"(",
"self",
")",
":",
"x",
"=",
"(",
"self",
".",
"x",
"+",
"self",
".",
"width",
"/",
"2",
")",
"y",
"=",
"(",
"self",
".",
"y",
"+",
"self",
".",
"height",
"/",
"2",
")",
"return",
"(",
"x",
",",
"y",
")"
] | Returns the center point of the path, disregarding transforms. | [
"Returns",
"the",
"center",
"point",
"of",
"the",
"path",
"disregarding",
"transforms",
"."
] | python | valid |
davisd50/sparc.common | sparc/common/cli.py | https://github.com/davisd50/sparc.common/blob/50fb47ff6f42042c363f27bd13cb3919a560e235/sparc/common/cli.py#L15-L70 | def askQuestion(question, required = True, answers = dict(), tries = 3):
"""Ask a question to STDOUT and return answer from STDIN
Args:
question: A string question that will be printed to stdout
Kwargs:
required: True indicates the question must be answered
answers: A seque... | [
"def",
"askQuestion",
"(",
"question",
",",
"required",
"=",
"True",
",",
"answers",
"=",
"dict",
"(",
")",
",",
"tries",
"=",
"3",
")",
":",
"print",
"question",
"if",
"not",
"answers",
":",
"# we get the user's answer via a named utility because direct calls to"... | Ask a question to STDOUT and return answer from STDIN
Args:
question: A string question that will be printed to stdout
Kwargs:
required: True indicates the question must be answered
answers: A sequence of dicts with key value pairs where the key will
be a user-selec... | [
"Ask",
"a",
"question",
"to",
"STDOUT",
"and",
"return",
"answer",
"from",
"STDIN",
"Args",
":",
"question",
":",
"A",
"string",
"question",
"that",
"will",
"be",
"printed",
"to",
"stdout",
"Kwargs",
":",
"required",
":",
"True",
"indicates",
"the",
"quest... | python | test |
genialis/resolwe | resolwe/flow/executors/manager_commands.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/manager_commands.py#L44-L90 | async def send_manager_command(cmd, expect_reply=True, extra_fields={}):
"""Send a properly formatted command to the manager.
:param cmd: The command to send (:class:`str`).
:param expect_reply: If ``True``, wait for the manager to reply
with an acknowledgement packet.
:param extra_fields: A di... | [
"async",
"def",
"send_manager_command",
"(",
"cmd",
",",
"expect_reply",
"=",
"True",
",",
"extra_fields",
"=",
"{",
"}",
")",
":",
"packet",
"=",
"{",
"ExecutorProtocol",
".",
"DATA_ID",
":",
"DATA",
"[",
"'id'",
"]",
",",
"ExecutorProtocol",
".",
"COMMAN... | Send a properly formatted command to the manager.
:param cmd: The command to send (:class:`str`).
:param expect_reply: If ``True``, wait for the manager to reply
with an acknowledgement packet.
:param extra_fields: A dictionary of extra information that's
merged into the packet body (i.e. n... | [
"Send",
"a",
"properly",
"formatted",
"command",
"to",
"the",
"manager",
"."
] | python | train |
wbond/oscrypto | oscrypto/keys.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/keys.py#L613-L691 | def _decrypt_encrypted_data(encryption_algorithm_info, encrypted_content, password):
"""
Decrypts encrypted ASN.1 data
:param encryption_algorithm_info:
An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm
:param encrypted_content:
A byte string of the encrypted content
:param... | [
"def",
"_decrypt_encrypted_data",
"(",
"encryption_algorithm_info",
",",
"encrypted_content",
",",
"password",
")",
":",
"decrypt_func",
"=",
"crypto_funcs",
"[",
"encryption_algorithm_info",
".",
"encryption_cipher",
"]",
"# Modern, PKCS#5 PBES2-based encryption",
"if",
"enc... | Decrypts encrypted ASN.1 data
:param encryption_algorithm_info:
An instance of asn1crypto.pkcs5.Pkcs5EncryptionAlgorithm
:param encrypted_content:
A byte string of the encrypted content
:param password:
A byte string of the encrypted content's password
:return:
A byte... | [
"Decrypts",
"encrypted",
"ASN",
".",
"1",
"data"
] | python | valid |
honeybadger-io/honeybadger-python | honeybadger/contrib/flask.py | https://github.com/honeybadger-io/honeybadger-python/blob/81519b40d3e446b62035f64e34900e08ff91938c/honeybadger/contrib/flask.py#L98-L127 | def init_app(self, app, report_exceptions=False, reset_context_after_request=False):
"""
Initialize honeybadger and listen for errors.
:param Flask app: the Flask application object.
:param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"report_exceptions",
"=",
"False",
",",
"reset_context_after_request",
"=",
"False",
")",
":",
"from",
"flask",
"import",
"request_tearing_down",
",",
"got_request_exception",
"self",
".",
"app",
"=",
"app",
"self... | Initialize honeybadger and listen for errors.
:param Flask app: the Flask application object.
:param bool report_exceptions: whether to automatically report exceptions raised by Flask on requests
(i.e. by calling abort) or not.
:param bool reset_context_after_request: whether to reset ... | [
"Initialize",
"honeybadger",
"and",
"listen",
"for",
"errors",
".",
":",
"param",
"Flask",
"app",
":",
"the",
"Flask",
"application",
"object",
".",
":",
"param",
"bool",
"report_exceptions",
":",
"whether",
"to",
"automatically",
"report",
"exceptions",
"raised... | python | train |
ansible/molecule | molecule/command/init/role.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/command/init/role.py#L133-L160 | def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, verifier_name, template): # pragma: no cover
""" Initialize a new role for use with Molecule. """
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
'lint_name': li... | [
"def",
"role",
"(",
"ctx",
",",
"dependency_name",
",",
"driver_name",
",",
"lint_name",
",",
"provisioner_name",
",",
"role_name",
",",
"verifier_name",
",",
"template",
")",
":",
"# pragma: no cover",
"command_args",
"=",
"{",
"'dependency_name'",
":",
"dependen... | Initialize a new role for use with Molecule. | [
"Initialize",
"a",
"new",
"role",
"for",
"use",
"with",
"Molecule",
"."
] | python | train |
saltstack/salt | salt/proxy/onyx.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L87-L107 | def init(opts=None):
'''
Required.
Can be used to initialize the server connection.
'''
if opts is None:
opts = __opts__
try:
DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts... | [
"def",
"init",
"(",
"opts",
"=",
"None",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"__opts__",
"try",
":",
"DETAILS",
"[",
"_worker_name",
"(",
")",
"]",
"=",
"SSHConnection",
"(",
"host",
"=",
"opts",
"[",
"'proxy'",
"]",
"[",
"'host... | Required.
Can be used to initialize the server connection. | [
"Required",
".",
"Can",
"be",
"used",
"to",
"initialize",
"the",
"server",
"connection",
"."
] | python | train |
proversity-org/bibblio-api-python | bibbliothon/discovery.py | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/discovery.py#L14-L30 | def content_recommendations(access_token, content_item_id):
'''
Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
recommendations_url =\
construct_content_recommendations_url(enrichment_url, content_item_id... | [
"def",
"content_recommendations",
"(",
"access_token",
",",
"content_item_id",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"recommendations_url",
"=",
"construct_content_recommendations_url",
"(",
"enr... | Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary | [
"Name",
":",
"content_recommendations",
"Parameters",
":",
"access_token",
"content_item_id",
"Return",
":",
"dictionary"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/phase_diagram.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/phase_diagram.py#L624-L653 | def get_transition_chempots(self, element):
"""
Get the critical chemical potentials for an element in the Phase
Diagram.
Args:
element: An element. Has to be in the PD in the first place.
Returns:
A sorted sequence of critical chemical potentials, from ... | [
"def",
"get_transition_chempots",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
"not",
"in",
"self",
".",
"elements",
":",
"raise",
"ValueError",
"(",
"\"get_transition_chempots can only be called with \"",
"\"elements in the phase diagram.\"",
")",
"critical_ch... | Get the critical chemical potentials for an element in the Phase
Diagram.
Args:
element: An element. Has to be in the PD in the first place.
Returns:
A sorted sequence of critical chemical potentials, from less
negative to more negative. | [
"Get",
"the",
"critical",
"chemical",
"potentials",
"for",
"an",
"element",
"in",
"the",
"Phase",
"Diagram",
"."
] | python | train |
jopohl/urh | src/urh/plugins/PluginManager.py | https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/plugins/PluginManager.py#L18-L38 | def load_installed_plugins(self):
""" :rtype: list of Plugin """
result = []
plugin_dirs = [d for d in os.listdir(self.plugin_path) if os.path.isdir(os.path.join(self.plugin_path, d))]
settings = constants.SETTINGS
for d in plugin_dirs:
if d == "__pycache__":
... | [
"def",
"load_installed_plugins",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"plugin_dirs",
"=",
"[",
"d",
"for",
"d",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"plugin_path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"pat... | :rtype: list of Plugin | [
":",
"rtype",
":",
"list",
"of",
"Plugin"
] | python | train |
buckhx/QuadKey | quadkey/__init__.py | https://github.com/buckhx/QuadKey/blob/546338f9b50b578ea765d3bf84b944db48dbec5b/quadkey/__init__.py#L33-L41 | def is_ancestor(self, node):
"""
If node is ancestor of self
Get the difference in level
If not, None
"""
if self.level <= node.level or self.key[:len(node.key)] != node.key:
return None
return self.level - node.level | [
"def",
"is_ancestor",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"level",
"<=",
"node",
".",
"level",
"or",
"self",
".",
"key",
"[",
":",
"len",
"(",
"node",
".",
"key",
")",
"]",
"!=",
"node",
".",
"key",
":",
"return",
"None",
"re... | If node is ancestor of self
Get the difference in level
If not, None | [
"If",
"node",
"is",
"ancestor",
"of",
"self",
"Get",
"the",
"difference",
"in",
"level",
"If",
"not",
"None"
] | python | train |
fhamborg/news-please | newsplease/helper_classes/url_extractor.py | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L31-L42 | def get_allowed_domain(url, allow_subdomains=True):
"""
Determines the url's domain.
:param str url: the url to extract the allowed domain from
:param bool allow_subdomains: determines wether to include subdomains
:return str: subdomains.domain.topleveldomain or domain.topleveld... | [
"def",
"get_allowed_domain",
"(",
"url",
",",
"allow_subdomains",
"=",
"True",
")",
":",
"if",
"allow_subdomains",
":",
"return",
"re",
".",
"sub",
"(",
"re_www",
",",
"''",
",",
"re",
".",
"search",
"(",
"r'[^/]+\\.[^/]+'",
",",
"url",
")",
".",
"group"... | Determines the url's domain.
:param str url: the url to extract the allowed domain from
:param bool allow_subdomains: determines wether to include subdomains
:return str: subdomains.domain.topleveldomain or domain.topleveldomain | [
"Determines",
"the",
"url",
"s",
"domain",
"."
] | python | train |
alvinwan/TexSoup | TexSoup/data.py | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/data.py#L386-L411 | def delete(self):
r"""Delete this node from the parse tree.
Where applicable, this will remove all descendants of this node from
the parse tree.
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''\textit{\color{blue}{Silly}}\textit{keep me!}''')
>>> soup.textit.colo... | [
"def",
"delete",
"(",
"self",
")",
":",
"# TODO: needs better abstraction for supports contents",
"parent",
"=",
"self",
".",
"parent",
"if",
"parent",
".",
"expr",
".",
"_supports_contents",
"(",
")",
":",
"parent",
".",
"remove",
"(",
"self",
")",
"return",
... | r"""Delete this node from the parse tree.
Where applicable, this will remove all descendants of this node from
the parse tree.
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''\textit{\color{blue}{Silly}}\textit{keep me!}''')
>>> soup.textit.color.delete()
>>> sou... | [
"r",
"Delete",
"this",
"node",
"from",
"the",
"parse",
"tree",
"."
] | python | train |
twilio/twilio-python | twilio/rest/sync/v1/service/sync_list/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_list/__init__.py#L102-L123 | def page(self, page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of SyncListInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_numbe... | [
"def",
"page",
"(",
"self",
",",
"page_token",
"=",
"values",
".",
"unset",
",",
"page_number",
"=",
"values",
".",
"unset",
",",
"page_size",
"=",
"values",
".",
"unset",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"'PageToken'",
":",
"p... | Retrieve a single page of SyncListInstance records from the API.
Request is executed immediately
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to... | [
"Retrieve",
"a",
"single",
"page",
"of",
"SyncListInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | python | train |
briwilcox/Concurrent-Pandas | concurrentpandas.py | https://github.com/briwilcox/Concurrent-Pandas/blob/22cb392dacb712e1bdb5b60c6ba7015c38445c99/concurrentpandas.py#L259-L266 | def set_source_google_finance(self):
"""
Set data source to Google Finance
"""
self.data_worker = data_worker
self.worker_args = {"function": pandas.io.data.DataReader, "input": self.input_queue, "output": self.output_map,
"source": 'google'}
s... | [
"def",
"set_source_google_finance",
"(",
"self",
")",
":",
"self",
".",
"data_worker",
"=",
"data_worker",
"self",
".",
"worker_args",
"=",
"{",
"\"function\"",
":",
"pandas",
".",
"io",
".",
"data",
".",
"DataReader",
",",
"\"input\"",
":",
"self",
".",
"... | Set data source to Google Finance | [
"Set",
"data",
"source",
"to",
"Google",
"Finance"
] | python | train |
librosa/librosa | examples/estimate_tuning.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/estimate_tuning.py#L15-L28 | def estimate_tuning(input_file):
'''Load an audio file and estimate tuning (in cents)'''
print('Loading ', input_file)
y, sr = librosa.load(input_file)
print('Separating harmonic component ... ')
y_harm = librosa.effects.harmonic(y)
print('Estimating tuning ... ')
# Just track the pitches... | [
"def",
"estimate_tuning",
"(",
"input_file",
")",
":",
"print",
"(",
"'Loading '",
",",
"input_file",
")",
"y",
",",
"sr",
"=",
"librosa",
".",
"load",
"(",
"input_file",
")",
"print",
"(",
"'Separating harmonic component ... '",
")",
"y_harm",
"=",
"librosa",... | Load an audio file and estimate tuning (in cents) | [
"Load",
"an",
"audio",
"file",
"and",
"estimate",
"tuning",
"(",
"in",
"cents",
")"
] | python | test |
RudolfCardinal/pythonlib | cardinal_pythonlib/timing.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L81-L106 | def start(self, name: str, increment_count: bool = True) -> None:
"""
Start a named timer.
Args:
name: name of the timer
increment_count: increment the start count for this timer
"""
if not self._timing:
return
now = get_now_utc_pendu... | [
"def",
"start",
"(",
"self",
",",
"name",
":",
"str",
",",
"increment_count",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_timing",
":",
"return",
"now",
"=",
"get_now_utc_pendulum",
"(",
")",
"# If we were already timing s... | Start a named timer.
Args:
name: name of the timer
increment_count: increment the start count for this timer | [
"Start",
"a",
"named",
"timer",
"."
] | python | train |
sernst/cauldron | cauldron/session/reloading.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L96-L143 | def reload_module(
module: typing.Union[str, types.ModuleType],
recursive: bool,
force: bool
) -> bool:
"""
Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
... | [
"def",
"reload_module",
"(",
"module",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"types",
".",
"ModuleType",
"]",
",",
"recursive",
":",
"bool",
",",
"force",
":",
"bool",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"module",
",",
"str",
")"... | Reloads the specified module, which can either be a module object or
a string name of a module. Will not reload a module that has not been
imported
:param module:
A module object or string module name that should be refreshed if its
currently loaded version is out of date or the action is f... | [
"Reloads",
"the",
"specified",
"module",
"which",
"can",
"either",
"be",
"a",
"module",
"object",
"or",
"a",
"string",
"name",
"of",
"a",
"module",
".",
"Will",
"not",
"reload",
"a",
"module",
"that",
"has",
"not",
"been",
"imported"
] | python | train |
saltant-org/saltant-py | saltant/models/resource.py | https://github.com/saltant-org/saltant-py/blob/bf3bdbc4ec9c772c7f621f8bd6a76c5932af68be/saltant/models/resource.py#L131-L157 | def get(self, id):
"""Get the model instance with a given id.
Args:
id (int or str): The primary identifier (e.g., pk or UUID)
for the task instance to get.
Returns:
:class:`saltant.models.resource.Model`:
A :class:`saltant.models.resourc... | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"# Get the object",
"request_url",
"=",
"self",
".",
"_client",
".",
"base_api_url",
"+",
"self",
".",
"detail_url",
".",
"format",
"(",
"id",
"=",
"id",
")",
"response",
"=",
"self",
".",
"_client",
".",... | Get the model instance with a given id.
Args:
id (int or str): The primary identifier (e.g., pk or UUID)
for the task instance to get.
Returns:
:class:`saltant.models.resource.Model`:
A :class:`saltant.models.resource.Model` subclass
... | [
"Get",
"the",
"model",
"instance",
"with",
"a",
"given",
"id",
"."
] | python | train |
iterative/dvc | dvc/utils/compat.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L68-L90 | def _makedirs(name, mode=0o777, exist_ok=False):
"""Source: https://github.com/python/cpython/blob/
3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
"""
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(... | [
"def",
"_makedirs",
"(",
"name",
",",
"mode",
"=",
"0o777",
",",
"exist_ok",
"=",
"False",
")",
":",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"name",
")",
"if",
"not",
"tail",
":",
"head",
",",
"tail",
"=",
"os",
".",
"pa... | Source: https://github.com/python/cpython/blob/
3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 | [
"Source",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"python",
"/",
"cpython",
"/",
"blob",
"/",
"3ce3dea60646d8a5a1c952469a2eb65f937875b3",
"/",
"Lib",
"/",
"os",
".",
"py#L196",
"-",
"L226"
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/teal.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/teal.py#L232-L237 | def load(theTask, canExecute=True, strict=True, defaults=False):
""" Shortcut to load TEAL .cfg files for non-GUI access where
loadOnly=True. """
return teal(theTask, parent=None, loadOnly=True, returnAs="dict",
canExecute=canExecute, strict=strict, errorsToTerm=True,
default... | [
"def",
"load",
"(",
"theTask",
",",
"canExecute",
"=",
"True",
",",
"strict",
"=",
"True",
",",
"defaults",
"=",
"False",
")",
":",
"return",
"teal",
"(",
"theTask",
",",
"parent",
"=",
"None",
",",
"loadOnly",
"=",
"True",
",",
"returnAs",
"=",
"\"d... | Shortcut to load TEAL .cfg files for non-GUI access where
loadOnly=True. | [
"Shortcut",
"to",
"load",
"TEAL",
".",
"cfg",
"files",
"for",
"non",
"-",
"GUI",
"access",
"where",
"loadOnly",
"=",
"True",
"."
] | python | train |
stephen-bunn/file-config | src/file_config/handlers/msgpack.py | https://github.com/stephen-bunn/file-config/blob/93429360c949985202e1f2b9cd0340731819ba75/src/file_config/handlers/msgpack.py#L27-L37 | def on_msgpack_loads(self, msgpack, config, content, **kwargs):
""" The `msgpack <https://pypi.org/project/msgpack/>`_ loads method.
:param module msgpack: The ``msgpack`` module
:param class config: The loading config class
:param dict content: The serialized content to deserialize
... | [
"def",
"on_msgpack_loads",
"(",
"self",
",",
"msgpack",
",",
"config",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"msgpack",
".",
"loads",
"(",
"content",
",",
"raw",
"=",
"False",
")"
] | The `msgpack <https://pypi.org/project/msgpack/>`_ loads method.
:param module msgpack: The ``msgpack`` module
:param class config: The loading config class
:param dict content: The serialized content to deserialize
:returns: The deserialized dictionary
:rtype: dict | [
"The",
"msgpack",
"<https",
":",
"//",
"pypi",
".",
"org",
"/",
"project",
"/",
"msgpack",
"/",
">",
"_",
"loads",
"method",
"."
] | python | train |
geertj/gruvi | vendor/txdbus/marshal.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/vendor/txdbus/marshal.py#L783-L815 | def unmarshal( compoundSignature, data, offset = 0, lendian = True ):
"""
Unmarshals DBus encoded data.
@type compoundSignature: C{string}
@param compoundSignature: DBus signature specifying the encoded value types
@type data: C{string}
@param data: Binary data
@type offset: C{int}
@p... | [
"def",
"unmarshal",
"(",
"compoundSignature",
",",
"data",
",",
"offset",
"=",
"0",
",",
"lendian",
"=",
"True",
")",
":",
"values",
"=",
"list",
"(",
")",
"start_offset",
"=",
"offset",
"for",
"ct",
"in",
"genCompleteTypes",
"(",
"compoundSignature",
")",... | Unmarshals DBus encoded data.
@type compoundSignature: C{string}
@param compoundSignature: DBus signature specifying the encoded value types
@type data: C{string}
@param data: Binary data
@type offset: C{int}
@param offset: Offset within data at which data for compoundSignature
... | [
"Unmarshals",
"DBus",
"encoded",
"data",
"."
] | python | train |
funilrys/PyFunceble | PyFunceble/mining.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/mining.py#L243-L252 | def _backup(self):
"""
Backup the mined informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We backup our mined informations.
Dict(PyFunceble.INTERN["mined"]).to_json(self.file) | [
"def",
"_backup",
"(",
"self",
")",
":",
"if",
"PyFunceble",
".",
"CONFIGURATION",
"[",
"\"mining\"",
"]",
":",
"# The mining is activated.",
"# We backup our mined informations.",
"Dict",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"mined\"",
"]",
")",
".",
"to_json... | Backup the mined informations. | [
"Backup",
"the",
"mined",
"informations",
"."
] | python | test |
EnigmaBridge/client.py | ebclient/eb_registration.py | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_registration.py#L62-L92 | def call(self, client_data=None, api_data=None, aux_data=None, *args, **kwargs):
"""
Calls the request with input data using given configuration (retry, timeout, ...).
:param client_data:
:param api_data:
:param aux_data:
:param args:
:param kwargs:
:retur... | [
"def",
"call",
"(",
"self",
",",
"client_data",
"=",
"None",
",",
"api_data",
"=",
"None",
",",
"aux_data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"build_request",
"(",
"client_data",
"=",
"client_data",
",",
"... | Calls the request with input data using given configuration (retry, timeout, ...).
:param client_data:
:param api_data:
:param aux_data:
:param args:
:param kwargs:
:return: | [
"Calls",
"the",
"request",
"with",
"input",
"data",
"using",
"given",
"configuration",
"(",
"retry",
"timeout",
"...",
")",
".",
":",
"param",
"client_data",
":",
":",
"param",
"api_data",
":",
":",
"param",
"aux_data",
":",
":",
"param",
"args",
":",
":... | python | train |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/servicebusmanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicebusmanagementservice.py#L284-L303 | def get_supported_metrics_notification_hub(self, name, hub_name):
'''
Retrieves the list of supported metrics for this namespace and topic
name:
Name of the service bus namespace.
hub_name:
Name of the service bus notification hub in this namespace.
'''
... | [
"def",
"get_supported_metrics_notification_hub",
"(",
"self",
",",
"name",
",",
"hub_name",
")",
":",
"response",
"=",
"self",
".",
"_perform_get",
"(",
"self",
".",
"_get_get_supported_metrics_hub_path",
"(",
"name",
",",
"hub_name",
")",
",",
"None",
")",
"ret... | Retrieves the list of supported metrics for this namespace and topic
name:
Name of the service bus namespace.
hub_name:
Name of the service bus notification hub in this namespace. | [
"Retrieves",
"the",
"list",
"of",
"supported",
"metrics",
"for",
"this",
"namespace",
"and",
"topic"
] | python | test |
pvlib/pvlib-python | pvlib/iotools/midc.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/iotools/midc.py#L30-L64 | def map_midc_to_pvlib(variable_map, field_name):
"""A mapper function to rename Dataframe columns to their pvlib counterparts.
Parameters
----------
variable_map: Dictionary
A dictionary for mapping MIDC field name to pvlib name. See
VARIABLE_MAP for default value and description of how... | [
"def",
"map_midc_to_pvlib",
"(",
"variable_map",
",",
"field_name",
")",
":",
"new_field_name",
"=",
"field_name",
"for",
"midc_name",
",",
"pvlib_name",
"in",
"variable_map",
".",
"items",
"(",
")",
":",
"if",
"field_name",
".",
"startswith",
"(",
"midc_name",
... | A mapper function to rename Dataframe columns to their pvlib counterparts.
Parameters
----------
variable_map: Dictionary
A dictionary for mapping MIDC field name to pvlib name. See
VARIABLE_MAP for default value and description of how to construct
this argument.
field_name: str... | [
"A",
"mapper",
"function",
"to",
"rename",
"Dataframe",
"columns",
"to",
"their",
"pvlib",
"counterparts",
"."
] | python | train |
a1ezzz/wasp-general | wasp_general/network/clients/virtual_dir.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L105-L111 | def full_path(self):
""" Return a full path to a current session directory. A result is made by joining a start path with
current session directory
:return: str
"""
return self.normalize_path(self.directory_sep().join((self.start_path(), self.session_path()))) | [
"def",
"full_path",
"(",
"self",
")",
":",
"return",
"self",
".",
"normalize_path",
"(",
"self",
".",
"directory_sep",
"(",
")",
".",
"join",
"(",
"(",
"self",
".",
"start_path",
"(",
")",
",",
"self",
".",
"session_path",
"(",
")",
")",
")",
")"
] | Return a full path to a current session directory. A result is made by joining a start path with
current session directory
:return: str | [
"Return",
"a",
"full",
"path",
"to",
"a",
"current",
"session",
"directory",
".",
"A",
"result",
"is",
"made",
"by",
"joining",
"a",
"start",
"path",
"with",
"current",
"session",
"directory"
] | python | train |
koalalorenzo/python-digitalocean | digitalocean/Volume.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Volume.py#L21-L27 | def get_object(cls, api_token, volume_id):
"""
Class method that will return an Volume object by ID.
"""
volume = cls(token=api_token, id=volume_id)
volume.load()
return volume | [
"def",
"get_object",
"(",
"cls",
",",
"api_token",
",",
"volume_id",
")",
":",
"volume",
"=",
"cls",
"(",
"token",
"=",
"api_token",
",",
"id",
"=",
"volume_id",
")",
"volume",
".",
"load",
"(",
")",
"return",
"volume"
] | Class method that will return an Volume object by ID. | [
"Class",
"method",
"that",
"will",
"return",
"an",
"Volume",
"object",
"by",
"ID",
"."
] | python | valid |
aio-libs/aiohttp | aiohttp/web_middlewares.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_middlewares.py#L42-L111 | def normalize_path_middleware(
*, append_slash: bool=True, remove_slash: bool=False,
merge_slashes: bool=True,
redirect_class: Type[HTTPMove]=HTTPMovedPermanently) -> _Middleware:
"""
Middleware factory which produces a middleware that normalizes
the path of a request. By normalizing... | [
"def",
"normalize_path_middleware",
"(",
"*",
",",
"append_slash",
":",
"bool",
"=",
"True",
",",
"remove_slash",
":",
"bool",
"=",
"False",
",",
"merge_slashes",
":",
"bool",
"=",
"True",
",",
"redirect_class",
":",
"Type",
"[",
"HTTPMove",
"]",
"=",
"HTT... | Middleware factory which produces a middleware that normalizes
the path of a request. By normalizing it means:
- Add or remove a trailing slash to the path.
- Double slashes are replaced by one.
The middleware returns as soon as it finds a path that resolves
correctly. The order if both me... | [
"Middleware",
"factory",
"which",
"produces",
"a",
"middleware",
"that",
"normalizes",
"the",
"path",
"of",
"a",
"request",
".",
"By",
"normalizing",
"it",
"means",
":"
] | python | train |
TimBest/django-multi-form-view | multi_form_view/base.py | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L15-L22 | def are_forms_valid(self, forms):
"""
Check if all forms defined in `form_classes` are valid.
"""
for form in six.itervalues(forms):
if not form.is_valid():
return False
return True | [
"def",
"are_forms_valid",
"(",
"self",
",",
"forms",
")",
":",
"for",
"form",
"in",
"six",
".",
"itervalues",
"(",
"forms",
")",
":",
"if",
"not",
"form",
".",
"is_valid",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Check if all forms defined in `form_classes` are valid. | [
"Check",
"if",
"all",
"forms",
"defined",
"in",
"form_classes",
"are",
"valid",
"."
] | python | train |
F5Networks/f5-common-python | f5/bigip/resource.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/resource.py#L475-L504 | def _check_keys(self, rdict):
"""Call this from _local_update to validate response keys
disallowed server-response json keys:
1. The string-literal '_meta_data'
2. strings that are not valid Python 2.7 identifiers
3. strings beginning with '__'.
:param rdict: from respo... | [
"def",
"_check_keys",
"(",
"self",
",",
"rdict",
")",
":",
"if",
"'_meta_data'",
"in",
"rdict",
":",
"error_message",
"=",
"\"Response contains key '_meta_data' which is \"",
"\"incompatible with this API!!\\n Response json: %r\"",
"%",
"rdict",
"raise",
"DeviceProvidesIncomp... | Call this from _local_update to validate response keys
disallowed server-response json keys:
1. The string-literal '_meta_data'
2. strings that are not valid Python 2.7 identifiers
3. strings beginning with '__'.
:param rdict: from response.json()
:raises: DeviceProvide... | [
"Call",
"this",
"from",
"_local_update",
"to",
"validate",
"response",
"keys"
] | python | train |
albahnsen/CostSensitiveClassification | costcla/datasets/base.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L336-L415 | def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters):
""" Private function to calculate the cost matrix of credit scoring models.
Parameters
----------
income : array of shape = [n_samples]
Monthly income of each example
debt : array of shape = [n_samples]
Debt ratio... | [
"def",
"_creditscoring_costmat",
"(",
"income",
",",
"debt",
",",
"pi_1",
",",
"cost_mat_parameters",
")",
":",
"def",
"calculate_a",
"(",
"cl_i",
",",
"int_",
",",
"n_term",
")",
":",
"\"\"\" Private function \"\"\"",
"return",
"cl_i",
"*",
"(",
"(",
"int_",
... | Private function to calculate the cost matrix of credit scoring models.
Parameters
----------
income : array of shape = [n_samples]
Monthly income of each example
debt : array of shape = [n_samples]
Debt ratio each example
pi_1 : float
Percentage of positives in the traini... | [
"Private",
"function",
"to",
"calculate",
"the",
"cost",
"matrix",
"of",
"credit",
"scoring",
"models",
"."
] | python | train |
saltstack/salt | salt/crypt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L1428-L1464 | def decrypt(self, data):
'''
verify HMAC-SHA256 signature and decrypt data with AES-CBC
'''
aes_key, hmac_key = self.keys
sig = data[-self.SIG_SIZE:]
data = data[:-self.SIG_SIZE]
if six.PY3 and not isinstance(data, bytes):
data = salt.utils.stringutils... | [
"def",
"decrypt",
"(",
"self",
",",
"data",
")",
":",
"aes_key",
",",
"hmac_key",
"=",
"self",
".",
"keys",
"sig",
"=",
"data",
"[",
"-",
"self",
".",
"SIG_SIZE",
":",
"]",
"data",
"=",
"data",
"[",
":",
"-",
"self",
".",
"SIG_SIZE",
"]",
"if",
... | verify HMAC-SHA256 signature and decrypt data with AES-CBC | [
"verify",
"HMAC",
"-",
"SHA256",
"signature",
"and",
"decrypt",
"data",
"with",
"AES",
"-",
"CBC"
] | python | train |
jay-johnson/spylunking | spylunking/send_to_splunk.py | https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/send_to_splunk.py#L3-L33 | def send_to_splunk(
session=None,
url=None,
data=None,
headers=None,
verify=False,
ssl_options=None,
timeout=10.0):
"""send_to_splunk
Send formatted msgs to Splunk. This will throw exceptions
for any errors. It is decoupled from the publishers to
... | [
"def",
"send_to_splunk",
"(",
"session",
"=",
"None",
",",
"url",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"ssl_options",
"=",
"None",
",",
"timeout",
"=",
"10.0",
")",
":",
"r",
"=",
"se... | send_to_splunk
Send formatted msgs to Splunk. This will throw exceptions
for any errors. It is decoupled from the publishers to
make testing easier with mocks.
:param session: requests.Session
:param url: url for splunk logs
:param data: data to send
:param headers: headers for splunk
... | [
"send_to_splunk"
] | python | train |
django-danceschool/django-danceschool | danceschool/financial/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/financial/models.py#L874-L880 | def relatedItems(self):
'''
If this item is associated with a registration, then return all other items associated with
the same registration.
'''
if self.registration:
return self.registration.revenueitem_set.exclude(pk=self.pk) | [
"def",
"relatedItems",
"(",
"self",
")",
":",
"if",
"self",
".",
"registration",
":",
"return",
"self",
".",
"registration",
".",
"revenueitem_set",
".",
"exclude",
"(",
"pk",
"=",
"self",
".",
"pk",
")"
] | If this item is associated with a registration, then return all other items associated with
the same registration. | [
"If",
"this",
"item",
"is",
"associated",
"with",
"a",
"registration",
"then",
"return",
"all",
"other",
"items",
"associated",
"with",
"the",
"same",
"registration",
"."
] | python | train |
jhuapl-boss/intern | intern/remote/boss/remote.py | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L127-L147 | def _init_volume_service(self, version):
"""
Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
vol... | [
"def",
"_init_volume_service",
"(",
"self",
",",
"version",
")",
":",
"volume_cfg",
"=",
"self",
".",
"_load_config_section",
"(",
"CONFIG_VOLUME_SECTION",
")",
"self",
".",
"_token_volume",
"=",
"volume_cfg",
"[",
"CONFIG_TOKEN",
"]",
"proto",
"=",
"volume_cfg",
... | Method to initialize the Volume Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version. | [
"Method",
"to",
"initialize",
"the",
"Volume",
"Service",
"from",
"the",
"config",
"data"
] | python | train |
angr/angr | angr/engines/soot/statements/base.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/engines/soot/statements/base.py#L41-L57 | def _get_bb_addr_from_instr(self, instr):
"""
Returns the address of the methods basic block that contains the given
instruction.
:param instr: The index of the instruction (within the current method).
:rtype: SootAddressDescriptor
"""
current_method = self.state... | [
"def",
"_get_bb_addr_from_instr",
"(",
"self",
",",
"instr",
")",
":",
"current_method",
"=",
"self",
".",
"state",
".",
"addr",
".",
"method",
"try",
":",
"bb",
"=",
"current_method",
".",
"block_by_label",
"[",
"instr",
"]",
"except",
"KeyError",
":",
"l... | Returns the address of the methods basic block that contains the given
instruction.
:param instr: The index of the instruction (within the current method).
:rtype: SootAddressDescriptor | [
"Returns",
"the",
"address",
"of",
"the",
"methods",
"basic",
"block",
"that",
"contains",
"the",
"given",
"instruction",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/glow_ops.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L53-L82 | def linear_interpolate_rank(tensor1, tensor2, coeffs, rank=1):
"""Linearly interpolate channel at "rank" between two tensors.
The channels are ranked according to their L2 norm between tensor1[channel]
and tensor2[channel].
Args:
tensor1: 4-D Tensor, NHWC
tensor2: 4-D Tensor, NHWC
coeffs: list of ... | [
"def",
"linear_interpolate_rank",
"(",
"tensor1",
",",
"tensor2",
",",
"coeffs",
",",
"rank",
"=",
"1",
")",
":",
"# sum across space, max across channels.",
"_",
",",
"_",
",",
"_",
",",
"num_channels",
"=",
"common_layers",
".",
"shape_list",
"(",
"tensor1",
... | Linearly interpolate channel at "rank" between two tensors.
The channels are ranked according to their L2 norm between tensor1[channel]
and tensor2[channel].
Args:
tensor1: 4-D Tensor, NHWC
tensor2: 4-D Tensor, NHWC
coeffs: list of floats.
rank: integer.
Returns:
interp_latents: list of in... | [
"Linearly",
"interpolate",
"channel",
"at",
"rank",
"between",
"two",
"tensors",
"."
] | python | train |
pyviz/holoviews | holoviews/core/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1984-L1990 | def search_indices(values, source):
"""
Given a set of values returns the indices of each of those values
in the source array.
"""
orig_indices = source.argsort()
return orig_indices[np.searchsorted(source[orig_indices], values)] | [
"def",
"search_indices",
"(",
"values",
",",
"source",
")",
":",
"orig_indices",
"=",
"source",
".",
"argsort",
"(",
")",
"return",
"orig_indices",
"[",
"np",
".",
"searchsorted",
"(",
"source",
"[",
"orig_indices",
"]",
",",
"values",
")",
"]"
] | Given a set of values returns the indices of each of those values
in the source array. | [
"Given",
"a",
"set",
"of",
"values",
"returns",
"the",
"indices",
"of",
"each",
"of",
"those",
"values",
"in",
"the",
"source",
"array",
"."
] | python | train |
DeV1doR/aioethereum | aioethereum/management/eth.py | https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/eth.py#L136-L149 | def eth_getBlockTransactionCountByHash(self, bhash):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbyhash
:param bhash: Block hash
:type bhash: str
:return: count
:rtype: int or None
"""
response = yield from self.rpc_call('eth_ge... | [
"def",
"eth_getBlockTransactionCountByHash",
"(",
"self",
",",
"bhash",
")",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"rpc_call",
"(",
"'eth_getBlockTransactionCountByHash'",
",",
"[",
"bhash",
"]",
")",
"if",
"response",
":",
"return",
"hex_to_dec",
... | https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbyhash
:param bhash: Block hash
:type bhash: str
:return: count
:rtype: int or None | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"ethereum",
"/",
"wiki",
"/",
"wiki",
"/",
"JSON",
"-",
"RPC#eth_getblocktransactioncountbyhash"
] | python | train |
openego/eTraGo | etrago/tools/plot.py | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L792-L827 | def plot_residual_load(network):
""" Plots residual load summed of all exisiting buses.
Parameters
----------
network : PyPSA network containter
"""
renewables = network.generators[
network.generators.carrier.isin(['wind_onshore', 'wind_offshore',
... | [
"def",
"plot_residual_load",
"(",
"network",
")",
":",
"renewables",
"=",
"network",
".",
"generators",
"[",
"network",
".",
"generators",
".",
"carrier",
".",
"isin",
"(",
"[",
"'wind_onshore'",
",",
"'wind_offshore'",
",",
"'solar'",
",",
"'run_of_river'",
"... | Plots residual load summed of all exisiting buses.
Parameters
----------
network : PyPSA network containter | [
"Plots",
"residual",
"load",
"summed",
"of",
"all",
"exisiting",
"buses",
"."
] | python | train |
biolink/ontobio | ontobio/assoc_factory.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/assoc_factory.py#L88-L102 | def create_from_tuples(self, tuples, **args):
"""
Creates from a list of (subj,subj_name,obj) tuples
"""
amap = {}
subject_label_map = {}
for a in tuples:
subj = a[0]
subject_label_map[subj] = a[1]
if subj not in amap:
a... | [
"def",
"create_from_tuples",
"(",
"self",
",",
"tuples",
",",
"*",
"*",
"args",
")",
":",
"amap",
"=",
"{",
"}",
"subject_label_map",
"=",
"{",
"}",
"for",
"a",
"in",
"tuples",
":",
"subj",
"=",
"a",
"[",
"0",
"]",
"subject_label_map",
"[",
"subj",
... | Creates from a list of (subj,subj_name,obj) tuples | [
"Creates",
"from",
"a",
"list",
"of",
"(",
"subj",
"subj_name",
"obj",
")",
"tuples"
] | python | train |
alexras/pylsdj | pylsdj/filepack.py | https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L141-L201 | def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
... | [
"def",
"renumber_block_keys",
"(",
"blocks",
")",
":",
"# There is an implicit block switch to the 0th block at the start of the",
"# file",
"byte_switch_keys",
"=",
"[",
"0",
"]",
"block_keys",
"=",
"list",
"(",
"blocks",
".",
"keys",
"(",
")",
")",
"# Scan the blocks,... | Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map | [
"Renumber",
"a",
"block",
"map",
"s",
"indices",
"so",
"that",
"tehy",
"match",
"the",
"blocks",
"block",
"switch",
"statements",
"."
] | python | train |
LonamiWebs/Telethon | telethon/tl/custom/message.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/message.py#L686-L701 | async def delete(self, *args, **kwargs):
"""
Deletes the message. You're responsible for checking whether you
have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``mess... | [
"async",
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_client",
".",
"delete_messages",
"(",
"await",
"self",
".",
"get_input_chat",
"(",
")",
",",
"[",
"self",
".",
"id",
"]",
... | Deletes the message. You're responsible for checking whether you
have the permission to do so, or to except the error otherwise.
Shorthand for
`telethon.client.messages.MessageMethods.delete_messages` with
``entity`` and ``message_ids`` already set.
If you need to delete more th... | [
"Deletes",
"the",
"message",
".",
"You",
"re",
"responsible",
"for",
"checking",
"whether",
"you",
"have",
"the",
"permission",
"to",
"do",
"so",
"or",
"to",
"except",
"the",
"error",
"otherwise",
".",
"Shorthand",
"for",
"telethon",
".",
"client",
".",
"m... | python | train |
spyder-ide/spyder | spyder/preferences/appearance.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/appearance.py#L334-L377 | def create_new_scheme(self):
"""Creates a new color scheme with a custom name."""
names = self.get_option('names')
custom_names = self.get_option('custom_names', [])
# Get the available number this new color scheme
counter = len(custom_names) - 1
custom_index = [int(n.sp... | [
"def",
"create_new_scheme",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"get_option",
"(",
"'names'",
")",
"custom_names",
"=",
"self",
".",
"get_option",
"(",
"'custom_names'",
",",
"[",
"]",
")",
"# Get the available number this new color scheme",
"counter... | Creates a new color scheme with a custom name. | [
"Creates",
"a",
"new",
"color",
"scheme",
"with",
"a",
"custom",
"name",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L1092-L1098 | def record_add_types(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /record-xxxx/addTypes API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FaddTypes
"""
return DXHTTPRequest('/%s/addTypes' % object_id, i... | [
"def",
"record_add_types",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/addTypes'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",
... | Invokes the /record-xxxx/addTypes API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FaddTypes | [
"Invokes",
"the",
"/",
"record",
"-",
"xxxx",
"/",
"addTypes",
"API",
"method",
"."
] | python | train |
dschreij/python-mediadecoder | mediadecoder/soundrenderers/_base.py | https://github.com/dschreij/python-mediadecoder/blob/f01b02d790f2abc52d9792e43076cf4cb7d3ce51/mediadecoder/soundrenderers/_base.py#L22-L32 | def queue(self, value):
""" Sets the audioqueue.
Parameters
----------
value : queue.Queue
The buffer from which audioframes are received.
"""
if not isinstance(value, Queue):
raise TypeError("queue is not a Queue object")
self._queue = value | [
"def",
"queue",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Queue",
")",
":",
"raise",
"TypeError",
"(",
"\"queue is not a Queue object\"",
")",
"self",
".",
"_queue",
"=",
"value"
] | Sets the audioqueue.
Parameters
----------
value : queue.Queue
The buffer from which audioframes are received. | [
"Sets",
"the",
"audioqueue",
"."
] | python | train |
scoutapp/scout_apm_python | src/scout_apm/core/socket.py | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/core/socket.py#L95-L132 | def run(self):
"""
Called by the threading system
"""
try:
self._connect()
self._register()
while True:
try:
body = self.command_queue.get(block=True, timeout=1 * SECOND)
except queue.Empty:
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_register",
"(",
")",
"while",
"True",
":",
"try",
":",
"body",
"=",
"self",
".",
"command_queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"time... | Called by the threading system | [
"Called",
"by",
"the",
"threading",
"system"
] | python | train |
catherinedevlin/ddl-generator | ddlgenerator/typehelpers.py | https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L122-L132 | def worst_decimal(d1, d2):
"""
Given two Decimals, return a 9-filled decimal representing both enough > 0 digits
and enough < 0 digits (scale) to accomodate numbers like either.
>>> worst_decimal(Decimal('762.1'), Decimal('-1.983'))
Decimal('999.999')
"""
(d1b4, d1after) = _places_b4_and_af... | [
"def",
"worst_decimal",
"(",
"d1",
",",
"d2",
")",
":",
"(",
"d1b4",
",",
"d1after",
")",
"=",
"_places_b4_and_after_decimal",
"(",
"d1",
")",
"(",
"d2b4",
",",
"d2after",
")",
"=",
"_places_b4_and_after_decimal",
"(",
"d2",
")",
"return",
"Decimal",
"(",
... | Given two Decimals, return a 9-filled decimal representing both enough > 0 digits
and enough < 0 digits (scale) to accomodate numbers like either.
>>> worst_decimal(Decimal('762.1'), Decimal('-1.983'))
Decimal('999.999') | [
"Given",
"two",
"Decimals",
"return",
"a",
"9",
"-",
"filled",
"decimal",
"representing",
"both",
"enough",
">",
"0",
"digits",
"and",
"enough",
"<",
"0",
"digits",
"(",
"scale",
")",
"to",
"accomodate",
"numbers",
"like",
"either",
"."
] | python | train |
googleapis/google-cloud-python | api_core/google/api_core/timeout.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/timeout.py#L110-L140 | def _exponential_timeout_generator(initial, maximum, multiplier, deadline):
"""A generator that yields exponential timeout values.
Args:
initial (float): The initial timeout.
maximum (float): The maximum timeout.
multiplier (float): The multiplier applied to the timeout.
deadlin... | [
"def",
"_exponential_timeout_generator",
"(",
"initial",
",",
"maximum",
",",
"multiplier",
",",
"deadline",
")",
":",
"if",
"deadline",
"is",
"not",
"None",
":",
"deadline_datetime",
"=",
"datetime_helpers",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"tim... | A generator that yields exponential timeout values.
Args:
initial (float): The initial timeout.
maximum (float): The maximum timeout.
multiplier (float): The multiplier applied to the timeout.
deadline (float): The overall deadline across all invocations.
Yields:
float:... | [
"A",
"generator",
"that",
"yields",
"exponential",
"timeout",
"values",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L3081-L3134 | def minimum(lhs, rhs):
"""Returns element-wise minimum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a com... | [
"def",
"minimum",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"return",
"_ufunc_helper",
"(",
"lhs",
",",
"rhs",
",",
"op",
".",
"broadcast_minimum",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"if",
"x",
"<",
"y",
"else... | Returns element-wise minimum of the input arrays with broadcasting.
Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
then the arrays are broadcastable to a common shape.
Parameters
... | [
"Returns",
"element",
"-",
"wise",
"minimum",
"of",
"the",
"input",
"arrays",
"with",
"broadcasting",
"."
] | python | train |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L1116-L1136 | def set_disk_usage(self, total_size, path=None):
"""Changes the total size of the file system, preserving the used space.
Example usage: set the size of an auto-mounted Windows drive.
Args:
total_size: The new total size of the filesystem in bytes.
path: The disk space ... | [
"def",
"set_disk_usage",
"(",
"self",
",",
"total_size",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"root",
".",
"name",
"mount_point",
"=",
"self",
".",
"_mount_point_for_path",
"(",
"path",
")",
"if... | Changes the total size of the file system, preserving the used space.
Example usage: set the size of an auto-mounted Windows drive.
Args:
total_size: The new total size of the filesystem in bytes.
path: The disk space is changed for the file system device where
... | [
"Changes",
"the",
"total",
"size",
"of",
"the",
"file",
"system",
"preserving",
"the",
"used",
"space",
".",
"Example",
"usage",
":",
"set",
"the",
"size",
"of",
"an",
"auto",
"-",
"mounted",
"Windows",
"drive",
"."
] | python | train |
serge-sans-paille/pythran | pythran/analyses/aliases.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L317-L380 | def visit_Call(self, node):
'''
Resulting node alias to the return_alias of called function,
if the function is already known by Pythran (i.e. it's an Intrinsic)
or if Pythran already computed it's ``return_alias`` behavior.
>>> from pythran import passmanager
>>> pm = p... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"f",
"=",
"node",
".",
"func",
"# special handler for bind functions",
"if",
"isinstance",
"(",
"f",
",",
"ast",
".",
"Attribute",
")",
"and",
"f",
"... | Resulting node alias to the return_alias of called function,
if the function is already known by Pythran (i.e. it's an Intrinsic)
or if Pythran already computed it's ``return_alias`` behavior.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> fun =... | [
"Resulting",
"node",
"alias",
"to",
"the",
"return_alias",
"of",
"called",
"function",
"if",
"the",
"function",
"is",
"already",
"known",
"by",
"Pythran",
"(",
"i",
".",
"e",
".",
"it",
"s",
"an",
"Intrinsic",
")",
"or",
"if",
"Pythran",
"already",
"comp... | python | train |
caseman/noise | shader_noise.py | https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/shader_noise.py#L46-L50 | def load(self):
"""Load the noise texture data into the current texture unit"""
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_SHORT, ctypes.byref(self.data)) | [
"def",
"load",
"(",
"self",
")",
":",
"glTexImage3D",
"(",
"GL_TEXTURE_3D",
",",
"0",
",",
"GL_LUMINANCE16_ALPHA16",
",",
"self",
".",
"width",
",",
"self",
".",
"width",
",",
"self",
".",
"width",
",",
"0",
",",
"GL_LUMINANCE_ALPHA",
",",
"GL_UNSIGNED_SHO... | Load the noise texture data into the current texture unit | [
"Load",
"the",
"noise",
"texture",
"data",
"into",
"the",
"current",
"texture",
"unit"
] | python | train |
opencast/pyCA | pyca/ui/jsonapi.py | https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/ui/jsonapi.py#L84-L106 | def delete_event(uid):
'''Delete a specific event identified by its uid. Note that only recorded
events can be deleted. Events in the buffer for upcoming events are
regularly replaced anyway and a manual removal could have unpredictable
effects.
Use ?hard=true parameter to delete the recorded files... | [
"def",
"delete_event",
"(",
"uid",
")",
":",
"logger",
".",
"info",
"(",
"'deleting event %s via api'",
",",
"uid",
")",
"db",
"=",
"get_session",
"(",
")",
"events",
"=",
"db",
".",
"query",
"(",
"RecordedEvent",
")",
".",
"filter",
"(",
"RecordedEvent",
... | Delete a specific event identified by its uid. Note that only recorded
events can be deleted. Events in the buffer for upcoming events are
regularly replaced anyway and a manual removal could have unpredictable
effects.
Use ?hard=true parameter to delete the recorded files on disk as well.
Returns... | [
"Delete",
"a",
"specific",
"event",
"identified",
"by",
"its",
"uid",
".",
"Note",
"that",
"only",
"recorded",
"events",
"can",
"be",
"deleted",
".",
"Events",
"in",
"the",
"buffer",
"for",
"upcoming",
"events",
"are",
"regularly",
"replaced",
"anyway",
"and... | python | test |
diffeo/yakonfig | yakonfig/toplevel.py | https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L303-L332 | def create_config_tree(config, modules, prefix=''):
'''Cause every possible configuration sub-dictionary to exist.
This is intended to be called very early in the configuration
sequence. For each module, it checks that the corresponding
configuration item exists in `config` and creates it as an empty
... | [
"def",
"create_config_tree",
"(",
"config",
",",
"modules",
",",
"prefix",
"=",
"''",
")",
":",
"def",
"work_in",
"(",
"parent_config",
",",
"config_name",
",",
"prefix",
",",
"module",
")",
":",
"if",
"config_name",
"not",
"in",
"parent_config",
":",
"# t... | Cause every possible configuration sub-dictionary to exist.
This is intended to be called very early in the configuration
sequence. For each module, it checks that the corresponding
configuration item exists in `config` and creates it as an empty
dictionary if required, and then recurses into child
... | [
"Cause",
"every",
"possible",
"configuration",
"sub",
"-",
"dictionary",
"to",
"exist",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/mpls_state/lsp/frr/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/mpls_state/lsp/frr/__init__.py#L691-L714 | def _set_computation_mode(self, v, load=False):
"""
Setter method for computation_mode, mapped from YANG variable /mpls_state/lsp/frr/computation_mode (lsp-cspf-computation-mode)
If this variable is read-only (config: false) in the
source YANG file, then _set_computation_mode is considered as a private
... | [
"def",
"_set_computation_mode",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for computation_mode, mapped from YANG variable /mpls_state/lsp/frr/computation_mode (lsp-cspf-computation-mode)
If this variable is read-only (config: false) in the
source YANG file, then _set_computation_mode is considered as a private
method. Backends looking to populate this variable shoul... | [
"Setter",
"method",
"for",
"computation_mode",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_state",
"/",
"lsp",
"/",
"frr",
"/",
"computation_mode",
"(",
"lsp",
"-",
"cspf",
"-",
"computation",
"-",
"mode",
")",
"If",
"this",
"variable",
"is",
"read",
... | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/netcdf.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/netcdf.py#L233-L250 | def read_keys(self, keys, dict_cls=AttrDict, path="/"):
"""
Read a list of variables/dimensions from file. If a key is not present the corresponding
entry in the output dictionary is set to None.
"""
od = dict_cls()
for k in keys:
try:
# Try to... | [
"def",
"read_keys",
"(",
"self",
",",
"keys",
",",
"dict_cls",
"=",
"AttrDict",
",",
"path",
"=",
"\"/\"",
")",
":",
"od",
"=",
"dict_cls",
"(",
")",
"for",
"k",
"in",
"keys",
":",
"try",
":",
"# Try to read a variable.",
"od",
"[",
"k",
"]",
"=",
... | Read a list of variables/dimensions from file. If a key is not present the corresponding
entry in the output dictionary is set to None. | [
"Read",
"a",
"list",
"of",
"variables",
"/",
"dimensions",
"from",
"file",
".",
"If",
"a",
"key",
"is",
"not",
"present",
"the",
"corresponding",
"entry",
"in",
"the",
"output",
"dictionary",
"is",
"set",
"to",
"None",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/standard/seq/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/type/vxlan/standard/seq/__init__.py#L272-L293 | def _set_src_vtep_ip_any(self, v, load=False):
"""
Setter method for src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_vtep_ip_any is considered as a private... | [
"def",
"_set_src_vtep_ip_any",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_vtep_ip_any is considered as a private
method. Backends looking to populate this variable sho... | [
"Setter",
"method",
"for",
"src_vtep_ip_any",
"mapped",
"from",
"YANG",
"variable",
"/",
"overlay",
"/",
"access_list",
"/",
"type",
"/",
"vxlan",
"/",
"standard",
"/",
"seq",
"/",
"src_vtep_ip_any",
"(",
"empty",
")",
"If",
"this",
"variable",
"is",
"read",... | python | train |
lord63/tldr.py | tldr/cli.py | https://github.com/lord63/tldr.py/blob/73cf9f86254691b2476910ea6a743b6d8bd04963/tldr/cli.py#L175-L178 | def locate(command, on):
"""Locate the command's man page."""
location = find_page_location(command, on)
click.echo(location) | [
"def",
"locate",
"(",
"command",
",",
"on",
")",
":",
"location",
"=",
"find_page_location",
"(",
"command",
",",
"on",
")",
"click",
".",
"echo",
"(",
"location",
")"
] | Locate the command's man page. | [
"Locate",
"the",
"command",
"s",
"man",
"page",
"."
] | python | train |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L605-L612 | def artist_undelete(self, artist_id):
"""Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+).
Parameters:
artist_id (int):
"""
return self._get('artists/{0}/undelete.json'.format(artist_id),
method='POST', auth=True) | [
"def",
"artist_undelete",
"(",
"self",
",",
"artist_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'artists/{0}/undelete.json'",
".",
"format",
"(",
"artist_id",
")",
",",
"method",
"=",
"'POST'",
",",
"auth",
"=",
"True",
")"
] | Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+).
Parameters:
artist_id (int): | [
"Lets",
"you",
"undelete",
"artist",
"(",
"Requires",
"login",
")",
"(",
"UNTESTED",
")",
"(",
"Only",
"Builder",
"+",
")",
"."
] | python | train |
rocky/python-uncompyle6 | uncompyle6/parsers/parse3.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/parsers/parse3.py#L480-L515 | def custom_classfunc_rule(self, opname, token, customize, next_token):
"""
call ::= expr {expr}^n CALL_FUNCTION_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n
call ::= expr {expr}^n CALL_FUNCTION_KW_n
classdefdeco2 ::= LOAD_BUI... | [
"def",
"custom_classfunc_rule",
"(",
"self",
",",
"opname",
",",
"token",
",",
"customize",
",",
"next_token",
")",
":",
"args_pos",
",",
"args_kw",
"=",
"self",
".",
"get_pos_kw",
"(",
"token",
")",
"# Additional exprs for * and ** args:",
"# 0 if neither",
"# ... | call ::= expr {expr}^n CALL_FUNCTION_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_n
call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n
call ::= expr {expr}^n CALL_FUNCTION_KW_n
classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc {expr}^n-1 CALL_FUNCTION_n | [
"call",
"::",
"=",
"expr",
"{",
"expr",
"}",
"^n",
"CALL_FUNCTION_n",
"call",
"::",
"=",
"expr",
"{",
"expr",
"}",
"^n",
"CALL_FUNCTION_VAR_n",
"call",
"::",
"=",
"expr",
"{",
"expr",
"}",
"^n",
"CALL_FUNCTION_VAR_KW_n",
"call",
"::",
"=",
"expr",
"{",
... | python | train |
bioasp/ingranalyze | src/bioquali.py | https://github.com/bioasp/ingranalyze/blob/60bdd679b6044a4d142abbca5bbe3cd5e9fd7596/src/bioquali.py#L46-L67 | def readGraph(filename):
p = graph_parser.Parser()
"""
input: string, name of a file containing a Bioquali-like graph description
output: asp.TermSet, with atoms matching the contents of the input file
Parses a Bioquali-like graph description, and returns
a TermSet object.
Written using ori... | [
"def",
"readGraph",
"(",
"filename",
")",
":",
"p",
"=",
"graph_parser",
".",
"Parser",
"(",
")",
"accu",
"=",
"TermSet",
"(",
")",
"file",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"s",
"=",
"file",
".",
"readline",
"(",
")",
"while",
"s",
... | input: string, name of a file containing a Bioquali-like graph description
output: asp.TermSet, with atoms matching the contents of the input file
Parses a Bioquali-like graph description, and returns
a TermSet object.
Written using original Bioquali | [
"input",
":",
"string",
"name",
"of",
"a",
"file",
"containing",
"a",
"Bioquali",
"-",
"like",
"graph",
"description",
"output",
":",
"asp",
".",
"TermSet",
"with",
"atoms",
"matching",
"the",
"contents",
"of",
"the",
"input",
"file"
] | python | train |
timothycrosley/connectable | connectable/base.py | https://github.com/timothycrosley/connectable/blob/d5958d974c04b16f410c602786809d0e2a6665d2/connectable/base.py#L22-L57 | def emit(self, signal, value=None, gather=False):
"""Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value)
signal: the name of the signal to emit, must be defined in the classes 'signals' list.
value: the value to pass to all connect... | [
"def",
"emit",
"(",
"self",
",",
"signal",
",",
"value",
"=",
"None",
",",
"gather",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"if",
"gather",
"else",
"True",
"if",
"hasattr",
"(",
"self",
",",
"'connections'",
")",
"and",
"signal",
"in",
"... | Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value)
signal: the name of the signal to emit, must be defined in the classes 'signals' list.
value: the value to pass to all connected slot methods.
gather: if set, causes emit to re... | [
"Emits",
"a",
"signal",
"causing",
"all",
"slot",
"methods",
"connected",
"with",
"the",
"signal",
"to",
"be",
"called",
"(",
"optionally",
"w",
"/",
"related",
"value",
")"
] | python | train |
shaypal5/decore | decore/decore.py | https://github.com/shaypal5/decore/blob/460f22f8b9127e6a80b161a626d8827673343afb/decore/decore.py#L24-L30 | def threadsafe_generator(generator_func):
"""A decorator that takes a generator function and makes it thread-safe.
"""
def decoration(*args, **keyword_args):
"""A thread-safe decoration for a generator function."""
return ThreadSafeIter(generator_func(*args, **keyword_args))
return decor... | [
"def",
"threadsafe_generator",
"(",
"generator_func",
")",
":",
"def",
"decoration",
"(",
"*",
"args",
",",
"*",
"*",
"keyword_args",
")",
":",
"\"\"\"A thread-safe decoration for a generator function.\"\"\"",
"return",
"ThreadSafeIter",
"(",
"generator_func",
"(",
"*",... | A decorator that takes a generator function and makes it thread-safe. | [
"A",
"decorator",
"that",
"takes",
"a",
"generator",
"function",
"and",
"makes",
"it",
"thread",
"-",
"safe",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L280-L298 | def axisar(axis, angle):
"""
Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html
:param axis: Rotation axis.
:type axis: 3 Element vector (list, tuple, numpy array)
:param angle... | [
"def",
"axisar",
"(",
"axis",
",",
"angle",
")",
":",
"axis",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"axis",
")",
"angle",
"=",
"ctypes",
".",
"c_double",
"(",
"angle",
")",
"r",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
")",
"libspice",
".",
... | Construct a rotation matrix that rotates vectors by a specified
angle about a specified axis.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html
:param axis: Rotation axis.
:type axis: 3 Element vector (list, tuple, numpy array)
:param angle: Rotation angle, in radians.
:t... | [
"Construct",
"a",
"rotation",
"matrix",
"that",
"rotates",
"vectors",
"by",
"a",
"specified",
"angle",
"about",
"a",
"specified",
"axis",
"."
] | python | train |
markovmodel/msmtools | msmtools/dtraj/api.py | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/dtraj/api.py#L524-L561 | def sample_indexes_by_distribution(indexes, distributions, nsample):
"""Samples trajectory/time indexes according to the given probability distributions
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
E... | [
"def",
"sample_indexes_by_distribution",
"(",
"indexes",
",",
"distributions",
",",
"nsample",
")",
":",
"# how many states in total?",
"n",
"=",
"len",
"(",
"indexes",
")",
"for",
"dist",
"in",
"distributions",
":",
"if",
"len",
"(",
"dist",
")",
"!=",
"n",
... | Samples trajectory/time indexes according to the given probability distributions
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
Each matrix has a number of rows equal to the number of occurrences of the co... | [
"Samples",
"trajectory",
"/",
"time",
"indexes",
"according",
"to",
"the",
"given",
"probability",
"distributions"
] | python | train |
OLC-Bioinformatics/sipprverse | method.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/method.py#L25-L44 | def main(self):
"""
Run the analyses using the inputted values for forward and reverse read length. However, if not all strains
pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either
all strains are complete, or the sequencing run ... | [
"def",
"main",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Starting {} analysis pipeline'",
".",
"format",
"(",
"self",
".",
"analysistype",
")",
")",
"self",
".",
"createobjects",
"(",
")",
"# Run the genesipping analyses",
"self",
".",
"methods",
"... | Run the analyses using the inputted values for forward and reverse read length. However, if not all strains
pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either
all strains are complete, or the sequencing run is finished | [
"Run",
"the",
"analyses",
"using",
"the",
"inputted",
"values",
"for",
"forward",
"and",
"reverse",
"read",
"length",
".",
"However",
"if",
"not",
"all",
"strains",
"pass",
"the",
"quality",
"thresholds",
"continue",
"to",
"periodically",
"run",
"the",
"analys... | python | train |
QInfer/python-qinfer | src/qinfer/abstract_model.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L357-L374 | def update_timestep(self, modelparams, expparams):
r"""
Returns a set of model parameter vectors that is the update of an
input set of model parameter vectors, such that the new models are
conditioned on a particular experiment having been performed.
By default, this is the trivi... | [
"def",
"update_timestep",
"(",
"self",
",",
"modelparams",
",",
"expparams",
")",
":",
"return",
"np",
".",
"tile",
"(",
"modelparams",
",",
"(",
"expparams",
".",
"shape",
"[",
"0",
"]",
",",
"1",
",",
"1",
")",
")",
".",
"transpose",
"(",
"(",
"1... | r"""
Returns a set of model parameter vectors that is the update of an
input set of model parameter vectors, such that the new models are
conditioned on a particular experiment having been performed.
By default, this is the trivial function
:math:`\vec{x}(t_{k+1}) = \vec{x}(t_k)`... | [
"r",
"Returns",
"a",
"set",
"of",
"model",
"parameter",
"vectors",
"that",
"is",
"the",
"update",
"of",
"an",
"input",
"set",
"of",
"model",
"parameter",
"vectors",
"such",
"that",
"the",
"new",
"models",
"are",
"conditioned",
"on",
"a",
"particular",
"exp... | python | train |
dwavesystems/dwave-cloud-client | dwave/cloud/utils.py | https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L316-L320 | def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items()))
return a + b | [
"def",
"argshash",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"a",
"=",
"repr",
"(",
"args",
")",
"b",
"=",
"repr",
"(",
"sorted",
"(",
"(",
"repr",
"(",
"k",
")",
",",
"repr",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs... | Hash mutable arguments' containers with immutable keys and values. | [
"Hash",
"mutable",
"arguments",
"containers",
"with",
"immutable",
"keys",
"and",
"values",
"."
] | python | train |
andrenarchy/krypy | krypy/utils.py | https://github.com/andrenarchy/krypy/blob/4883ec9a61d64ea56489e15c35cc40f0633ab2f1/krypy/utils.py#L1593-L1600 | def strakos(n, l_min=0.1, l_max=100, rho=0.9):
"""Return the Strakoš matrix.
See [Str92]_.
"""
d = [l_min + (i-1)*1./(n-1)*(l_max-l_min)*(rho**(n-i))
for i in range(1, n+1)]
return numpy.diag(d) | [
"def",
"strakos",
"(",
"n",
",",
"l_min",
"=",
"0.1",
",",
"l_max",
"=",
"100",
",",
"rho",
"=",
"0.9",
")",
":",
"d",
"=",
"[",
"l_min",
"+",
"(",
"i",
"-",
"1",
")",
"*",
"1.",
"/",
"(",
"n",
"-",
"1",
")",
"*",
"(",
"l_max",
"-",
"l_... | Return the Strakoš matrix.
See [Str92]_. | [
"Return",
"the",
"Strakoš",
"matrix",
"."
] | python | train |
saltstack/salt | salt/modules/riak.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/riak.py#L157-L179 | def cluster_commit():
'''
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak-admin', 'cluster commit')
if cmd['retcode'] != 0:
r... | [
"def",
"cluster_commit",
"(",
")",
":",
"ret",
"=",
"{",
"'comment'",
":",
"''",
",",
"'success'",
":",
"False",
"}",
"cmd",
"=",
"__execute_cmd",
"(",
"'riak-admin'",
",",
"'cluster commit'",
")",
"if",
"cmd",
"[",
"'retcode'",
"]",
"!=",
"0",
":",
"r... | Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit | [
"Commit",
"Cluster",
"Changes"
] | python | train |
ph4r05/monero-serialize | monero_serialize/xmrrpc.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L372-L392 | async def section(self, sec=None):
"""
Section / dict serialization
:return:
"""
if self.writing:
await dump_varint(self.iobj, len(sec))
for key in sec:
await self.section_name(key)
await self.storage_entry(sec[key])
... | [
"async",
"def",
"section",
"(",
"self",
",",
"sec",
"=",
"None",
")",
":",
"if",
"self",
".",
"writing",
":",
"await",
"dump_varint",
"(",
"self",
".",
"iobj",
",",
"len",
"(",
"sec",
")",
")",
"for",
"key",
"in",
"sec",
":",
"await",
"self",
"."... | Section / dict serialization
:return: | [
"Section",
"/",
"dict",
"serialization",
":",
"return",
":"
] | python | train |
gwpy/gwpy | gwpy/io/cache.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/cache.py#L155-L194 | def read_cache(cachefile, coltype=LIGOTimeGPS, sort=None, segment=None):
"""Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
... | [
"def",
"read_cache",
"(",
"cachefile",
",",
"coltype",
"=",
"LIGOTimeGPS",
",",
"sort",
"=",
"None",
",",
"segment",
"=",
"None",
")",
":",
"# open file",
"if",
"not",
"isinstance",
"(",
"cachefile",
",",
"FILE_LIKE",
")",
":",
"with",
"open",
"(",
"file... | Read a LAL- or FFL-format cache file as a list of file paths
Parameters
----------
cachefile : `str`, `file`
Input file or file path to read.
coltype : `LIGOTimeGPS`, `int`, optional
Type for GPS times.
sort : `callable`, optional
A callable key function by which to sort t... | [
"Read",
"a",
"LAL",
"-",
"or",
"FFL",
"-",
"format",
"cache",
"file",
"as",
"a",
"list",
"of",
"file",
"paths"
] | python | train |
edx/edx-enterprise | enterprise/api_client/discovery.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L364-L416 | def get_common_course_modes(self, course_run_ids):
"""
Find common course modes for a set of course runs.
This function essentially returns an intersection of types of seats available
for each course run.
Arguments:
course_run_ids(Iterable[str]): Target Course run I... | [
"def",
"get_common_course_modes",
"(",
"self",
",",
"course_run_ids",
")",
":",
"available_course_modes",
"=",
"None",
"for",
"course_run_id",
"in",
"course_run_ids",
":",
"course_run",
"=",
"self",
".",
"get_course_run",
"(",
"course_run_id",
")",
"or",
"{",
"}",... | Find common course modes for a set of course runs.
This function essentially returns an intersection of types of seats available
for each course run.
Arguments:
course_run_ids(Iterable[str]): Target Course run IDs.
Returns:
set: course modes found in all given ... | [
"Find",
"common",
"course",
"modes",
"for",
"a",
"set",
"of",
"course",
"runs",
"."
] | python | valid |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L492-L500 | def cloudnetwork(vm_):
'''
Determine if we should use an extra network to bootstrap
Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'cloudnetwork', vm_, __opts__, default=False,
search_global=False
) | [
"def",
"cloudnetwork",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'cloudnetwork'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"False",
",",
"search_global",
"=",
"False",
")"
] | Determine if we should use an extra network to bootstrap
Either 'False' (default) or 'True'. | [
"Determine",
"if",
"we",
"should",
"use",
"an",
"extra",
"network",
"to",
"bootstrap",
"Either",
"False",
"(",
"default",
")",
"or",
"True",
"."
] | python | train |
Kaggle/kaggle-api | kaggle/api/kaggle_api.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L230-L250 | def competitions_data_download_file(self, id, file_name, **kwargs): # noqa: E501
"""Download competition data file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.competitions_data_... | [
"def",
"competitions_data_download_file",
"(",
"self",
",",
"id",
",",
"file_name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"ret... | Download competition data file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.competitions_data_download_file(id, file_name, async_req=True)
>>> result = thread.get()
:para... | [
"Download",
"competition",
"data",
"file",
"#",
"noqa",
":",
"E501"
] | python | train |
fvdsn/py-xml-escpos | xmlescpos/escpos.py | https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L169-L176 | def to_escpos(self):
""" converts the current style to an escpos command string """
cmd = ''
ordered_cmds = self.cmds.keys()
ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order']))
for style in ordered_cmds:
cmd += self.cmds[style][self.get(... | [
"def",
"to_escpos",
"(",
"self",
")",
":",
"cmd",
"=",
"''",
"ordered_cmds",
"=",
"self",
".",
"cmds",
".",
"keys",
"(",
")",
"ordered_cmds",
".",
"sort",
"(",
"lambda",
"x",
",",
"y",
":",
"cmp",
"(",
"self",
".",
"cmds",
"[",
"x",
"]",
"[",
"... | converts the current style to an escpos command string | [
"converts",
"the",
"current",
"style",
"to",
"an",
"escpos",
"command",
"string"
] | python | train |
cloudendpoints/endpoints-python | endpoints/util.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/util.py#L231-L259 | def get_app_hostname():
"""Return hostname of a running Endpoints service.
Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT"
if running on development server, or 2) "app_id.appspot.com" if running on
external app engine prod, or "app_id.googleplex.com" if running as Google
first-par... | [
"def",
"get_app_hostname",
"(",
")",
":",
"if",
"not",
"is_running_on_app_engine",
"(",
")",
"or",
"is_running_on_localhost",
"(",
")",
":",
"return",
"None",
"app_id",
"=",
"app_identity",
".",
"get_application_id",
"(",
")",
"prefix",
"=",
"get_hostname_prefix",... | Return hostname of a running Endpoints service.
Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT"
if running on development server, or 2) "app_id.appspot.com" if running on
external app engine prod, or "app_id.googleplex.com" if running as Google
first-party Endpoints API, or 4) None ... | [
"Return",
"hostname",
"of",
"a",
"running",
"Endpoints",
"service",
"."
] | python | train |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L611-L617 | def compute_convex_hull(feed: "Feed") -> Polygon:
"""
Return a Shapely Polygon representing the convex hull formed by
the stops of the given Feed.
"""
m = sg.MultiPoint(feed.stops[["stop_lon", "stop_lat"]].values)
return m.convex_hull | [
"def",
"compute_convex_hull",
"(",
"feed",
":",
"\"Feed\"",
")",
"->",
"Polygon",
":",
"m",
"=",
"sg",
".",
"MultiPoint",
"(",
"feed",
".",
"stops",
"[",
"[",
"\"stop_lon\"",
",",
"\"stop_lat\"",
"]",
"]",
".",
"values",
")",
"return",
"m",
".",
"conve... | Return a Shapely Polygon representing the convex hull formed by
the stops of the given Feed. | [
"Return",
"a",
"Shapely",
"Polygon",
"representing",
"the",
"convex",
"hull",
"formed",
"by",
"the",
"stops",
"of",
"the",
"given",
"Feed",
"."
] | python | train |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py#L209-L222 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance
:rtype: twilio.re... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"WorkersCumulativeStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.work... | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
PyCQA/pylint | pylint/utils/ast_walker.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/ast_walker.py#L27-L55 | def add_checker(self, checker):
"""walk to the checker's dir and collect visit and leave methods"""
# XXX : should be possible to merge needed_checkers and add_checker
vcids = set()
lcids = set()
visits = self.visit_events
leaves = self.leave_events
for member in ... | [
"def",
"add_checker",
"(",
"self",
",",
"checker",
")",
":",
"# XXX : should be possible to merge needed_checkers and add_checker",
"vcids",
"=",
"set",
"(",
")",
"lcids",
"=",
"set",
"(",
")",
"visits",
"=",
"self",
".",
"visit_events",
"leaves",
"=",
"self",
"... | walk to the checker's dir and collect visit and leave methods | [
"walk",
"to",
"the",
"checker",
"s",
"dir",
"and",
"collect",
"visit",
"and",
"leave",
"methods"
] | python | test |
vaexio/vaex | packages/vaex-astro/vaex/astro/transformations.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-astro/vaex/astro/transformations.py#L206-L239 | def add_virtual_columns_lbrvr_proper_motion2vcartesian(self, long_in="l", lat_in="b", distance="distance", pm_long="pm_l", pm_lat="pm_b",
vr="vr", vx="vx", vy="vy", vz="vz",
center_v=(0, 0, 0),
... | [
"def",
"add_virtual_columns_lbrvr_proper_motion2vcartesian",
"(",
"self",
",",
"long_in",
"=",
"\"l\"",
",",
"lat_in",
"=",
"\"b\"",
",",
"distance",
"=",
"\"distance\"",
",",
"pm_long",
"=",
"\"pm_l\"",
",",
"pm_lat",
"=",
"\"pm_b\"",
",",
"vr",
"=",
"\"vr\"",
... | Convert radial velocity and galactic proper motions (and positions) to cartesian velocities wrt the center_v
Based on http://adsabs.harvard.edu/abs/1987AJ.....93..864J
:param long_in: Name/expression for galactic longitude
:param lat_in: Name/expression for galactic latitude
:param distance: Name/exp... | [
"Convert",
"radial",
"velocity",
"and",
"galactic",
"proper",
"motions",
"(",
"and",
"positions",
")",
"to",
"cartesian",
"velocities",
"wrt",
"the",
"center_v"
] | python | test |
belbio/bel | bel/lang/partialparse.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/partialparse.py#L647-L736 | def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
"""Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
# Error ... | [
"def",
"parsed_top_level_errors",
"(",
"parsed",
",",
"errors",
",",
"component_type",
":",
"str",
"=",
"\"\"",
")",
"->",
"Errors",
":",
"# Error check",
"fn_cnt",
"=",
"0",
"rel_cnt",
"=",
"0",
"nested_cnt",
"=",
"0",
"for",
"key",
"in",
"parsed",
":",
... | Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input | [
"Check",
"full",
"parse",
"for",
"errors"
] | python | train |
pyrogram/pyrogram | pyrogram/client/types/bots/callback_query.py | https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/types/bots/callback_query.py#L123-L165 | def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0):
"""Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`.
Use this method as a shortcut for:
.. code-block:: python
client.answer_callback_query(
cal... | [
"def",
"answer",
"(",
"self",
",",
"text",
":",
"str",
"=",
"None",
",",
"show_alert",
":",
"bool",
"=",
"None",
",",
"url",
":",
"str",
"=",
"None",
",",
"cache_time",
":",
"int",
"=",
"0",
")",
":",
"return",
"self",
".",
"_client",
".",
"answe... | Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`.
Use this method as a shortcut for:
.. code-block:: python
client.answer_callback_query(
callback_query.id,
text="Hello",
show_alert=True
)
Example:
... | [
"Bound",
"method",
"*",
"answer",
"*",
"of",
":",
"obj",
":",
"CallbackQuery",
"<pyrogram",
".",
"CallbackQuery",
">",
"."
] | python | train |
fhcrc/taxtastic | taxtastic/taxtable.py | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/taxtable.py#L199-L226 | def write_taxtable(self, out_fp, **kwargs):
"""
Write a taxtable for this node and all descendants,
including the lineage leading to this node.
"""
ranks_represented = frozenset(i.rank for i in self) | \
frozenset(i.rank for i in self.lineage())
ranks = [i for... | [
"def",
"write_taxtable",
"(",
"self",
",",
"out_fp",
",",
"*",
"*",
"kwargs",
")",
":",
"ranks_represented",
"=",
"frozenset",
"(",
"i",
".",
"rank",
"for",
"i",
"in",
"self",
")",
"|",
"frozenset",
"(",
"i",
".",
"rank",
"for",
"i",
"in",
"self",
... | Write a taxtable for this node and all descendants,
including the lineage leading to this node. | [
"Write",
"a",
"taxtable",
"for",
"this",
"node",
"and",
"all",
"descendants",
"including",
"the",
"lineage",
"leading",
"to",
"this",
"node",
"."
] | python | train |
Azure/azure-cli-extensions | src/express-route/azext_express_route/vendored_sdks/network_management_client.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/express-route/azext_express_route/vendored_sdks/network_management_client.py#L327-L337 | def available_delegations(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>`
"""
api_version = self._get_api_version('available_delegations')
if api_ver... | [
"def",
"available_delegations",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'available_delegations'",
")",
"if",
"api_version",
"==",
"'2018-08-01'",
":",
"from",
".",
"v2018_08_01",
".",
"operations",
"import",
"AvailableDelega... | Instance depends on the API version:
* 2018-08-01: :class:`AvailableDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableDelegationsOperations>` | [
"Instance",
"depends",
"on",
"the",
"API",
"version",
":"
] | python | train |
cloud-custodian/cloud-custodian | c7n/cwe.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/cwe.py#L120-L147 | def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event."""
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
if not isinstance(e, dict):
... | [
"def",
"get_trail_ids",
"(",
"cls",
",",
"event",
",",
"mode",
")",
":",
"resource_ids",
"=",
"(",
")",
"event_name",
"=",
"event",
"[",
"'detail'",
"]",
"[",
"'eventName'",
"]",
"event_source",
"=",
"event",
"[",
"'detail'",
"]",
"[",
"'eventSource'",
"... | extract resources ids from a cloud trail event. | [
"extract",
"resources",
"ids",
"from",
"a",
"cloud",
"trail",
"event",
"."
] | python | train |
noxdafox/vminspect | vminspect/vtscan.py | https://github.com/noxdafox/vminspect/blob/e685282564877e2d1950f1e09b292f4f4db1dbcd/vminspect/vtscan.py#L79-L108 | def scan(self, filetypes=None):
"""Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given pa... | [
"def",
"scan",
"(",
"self",
",",
"filetypes",
"=",
"None",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Scanning FS content.\"",
")",
"checksums",
"=",
"self",
".",
"filetype_filter",
"(",
"self",
".",
"_filesystem",
".",
"checksums",
"(",
"'/'",... | Iterates over the content of the disk and queries VirusTotal
to determine whether it's malicious or not.
filetypes is a list containing regular expression patterns.
If given, only the files which type will match with one or more of
the given patterns will be queried against VirusTotal.
... | [
"Iterates",
"over",
"the",
"content",
"of",
"the",
"disk",
"and",
"queries",
"VirusTotal",
"to",
"determine",
"whether",
"it",
"s",
"malicious",
"or",
"not",
"."
] | python | train |
sci-bots/dmf-device-ui | dmf_device_ui/canvas.py | https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/canvas.py#L1236-L1245 | def register_electrode_command(self, command, title=None, group=None):
'''
Register electrode command.
Add electrode plugin command to context menu.
'''
commands = self.electrode_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1]... | [
"def",
"register_electrode_command",
"(",
"self",
",",
"command",
",",
"title",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"commands",
"=",
"self",
".",
"electrode_commands",
".",
"setdefault",
"(",
"group",
",",
"OrderedDict",
"(",
")",
")",
"if",
... | Register electrode command.
Add electrode plugin command to context menu. | [
"Register",
"electrode",
"command",
"."
] | python | train |
Jaymon/endpoints | endpoints/http.py | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L816-L825 | def accept_encoding(self):
"""The encoding the client requested the response to use"""
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset
ret = ""
accept_encoding = self.get_header("Accept-Charset", "")
if accept_encoding:
bits = re.split(r"\s+... | [
"def",
"accept_encoding",
"(",
"self",
")",
":",
"# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset",
"ret",
"=",
"\"\"",
"accept_encoding",
"=",
"self",
".",
"get_header",
"(",
"\"Accept-Charset\"",
",",
"\"\"",
")",
"if",
"accept_encoding",
":",... | The encoding the client requested the response to use | [
"The",
"encoding",
"the",
"client",
"requested",
"the",
"response",
"to",
"use"
] | python | train |
alvations/pywsd | pywsd/similarity.py | https://github.com/alvations/pywsd/blob/4c12394c8adbcfed71dd912bdbef2e36370821bf/pywsd/similarity.py#L73-L90 | def sim(sense1: "wn.Synset", sense2: "wn.Synset", option: str = "path") -> float:
"""
Calculates similarity based on user's choice.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin').
:return: A float, similarity measureme... | [
"def",
"sim",
"(",
"sense1",
":",
"\"wn.Synset\"",
",",
"sense2",
":",
"\"wn.Synset\"",
",",
"option",
":",
"str",
"=",
"\"path\"",
")",
"->",
"float",
":",
"option",
"=",
"option",
".",
"lower",
"(",
")",
"if",
"option",
".",
"lower",
"(",
")",
"in"... | Calculates similarity based on user's choice.
:param sense1: A synset.
:param sense2: A synset.
:param option: String, one of ('path', 'wup', 'lch', 'res', 'jcn', 'lin').
:return: A float, similarity measurement. | [
"Calculates",
"similarity",
"based",
"on",
"user",
"s",
"choice",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidget.py#L1007-L1012 | def headerSortDescending( self ):
"""
Sorts the column at the current header index by descending order.
"""
self.setSortingEnabled(True)
self.sortByColumn(self._headerIndex, QtCore.Qt.DescendingOrder) | [
"def",
"headerSortDescending",
"(",
"self",
")",
":",
"self",
".",
"setSortingEnabled",
"(",
"True",
")",
"self",
".",
"sortByColumn",
"(",
"self",
".",
"_headerIndex",
",",
"QtCore",
".",
"Qt",
".",
"DescendingOrder",
")"
] | Sorts the column at the current header index by descending order. | [
"Sorts",
"the",
"column",
"at",
"the",
"current",
"header",
"index",
"by",
"descending",
"order",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/util.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/util.py#L283-L294 | def signal_children(children):
"""Relay interupt/term signals to children, for more solid process cleanup."""
def terminate_children(sig, frame):
log = Application.instance().log
log.critical("Got signal %i, terminating children..."%sig)
for child in children:
child.terminate... | [
"def",
"signal_children",
"(",
"children",
")",
":",
"def",
"terminate_children",
"(",
"sig",
",",
"frame",
")",
":",
"log",
"=",
"Application",
".",
"instance",
"(",
")",
".",
"log",
"log",
".",
"critical",
"(",
"\"Got signal %i, terminating children...\"",
"... | Relay interupt/term signals to children, for more solid process cleanup. | [
"Relay",
"interupt",
"/",
"term",
"signals",
"to",
"children",
"for",
"more",
"solid",
"process",
"cleanup",
"."
] | python | test |
spyder-ide/spyder | spyder/plugins/editor/utils/kill_ring.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/kill_ring.py#L55-L65 | def rotate(self):
""" Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
"""
self._index -= 1
if self._index >= 0:
return self._ring[self._index]
return None | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"_index",
"-=",
"1",
"if",
"self",
".",
"_index",
">=",
"0",
":",
"return",
"self",
".",
"_ring",
"[",
"self",
".",
"_index",
"]",
"return",
"None"
] | Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None. | [
"Rotate",
"the",
"kill",
"ring",
"then",
"yank",
"back",
"the",
"new",
"top",
"."
] | python | train |
gmr/infoblox | infoblox/record.py | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/record.py#L185-L200 | def _build_search_values(self, kwargs):
"""Build the search criteria dictionary. It will first try and build
the values from already set attributes on the object, falling back
to the passed in kwargs.
:param dict kwargs: Values to build the dict from
:rtype: dict
"""
... | [
"def",
"_build_search_values",
"(",
"self",
",",
"kwargs",
")",
":",
"criteria",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_search_by",
":",
"if",
"getattr",
"(",
"self",
",",
"key",
",",
"None",
")",
":",
"criteria",
"[",
"key",
"]",
"=",
"... | Build the search criteria dictionary. It will first try and build
the values from already set attributes on the object, falling back
to the passed in kwargs.
:param dict kwargs: Values to build the dict from
:rtype: dict | [
"Build",
"the",
"search",
"criteria",
"dictionary",
".",
"It",
"will",
"first",
"try",
"and",
"build",
"the",
"values",
"from",
"already",
"set",
"attributes",
"on",
"the",
"object",
"falling",
"back",
"to",
"the",
"passed",
"in",
"kwargs",
"."
] | python | train |
marcelnicolay/pycompressor | compressor/minifier/css.py | https://github.com/marcelnicolay/pycompressor/blob/ded6b16c58c9f2a7446014b171fd409a22b561e4/compressor/minifier/css.py#L40-L45 | def minify(self, css):
"""Tries to minimize the length of CSS code passed as parameter. Returns string."""
css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist
for rule in _REPLACERS[self.level]:
css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rul... | [
"def",
"minify",
"(",
"self",
",",
"css",
")",
":",
"css",
"=",
"css",
".",
"replace",
"(",
"\"\\r\\n\"",
",",
"\"\\n\"",
")",
"# get rid of Windows line endings, if they exist",
"for",
"rule",
"in",
"_REPLACERS",
"[",
"self",
".",
"level",
"]",
":",
"css",
... | Tries to minimize the length of CSS code passed as parameter. Returns string. | [
"Tries",
"to",
"minimize",
"the",
"length",
"of",
"CSS",
"code",
"passed",
"as",
"parameter",
".",
"Returns",
"string",
"."
] | python | valid |
mushkevych/scheduler | launch.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/launch.py#L148-L155 | def install_virtualenv(parser_args):
""" Installs virtual environment """
python_version = '.'.join(str(v) for v in sys.version_info[:2])
sys.stdout.write('Installing Python {0} virtualenv into {1} \n'.format(python_version, VE_ROOT))
if sys.version_info < (3, 3):
install_virtualenv_p2(VE_ROOT, ... | [
"def",
"install_virtualenv",
"(",
"parser_args",
")",
":",
"python_version",
"=",
"'.'",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"sys",
".",
"version_info",
"[",
":",
"2",
"]",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'Install... | Installs virtual environment | [
"Installs",
"virtual",
"environment"
] | python | train |
etalab/cada | cada/commands.py | https://github.com/etalab/cada/blob/36e8b57514445c01ff7cd59a1c965180baf83d5e/cada/commands.py#L70-L73 | def header(msg, *args, **kwargs):
'''Display an header'''
msg = ' '.join((yellow(HEADER), white(msg), yellow(HEADER)))
echo(msg, *args, **kwargs) | [
"def",
"header",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"' '",
".",
"join",
"(",
"(",
"yellow",
"(",
"HEADER",
")",
",",
"white",
"(",
"msg",
")",
",",
"yellow",
"(",
"HEADER",
")",
")",
")",
"echo",
"(",... | Display an header | [
"Display",
"an",
"header"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.