repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
zhmcclient/python-zhmcclient | zhmcclient/_lpar.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_lpar.py#L698-L786 | def stop(self, wait_for_completion=True, operation_timeout=None,
status_timeout=None, allow_status_exceptions=False):
"""
Stop this LPAR, using the HMC operation "Stop Logical
Partition". The stop operation stops the processors from
processing instructions.
This HMC... | [
"def",
"stop",
"(",
"self",
",",
"wait_for_completion",
"=",
"True",
",",
"operation_timeout",
"=",
"None",
",",
"status_timeout",
"=",
"None",
",",
"allow_status_exceptions",
"=",
"False",
")",
":",
"body",
"=",
"{",
"}",
"result",
"=",
"self",
".",
"mana... | Stop this LPAR, using the HMC operation "Stop Logical
Partition". The stop operation stops the processors from
processing instructions.
This HMC operation has deferred status behavior: If the asynchronous
job on the HMC is complete, it takes a few seconds until the LPAR
status h... | [
"Stop",
"this",
"LPAR",
"using",
"the",
"HMC",
"operation",
"Stop",
"Logical",
"Partition",
".",
"The",
"stop",
"operation",
"stops",
"the",
"processors",
"from",
"processing",
"instructions",
"."
] | python | train | 43.494382 |
fermiPy/fermipy | fermipy/srcmap_utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L225-L280 | def make_srcmap(psf, exp, spatial_model, sigma, npix=500, xpix=0.0, ypix=0.0,
cdelt=0.01, psf_scale_fn=None, klims=None, sparse=False):
"""Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
exp : `~numpy.ndarray`
Array of ... | [
"def",
"make_srcmap",
"(",
"psf",
",",
"exp",
",",
"spatial_model",
",",
"sigma",
",",
"npix",
"=",
"500",
",",
"xpix",
"=",
"0.0",
",",
"ypix",
"=",
"0.0",
",",
"cdelt",
"=",
"0.01",
",",
"psf_scale_fn",
"=",
"None",
",",
"klims",
"=",
"None",
","... | Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
exp : `~numpy.ndarray`
Array of exposures.
spatial_model : str
Spatial model.
sigma : float
Spatial size parameter for extended models.
xpix : float
Sou... | [
"Compute",
"the",
"source",
"map",
"for",
"a",
"given",
"spatial",
"model",
"."
] | python | train | 34.642857 |
tensorforce/tensorforce | tensorforce/util.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/util.py#L235-L263 | def register_saver_ops(self):
"""
Registers the saver operations to the graph in context.
"""
variables = self.get_savable_variables()
if variables is None or len(variables) == 0:
self._saver = None
return
base_scope = self._get_base_variable_sco... | [
"def",
"register_saver_ops",
"(",
"self",
")",
":",
"variables",
"=",
"self",
".",
"get_savable_variables",
"(",
")",
"if",
"variables",
"is",
"None",
"or",
"len",
"(",
"variables",
")",
"==",
"0",
":",
"self",
".",
"_saver",
"=",
"None",
"return",
"base... | Registers the saver operations to the graph in context. | [
"Registers",
"the",
"saver",
"operations",
"to",
"the",
"graph",
"in",
"context",
"."
] | python | valid | 30.896552 |
brocade/pynos | pynos/versions/base/interface.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L3026-L3105 | def vrrpe_spf_basic(self, **kwargs):
"""Set vrrpe short path forwarding to default.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
enable (bool): If vrrpe short... | [
"def",
"vrrpe_spf_basic",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"int_type",
"=",
"kwargs",
".",
"pop",
"(",
"'int_type'",
")",
".",
"lower",
"(",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"vrid",
"=",
"kwargs",
".",
"pop... | Set vrrpe short path forwarding to default.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
enable (bool): If vrrpe short path fowarding should be enabled
... | [
"Set",
"vrrpe",
"short",
"path",
"forwarding",
"to",
"default",
"."
] | python | train | 47.4625 |
lablup/backend.ai-client-py | src/ai/backend/client/cli/vfolder.py | https://github.com/lablup/backend.ai-client-py/blob/a063d774fea6f4350b89498c40d3c837ec3029a7/src/ai/backend/client/cli/vfolder.py#L190-L204 | def mkdir(name, path):
'''Create an empty directory in the virtual folder.
\b
NAME: Name of a virtual folder.
PATH: The name or path of directory. Parent directories are created automatically
if they do not exist.
'''
with Session() as session:
try:
session.VFolder... | [
"def",
"mkdir",
"(",
"name",
",",
"path",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"try",
":",
"session",
".",
"VFolder",
"(",
"name",
")",
".",
"mkdir",
"(",
"path",
")",
"print_done",
"(",
"'Done.'",
")",
"except",
"Exception",
... | Create an empty directory in the virtual folder.
\b
NAME: Name of a virtual folder.
PATH: The name or path of directory. Parent directories are created automatically
if they do not exist. | [
"Create",
"an",
"empty",
"directory",
"in",
"the",
"virtual",
"folder",
"."
] | python | train | 29.2 |
OCHA-DAP/hdx-python-api | src/hdx/hdx_locations.py | https://github.com/OCHA-DAP/hdx-python-api/blob/212440f54f73805826a16db77dbcb6033b18a313/src/hdx/hdx_locations.py#L66-L89 | def get_HDX_code_from_location(location, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]
"""Get HDX code for location
Args:
location (str): Location for which to get HDX code
locations (Optional[List[Dict... | [
"def",
"get_HDX_code_from_location",
"(",
"location",
",",
"locations",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]",
"if",
"locations",
"is",
"None",
":",
"locations",
"=",
"Loca... | Get HDX code for location
Args:
location (str): Location for which to get HDX code
locations (Optional[List[Dict]]): Valid locations list. Defaults to list downloaded from HDX.
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.
... | [
"Get",
"HDX",
"code",
"for",
"location"
] | python | train | 41.791667 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2724-L2751 | def fn_with_custom_grad(grad_fn, use_global_vars=False):
"""Decorator to create a subgraph with a custom gradient function.
The subgraph created by the decorated function is NOT put in a Defun and so
does not suffer from the limitations of the Defun (all subgraph ops on the
same device, no summaries).
Args:... | [
"def",
"fn_with_custom_grad",
"(",
"grad_fn",
",",
"use_global_vars",
"=",
"False",
")",
":",
"def",
"dec",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"return",
"_fn_with_custom_grad... | Decorator to create a subgraph with a custom gradient function.
The subgraph created by the decorated function is NOT put in a Defun and so
does not suffer from the limitations of the Defun (all subgraph ops on the
same device, no summaries).
Args:
grad_fn: function with signature
(inputs, variables... | [
"Decorator",
"to",
"create",
"a",
"subgraph",
"with",
"a",
"custom",
"gradient",
"function",
"."
] | python | train | 30.857143 |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L948-L965 | def delete_account_metadata(self, prefix=None):
"""
Removes all metadata matching the specified prefix from the account.
By default, the standard account metadata prefix ('X-Account-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must i... | [
"def",
"delete_account_metadata",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"# Add the metadata prefix, if needed.",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"ACCOUNT_META_PREFIX",
"curr_meta",
"=",
"self",
".",
"get_account_metadata",
"(",
"prefix... | Removes all metadata matching the specified prefix from the account.
By default, the standard account metadata prefix ('X-Account-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must include a non-None prefix, such as an empty string. | [
"Removes",
"all",
"metadata",
"matching",
"the",
"specified",
"prefix",
"from",
"the",
"account",
"."
] | python | train | 44.111111 |
leonidessaguisagjr/unicodeutil | unicodeutil/unicodeutil.py | https://github.com/leonidessaguisagjr/unicodeutil/blob/c25c882cf9cb38c123df49fad365be67e5818928/unicodeutil/unicodeutil.py#L394-L409 | def _load_unicode_block_info(self):
"""
Function for parsing the Unicode block info from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/
"""
filename = "Blocks.txt"
... | [
"def",
"_load_unicode_block_info",
"(",
"self",
")",
":",
"filename",
"=",
"\"Blocks.txt\"",
"current_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"codecs",
".",
"open",
"(",
"os... | Function for parsing the Unicode block info from the Unicode Character
Database (UCD) and generating a lookup table. For more info on the UCD,
see the following website: https://www.unicode.org/ucd/ | [
"Function",
"for",
"parsing",
"the",
"Unicode",
"block",
"info",
"from",
"the",
"Unicode",
"Character",
"Database",
"(",
"UCD",
")",
"and",
"generating",
"a",
"lookup",
"table",
".",
"For",
"more",
"info",
"on",
"the",
"UCD",
"see",
"the",
"following",
"we... | python | train | 60.75 |
saltstack/salt | salt/states/rabbitmq_policy.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_policy.py#L127-L165 | def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comme... | [
"def",
"absent",
"(",
"name",
",",
"vhost",
"=",
"'/'",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"policy_exists",
... | Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as | [
"Ensure",
"the",
"named",
"policy",
"is",
"absent"
] | python | train | 28.333333 |
APSL/transmanager | transmanager/utils.py | https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L46-L58 | def get_num_words(text):
"""
Counts and returns the number of words found in a given text
:param text:
:return:
"""
try:
word_regexp_pattern = re.compile(r"[a-zA-Záéíóúñ]+")
num_words = re.findall(word_regexp_pattern, text)
return len(num_words)
except TypeError:
... | [
"def",
"get_num_words",
"(",
"text",
")",
":",
"try",
":",
"word_regexp_pattern",
"=",
"re",
".",
"compile",
"(",
"r\"[a-zA-Záéíóúñ]+\")",
"",
"num_words",
"=",
"re",
".",
"findall",
"(",
"word_regexp_pattern",
",",
"text",
")",
"return",
"len",
"(",
"num_wo... | Counts and returns the number of words found in a given text
:param text:
:return: | [
"Counts",
"and",
"returns",
"the",
"number",
"of",
"words",
"found",
"in",
"a",
"given",
"text"
] | python | train | 24.692308 |
staugur/Flask-PluginKit | flask_pluginkit/utils.py | https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/utils.py#L40-L47 | def open(self, flag="c"):
"""Open handle
set protocol=2 to fix python3
.. versionadded:: 1.3.1
"""
return shelve.open(os.path.join(gettempdir(), self.index), flag=flag, protocol=2) | [
"def",
"open",
"(",
"self",
",",
"flag",
"=",
"\"c\"",
")",
":",
"return",
"shelve",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"self",
".",
"index",
")",
",",
"flag",
"=",
"flag",
",",
"protocol",
"=",
... | Open handle
set protocol=2 to fix python3
.. versionadded:: 1.3.1 | [
"Open",
"handle"
] | python | train | 26.875 |
mlperf/training | reinforcement/tensorflow/minigo/bigtable_input.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/bigtable_input.py#L384-L399 | def require_fresh_games(self, number_fresh):
"""Require a given number of fresh games to be played.
Args:
number_fresh: integer, number of new fresh games needed
Increments the cell `table_state=metadata:wait_for_game_number`
by the given number of games. This will cause
... | [
"def",
"require_fresh_games",
"(",
"self",
",",
"number_fresh",
")",
":",
"latest",
"=",
"self",
".",
"latest_game_number",
"table_state",
"=",
"self",
".",
"bt_table",
".",
"row",
"(",
"TABLE_STATE",
")",
"table_state",
".",
"set_cell",
"(",
"METADATA",
",",
... | Require a given number of fresh games to be played.
Args:
number_fresh: integer, number of new fresh games needed
Increments the cell `table_state=metadata:wait_for_game_number`
by the given number of games. This will cause
`self.wait_for_fresh_games()` to block until the g... | [
"Require",
"a",
"given",
"number",
"of",
"fresh",
"games",
"to",
"be",
"played",
"."
] | python | train | 43.75 |
google/prettytensor | prettytensor/pretty_tensor_class.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_class.py#L1479-L1482 | def with_name(self, name):
"""Sets the name scope for future operations."""
self._head = self._head.with_name(name)
return self | [
"def",
"with_name",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_head",
"=",
"self",
".",
"_head",
".",
"with_name",
"(",
"name",
")",
"return",
"self"
] | Sets the name scope for future operations. | [
"Sets",
"the",
"name",
"scope",
"for",
"future",
"operations",
"."
] | python | train | 34 |
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 | 31.230769 |
facetoe/zenpy | zenpy/lib/api.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api.py#L862-L873 | def upload(self, fp, token=None, target_name=None, content_type=None):
"""
Upload a file to Zendesk.
:param fp: file object, StringIO instance, content, or file path to be
uploaded
:param token: upload token for uploading multiple files
:param target_name: nam... | [
"def",
"upload",
"(",
"self",
",",
"fp",
",",
"token",
"=",
"None",
",",
"target_name",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"return",
"UploadRequest",
"(",
"self",
")",
".",
"post",
"(",
"fp",
",",
"token",
"=",
"token",
",",
"... | Upload a file to Zendesk.
:param fp: file object, StringIO instance, content, or file path to be
uploaded
:param token: upload token for uploading multiple files
:param target_name: name of the file inside Zendesk
:return: :class:`Upload` object containing a token and... | [
"Upload",
"a",
"file",
"to",
"Zendesk",
"."
] | python | train | 55.083333 |
gamechanger/dusty | dusty/http_server.py | https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/http_server.py#L61-L85 | def consume(consumer_id):
"""Given an existing consumer ID, return any new lines from the
log since the last time the consumer was consumed."""
global _consumers
consumer = _consumers[consumer_id]
client = get_docker_client()
try:
status = client.inspect_container(consumer.container_id)... | [
"def",
"consume",
"(",
"consumer_id",
")",
":",
"global",
"_consumers",
"consumer",
"=",
"_consumers",
"[",
"consumer_id",
"]",
"client",
"=",
"get_docker_client",
"(",
")",
"try",
":",
"status",
"=",
"client",
".",
"inspect_container",
"(",
"consumer",
".",
... | Given an existing consumer ID, return any new lines from the
log since the last time the consumer was consumed. | [
"Given",
"an",
"existing",
"consumer",
"ID",
"return",
"any",
"new",
"lines",
"from",
"the",
"log",
"since",
"the",
"last",
"time",
"the",
"consumer",
"was",
"consumed",
"."
] | python | valid | 39.92 |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1219-L1230 | def cookie_set(self, name, value):
"""
Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set.
"""
if not self.headers_active:
raise RuntimeError('headers have already b... | [
"def",
"cookie_set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"headers_active",
":",
"raise",
"RuntimeError",
"(",
"'headers have already been ended'",
")",
"cookie",
"=",
"\"{0}={1}; Path=/; HttpOnly\"",
".",
"format",
"(",
"n... | Set the value of a client cookie. This can only be called while
headers can be sent.
:param str name: The name of the cookie value to set.
:param str value: The value of the cookie to set. | [
"Set",
"the",
"value",
"of",
"a",
"client",
"cookie",
".",
"This",
"can",
"only",
"be",
"called",
"while",
"headers",
"can",
"be",
"sent",
"."
] | python | train | 35 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L639-L650 | def add_hours(self, datetimestr, n):
"""Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。
"""
a_datetime = self.parse_datetime(datetimestr)... | [
"def",
"add_hours",
"(",
"self",
",",
"datetimestr",
",",
"n",
")",
":",
"a_datetime",
"=",
"self",
".",
"parse_datetime",
"(",
"datetimestr",
")",
"return",
"a_datetime",
"+",
"timedelta",
"(",
"seconds",
"=",
"3600",
"*",
"n",
")"
] | Returns a time that n hours after a time.
:param datetimestr: a datetime object or a datetime str
:param n: number of hours, value can be negative
**中文文档**
返回给定日期N小时之后的时间。 | [
"Returns",
"a",
"time",
"that",
"n",
"hours",
"after",
"a",
"time",
"."
] | python | train | 30.416667 |
fermiPy/fermipy | fermipy/hpx_utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/hpx_utils.py#L423-L454 | def create_hpx(cls, nside, nest, coordsys='CEL', order=-1, ebins=None,
region=None, conv=HPX_Conv('FGST_CCUBE'), pixels=None):
"""Create a HPX object.
Parameters
----------
nside : int
HEALPix nside paramter
nest : bool
True for H... | [
"def",
"create_hpx",
"(",
"cls",
",",
"nside",
",",
"nest",
",",
"coordsys",
"=",
"'CEL'",
",",
"order",
"=",
"-",
"1",
",",
"ebins",
"=",
"None",
",",
"region",
"=",
"None",
",",
"conv",
"=",
"HPX_Conv",
"(",
"'FGST_CCUBE'",
")",
",",
"pixels",
"=... | Create a HPX object.
Parameters
----------
nside : int
HEALPix nside paramter
nest : bool
True for HEALPix "NESTED" indexing scheme, False for "RING" scheme.
coordsys : str
"CEL" or "GAL"
order : int
nside = 2**ord... | [
"Create",
"a",
"HPX",
"object",
"."
] | python | train | 28.875 |
MicroPyramid/django-simple-pagination | simple_pagination/models.py | https://github.com/MicroPyramid/django-simple-pagination/blob/8cb68b2b51b06cf8f72a13afa64564b1c49c3b41/simple_pagination/models.py#L83-L97 | def _endless_page(self, number, label=None):
"""Factory function that returns a *EndlessPage* instance.
This method works just like a partial constructor.
"""
return EndlessPage(
self._request,
number,
self._page.number,
len(self),
... | [
"def",
"_endless_page",
"(",
"self",
",",
"number",
",",
"label",
"=",
"None",
")",
":",
"return",
"EndlessPage",
"(",
"self",
".",
"_request",
",",
"number",
",",
"self",
".",
"_page",
".",
"number",
",",
"len",
"(",
"self",
")",
",",
"self",
".",
... | Factory function that returns a *EndlessPage* instance.
This method works just like a partial constructor. | [
"Factory",
"function",
"that",
"returns",
"a",
"*",
"EndlessPage",
"*",
"instance",
"."
] | python | train | 30.933333 |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/lexer.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/lexer.py#L336-L346 | def next(self):
"""Go one token ahead and return the old one"""
rv = self.current
if self._pushed:
self.current = self._pushed.popleft()
elif self.current.type is not TOKEN_EOF:
try:
self.current = self._next()
except StopIteration:
... | [
"def",
"next",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"current",
"if",
"self",
".",
"_pushed",
":",
"self",
".",
"current",
"=",
"self",
".",
"_pushed",
".",
"popleft",
"(",
")",
"elif",
"self",
".",
"current",
".",
"type",
"is",
"not",
"... | Go one token ahead and return the old one | [
"Go",
"one",
"token",
"ahead",
"and",
"return",
"the",
"old",
"one"
] | python | train | 32.090909 |
zkbt/the-friendly-stars | thefriendlystars/constellations/constellation.py | https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/constellations/constellation.py#L281-L314 | def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor='none', **kw):
'''
Plot the ra and dec of the coordinates,
at a given epoch, scaled by their magnitude.
(This does *not* create a new empty figure.)
Parameters
----------
sizescale : (opti... | [
"def",
"plot",
"(",
"self",
",",
"sizescale",
"=",
"10",
",",
"color",
"=",
"None",
",",
"alpha",
"=",
"0.5",
",",
"label",
"=",
"None",
",",
"edgecolor",
"=",
"'none'",
",",
"*",
"*",
"kw",
")",
":",
"# calculate the sizes of the stars (logarithmic with b... | Plot the ra and dec of the coordinates,
at a given epoch, scaled by their magnitude.
(This does *not* create a new empty figure.)
Parameters
----------
sizescale : (optional) float
The marker size for scatter for a star at the magnitudelimit.
color : (option... | [
"Plot",
"the",
"ra",
"and",
"dec",
"of",
"the",
"coordinates",
"at",
"a",
"given",
"epoch",
"scaled",
"by",
"their",
"magnitude",
"."
] | python | train | 37.911765 |
tarzanjw/python-mysql-binlog-to-blinker | mysqlbinlog2blinker/_subscribers.py | https://github.com/tarzanjw/python-mysql-binlog-to-blinker/blob/d61ab5962345377e142a225b16f731ab4196fc26/mysqlbinlog2blinker/_subscribers.py#L12-L26 | def _get_updated_values(before_values, after_values):
""" Get updated values from 2 dicts of values
Args:
before_values (dict): values before update
after_values (dict): values after update
Returns:
dict: a diff dict with key is field key, value is tuple of
(before_va... | [
"def",
"_get_updated_values",
"(",
"before_values",
",",
"after_values",
")",
":",
"assert",
"before_values",
".",
"keys",
"(",
")",
"==",
"after_values",
".",
"keys",
"(",
")",
"return",
"dict",
"(",
"[",
"(",
"k",
",",
"[",
"before_values",
"[",
"k",
"... | Get updated values from 2 dicts of values
Args:
before_values (dict): values before update
after_values (dict): values after update
Returns:
dict: a diff dict with key is field key, value is tuple of
(before_value, after_value) | [
"Get",
"updated",
"values",
"from",
"2",
"dicts",
"of",
"values"
] | python | train | 36.6 |
frictionlessdata/tabulator-py | tabulator/stream.py | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L177-L275 | def open(self):
'''Opens the stream for reading.'''
options = copy(self.__options)
# Get scheme and format if not already given
compression = None
if self.__scheme is None or self.__format is None:
detected_scheme, detected_format = helpers.detect_scheme_and_format(s... | [
"def",
"open",
"(",
"self",
")",
":",
"options",
"=",
"copy",
"(",
"self",
".",
"__options",
")",
"# Get scheme and format if not already given",
"compression",
"=",
"None",
"if",
"self",
".",
"__scheme",
"is",
"None",
"or",
"self",
".",
"__format",
"is",
"N... | Opens the stream for reading. | [
"Opens",
"the",
"stream",
"for",
"reading",
"."
] | python | train | 43.030303 |
probcomp/crosscat | src/LocalEngine.py | https://github.com/probcomp/crosscat/blob/4a05bddb06a45f3b7b3e05e095720f16257d1535/src/LocalEngine.py#L77-L101 | def initialize(
self, M_c, M_r, T, seed, initialization=b'from_the_prior',
row_initialization=-1, n_chains=1,
ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(),
S_GRID=(), MU_GRID=(), N_GRID=31,):
"""Sample a latent state from prior.
T, list of lists:
... | [
"def",
"initialize",
"(",
"self",
",",
"M_c",
",",
"M_r",
",",
"T",
",",
"seed",
",",
"initialization",
"=",
"b'from_the_prior'",
",",
"row_initialization",
"=",
"-",
"1",
",",
"n_chains",
"=",
"1",
",",
"ROW_CRP_ALPHA_GRID",
"=",
"(",
")",
",",
"COLUMN_... | Sample a latent state from prior.
T, list of lists:
The data table in mapped representation (all floats, generated
by data_utils.read_data_objects)
:returns: X_L, X_D -- the latent state | [
"Sample",
"a",
"latent",
"state",
"from",
"prior",
"."
] | python | train | 39.36 |
pydata/xarray | xarray/core/alignment.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/alignment.py#L265-L394 | def reindex_variables(
variables: Mapping[Any, Variable],
sizes: Mapping[Any, int],
indexes: Mapping[Any, pd.Index],
indexers: Mapping,
method: Optional[str] = None,
tolerance: Any = None,
copy: bool = True,
) -> 'Tuple[OrderedDict[Any, Variable], OrderedDict[Any, pd.Index]]':
"""Conform... | [
"def",
"reindex_variables",
"(",
"variables",
":",
"Mapping",
"[",
"Any",
",",
"Variable",
"]",
",",
"sizes",
":",
"Mapping",
"[",
"Any",
",",
"int",
"]",
",",
"indexes",
":",
"Mapping",
"[",
"Any",
",",
"pd",
".",
"Index",
"]",
",",
"indexers",
":",... | Conform a dictionary of aligned variables onto a new set of variables,
filling in missing values with NaN.
Not public API.
Parameters
----------
variables : dict-like
Dictionary of xarray.Variable objects.
sizes : dict-like
Dictionary from dimension names to integer sizes.
... | [
"Conform",
"a",
"dictionary",
"of",
"aligned",
"variables",
"onto",
"a",
"new",
"set",
"of",
"variables",
"filling",
"in",
"missing",
"values",
"with",
"NaN",
"."
] | python | train | 38.815385 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L242-L248 | def deserialize_json(cls, serialized_json):
'''Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon}
'''
serialized = json.loads(serialized_json)
return Macaroon.from_dict(serialized) | [
"def",
"deserialize_json",
"(",
"cls",
",",
"serialized_json",
")",
":",
"serialized",
"=",
"json",
".",
"loads",
"(",
"serialized_json",
")",
"return",
"Macaroon",
".",
"from_dict",
"(",
"serialized",
")"
] | Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon} | [
"Return",
"a",
"macaroon",
"deserialized",
"from",
"a",
"string"
] | python | train | 40.714286 |
saltstack/salt | salt/modules/webutil.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/webutil.py#L33-L70 | def useradd(pwfile, user, password, opts='', runas=None):
'''
Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid opt... | [
"def",
"useradd",
"(",
"pwfile",
",",
"user",
",",
"password",
",",
"opts",
"=",
"''",
",",
"runas",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pwfile",
")",
":",
"opts",
"+=",
"'c'",
"cmd",
"=",
"[",
"'htpasswd'"... | Add a user to htpasswd file using the htpasswd command. If the htpasswd
file does not exist, it will be created.
pwfile
Path to htpasswd file
user
User name
password
User password
opts
Valid options that can be passed are:
- `n` Don't update file; di... | [
"Add",
"a",
"user",
"to",
"htpasswd",
"file",
"using",
"the",
"htpasswd",
"command",
".",
"If",
"the",
"htpasswd",
"file",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
"."
] | python | train | 28.473684 |
lk-geimfari/mimesis | mimesis/providers/base.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/base.py#L51-L66 | def _validate_enum(self, item: Any, enum: Any) -> Any:
"""Validate enum parameter of method in subclasses of BaseProvider.
:param item: Item of enum object.
:param enum: Enum object.
:return: Value of item.
:raises NonEnumerableError: if ``item`` not in ``enum``.
"""
... | [
"def",
"_validate_enum",
"(",
"self",
",",
"item",
":",
"Any",
",",
"enum",
":",
"Any",
")",
"->",
"Any",
":",
"if",
"item",
"is",
"None",
":",
"result",
"=",
"get_random_item",
"(",
"enum",
",",
"self",
".",
"random",
")",
"elif",
"item",
"and",
"... | Validate enum parameter of method in subclasses of BaseProvider.
:param item: Item of enum object.
:param enum: Enum object.
:return: Value of item.
:raises NonEnumerableError: if ``item`` not in ``enum``. | [
"Validate",
"enum",
"parameter",
"of",
"method",
"in",
"subclasses",
"of",
"BaseProvider",
"."
] | python | train | 33.75 |
openid/python-openid | openid/yadis/xri.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L79-L86 | def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref | [
"def",
"_escape_xref",
"(",
"xref_match",
")",
":",
"xref",
"=",
"xref_match",
".",
"group",
"(",
")",
"xref",
"=",
"xref",
".",
"replace",
"(",
"'/'",
",",
"'%2F'",
")",
"xref",
"=",
"xref",
".",
"replace",
"(",
"'?'",
",",
"'%3F'",
")",
"xref",
"... | Escape things that need to be escaped if they're in a cross-reference. | [
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"if",
"they",
"re",
"in",
"a",
"cross",
"-",
"reference",
"."
] | python | train | 32.75 |
jedie/pathlib_revised | pathlib_revised/pathlib.py | https://github.com/jedie/pathlib_revised/blob/9e3921b683852d717793c1ac193d5b174fea6036/pathlib_revised/pathlib.py#L98-L107 | def extended_path(self):
"""
Add prefix \\?\ to every absolute path, so that it's a "extended-length"
path, that should be longer than 259 characters (called: "MAX_PATH")
see:
https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath
"""
if self.is_absolute()... | [
"def",
"extended_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_absolute",
"(",
")",
"and",
"not",
"self",
".",
"path",
".",
"startswith",
"(",
"\"\\\\\\\\\"",
")",
":",
"return",
"\"\\\\\\\\?\\\\%s\"",
"%",
"self",
".",
"path",
"return",
"self",
"... | Add prefix \\?\ to every absolute path, so that it's a "extended-length"
path, that should be longer than 259 characters (called: "MAX_PATH")
see:
https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath | [
"Add",
"prefix",
"\\\\",
"?",
"\\",
"to",
"every",
"absolute",
"path",
"so",
"that",
"it",
"s",
"a",
"extended",
"-",
"length",
"path",
"that",
"should",
"be",
"longer",
"than",
"259",
"characters",
"(",
"called",
":",
"MAX_PATH",
")",
"see",
":",
"htt... | python | valid | 41.7 |
coleifer/peewee | playhouse/sqlite_ext.py | https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L719-L807 | def ClosureTable(model_class, foreign_key=None, referencing_class=None,
referencing_key=None):
"""Model factory for the transitive closure extension."""
if referencing_class is None:
referencing_class = model_class
if foreign_key is None:
for field_obj in model_class._meta.... | [
"def",
"ClosureTable",
"(",
"model_class",
",",
"foreign_key",
"=",
"None",
",",
"referencing_class",
"=",
"None",
",",
"referencing_key",
"=",
"None",
")",
":",
"if",
"referencing_class",
"is",
"None",
":",
"referencing_class",
"=",
"model_class",
"if",
"foreig... | Model factory for the transitive closure extension. | [
"Model",
"factory",
"for",
"the",
"transitive",
"closure",
"extension",
"."
] | python | train | 37.022472 |
timmahrt/ProMo | promo/duration_morph.py | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/duration_morph.py#L95-L133 | def getMorphParameters(fromTGFN, toTGFN, tierName,
filterFunc=None, useBlanks=False):
'''
Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of ... | [
"def",
"getMorphParameters",
"(",
"fromTGFN",
",",
"toTGFN",
",",
"tierName",
",",
"filterFunc",
"=",
"None",
",",
"useBlanks",
"=",
"False",
")",
":",
"if",
"filterFunc",
"is",
"None",
":",
"filterFunc",
"=",
"lambda",
"entry",
":",
"True",
"# Everything is... | Get intervals for source and target audio files
Use this information to find out how much to stretch/shrink each source
interval.
The target values are based on the contents of toTGFN. | [
"Get",
"intervals",
"for",
"source",
"and",
"target",
"audio",
"files",
"Use",
"this",
"information",
"to",
"find",
"out",
"how",
"much",
"to",
"stretch",
"/",
"shrink",
"each",
"source",
"interval",
".",
"The",
"target",
"values",
"are",
"based",
"on",
"t... | python | train | 37.871795 |
spacetelescope/stsci.tools | lib/stsci/tools/minmatch.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/minmatch.py#L204-L210 | def getallkeys(self, key, failobj=None):
"""Returns a list of the full key names (not the items)
for all the matching values for key. The list will
contain a single entry for unambiguous matches and
multiple entries for ambiguous matches."""
if self.mmkeys is None: self._mmInit(... | [
"def",
"getallkeys",
"(",
"self",
",",
"key",
",",
"failobj",
"=",
"None",
")",
":",
"if",
"self",
".",
"mmkeys",
"is",
"None",
":",
"self",
".",
"_mmInit",
"(",
")",
"return",
"self",
".",
"mmkeys",
".",
"get",
"(",
"key",
",",
"failobj",
")"
] | Returns a list of the full key names (not the items)
for all the matching values for key. The list will
contain a single entry for unambiguous matches and
multiple entries for ambiguous matches. | [
"Returns",
"a",
"list",
"of",
"the",
"full",
"key",
"names",
"(",
"not",
"the",
"items",
")",
"for",
"all",
"the",
"matching",
"values",
"for",
"key",
".",
"The",
"list",
"will",
"contain",
"a",
"single",
"entry",
"for",
"unambiguous",
"matches",
"and",
... | python | train | 51.428571 |
jxtech/wechatpy | wechatpy/client/api/wxa.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/wxa.py#L203-L220 | def submit_audit(self, item_list):
"""
将第三方提交的代码包提交审核
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param item_list: 提交审核项的一个列表(至少填写1项,至多填写5项)
:type item_list: list[dict]
:return: 审核编号
:rtype: int
"... | [
"def",
"submit_audit",
"(",
"self",
",",
"item_list",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'wxa/submit_audit'",
",",
"data",
"=",
"{",
"'item_list'",
":",
"item_list",
",",
"}",
",",
"result_processor",
"=",
"lambda",
"x",
":",
"x",
"[",
"'aud... | 将第三方提交的代码包提交审核
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param item_list: 提交审核项的一个列表(至少填写1项,至多填写5项)
:type item_list: list[dict]
:return: 审核编号
:rtype: int | [
"将第三方提交的代码包提交审核",
"详情请参考",
"https",
":",
"//",
"open",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"cgi",
"-",
"bin",
"/",
"showdocument?action",
"=",
"dir_list&id",
"=",
"open1489140610_Uavc4"
] | python | train | 27.833333 |
pantsbuild/pants | src/python/pants/engine/legacy/graph.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/legacy/graph.py#L527-L539 | def hydrate_sources(sources_field, glob_match_error_behavior):
"""Given a SourcesField, request a Snapshot for its path_globs and create an EagerFilesetWithSpec.
"""
# TODO(#5864): merge the target's selection of --glob-expansion-failure (which doesn't exist yet)
# with the global default!
path_globs = source... | [
"def",
"hydrate_sources",
"(",
"sources_field",
",",
"glob_match_error_behavior",
")",
":",
"# TODO(#5864): merge the target's selection of --glob-expansion-failure (which doesn't exist yet)",
"# with the global default!",
"path_globs",
"=",
"sources_field",
".",
"path_globs",
".",
"... | Given a SourcesField, request a Snapshot for its path_globs and create an EagerFilesetWithSpec. | [
"Given",
"a",
"SourcesField",
"request",
"a",
"Snapshot",
"for",
"its",
"path_globs",
"and",
"create",
"an",
"EagerFilesetWithSpec",
"."
] | python | train | 51.923077 |
collectiveacuity/labPack | labpack/storage/appdata.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/appdata.py#L391-L494 | def list(self, prefix='', delimiter='', filter_function=None, max_results=1, reverse_search=True, previous_key=''):
'''
a method to list keys in the collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value which results must no... | [
"def",
"list",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"''",
",",
"filter_function",
"=",
"None",
",",
"max_results",
"=",
"1",
",",
"reverse_search",
"=",
"True",
",",
"previous_key",
"=",
"''",
")",
":",
"title",
"=",
"'%s.list'... | a method to list keys in the collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value which results must not contain (after prefix)
:param filter_function: (positional arguments) function used to filter results
:param max_results: int... | [
"a",
"method",
"to",
"list",
"keys",
"in",
"the",
"collection",
":",
"param",
"prefix",
":",
"string",
"with",
"prefix",
"value",
"to",
"filter",
"results",
":",
"param",
"delimiter",
":",
"string",
"with",
"value",
"which",
"results",
"must",
"not",
"cont... | python | train | 43.682692 |
samirelanduk/quickplots | quickplots/charts.py | https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L300-L320 | def vertical_padding(self, padding=None):
"""Returns or sets (if a value is provided) the chart's vertical
padding. This determines how much space will be above and below the
display area, as a proportion of overall height, and should be a value
between 0 and 0.5
:param float pa... | [
"def",
"vertical_padding",
"(",
"self",
",",
"padding",
"=",
"None",
")",
":",
"if",
"padding",
"is",
"None",
":",
"return",
"self",
".",
"_vertical_padding",
"else",
":",
"if",
"not",
"isinstance",
"(",
"padding",
",",
"float",
")",
":",
"raise",
"TypeE... | Returns or sets (if a value is provided) the chart's vertical
padding. This determines how much space will be above and below the
display area, as a proportion of overall height, and should be a value
between 0 and 0.5
:param float padding: If given, the chart's vertical_padding\
... | [
"Returns",
"or",
"sets",
"(",
"if",
"a",
"value",
"is",
"provided",
")",
"the",
"chart",
"s",
"vertical",
"padding",
".",
"This",
"determines",
"how",
"much",
"space",
"will",
"be",
"above",
"and",
"below",
"the",
"display",
"area",
"as",
"a",
"proportio... | python | train | 43.571429 |
nlm/nagplug | nagplug/__init__.py | https://github.com/nlm/nagplug/blob/9de70d8031caffbfa57ab9d8d03567e897e9e119/nagplug/__init__.py#L294-L301 | def add_result(self, code, message=None):
"""
add a result to the internal result list
arguments:
same arguments as for Result()
"""
self._results.append(Result(code, message)) | [
"def",
"add_result",
"(",
"self",
",",
"code",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"_results",
".",
"append",
"(",
"Result",
"(",
"code",
",",
"message",
")",
")"
] | add a result to the internal result list
arguments:
same arguments as for Result() | [
"add",
"a",
"result",
"to",
"the",
"internal",
"result",
"list"
] | python | train | 27.75 |
gem/oq-engine | openquake/hazardlib/gsim/tusa_langer_2016.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tusa_langer_2016.py#L353-L361 | def _compute_distance(self, rup, dists, C):
"""
Compute the distance function, equation (9):
"""
mref = 3.6
rref = 1.0
rval = np.sqrt(dists.rhypo ** 2 + C['h'] ** 2)
return (C['c1'] + C['c2'] * (rup.mag - mref)) *\
np.log10(rval / rref) + C['c3'] * (rv... | [
"def",
"_compute_distance",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"C",
")",
":",
"mref",
"=",
"3.6",
"rref",
"=",
"1.0",
"rval",
"=",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rhypo",
"**",
"2",
"+",
"C",
"[",
"'h'",
"]",
"**",
"2",
")",
"... | Compute the distance function, equation (9): | [
"Compute",
"the",
"distance",
"function",
"equation",
"(",
"9",
")",
":"
] | python | train | 35.777778 |
robotpy/pynetworktables2js | pynetworktables2js/nt_serial.py | https://github.com/robotpy/pynetworktables2js/blob/a2a925013b17de38306da36f091262d68610624c/pynetworktables2js/nt_serial.py#L25-L28 | def process_update(self, update):
"""Process an incoming update from a remote NetworkTables"""
data = json.loads(update)
NetworkTables.getEntry(data["k"]).setValue(data["v"]) | [
"def",
"process_update",
"(",
"self",
",",
"update",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"update",
")",
"NetworkTables",
".",
"getEntry",
"(",
"data",
"[",
"\"k\"",
"]",
")",
".",
"setValue",
"(",
"data",
"[",
"\"v\"",
"]",
")"
] | Process an incoming update from a remote NetworkTables | [
"Process",
"an",
"incoming",
"update",
"from",
"a",
"remote",
"NetworkTables"
] | python | train | 48.75 |
kgori/treeCl | treeCl/parsers.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/parsers.py#L222-L246 | def _dash_f_e_to_dict(self, info_filename, tree_filename):
"""
Raxml provides an option to fit model params to a tree,
selected with -f e.
The output is different and needs a different parser.
"""
with open(info_filename) as fl:
models, likelihood, partition_p... | [
"def",
"_dash_f_e_to_dict",
"(",
"self",
",",
"info_filename",
",",
"tree_filename",
")",
":",
"with",
"open",
"(",
"info_filename",
")",
"as",
"fl",
":",
"models",
",",
"likelihood",
",",
"partition_params",
"=",
"self",
".",
"_dash_f_e_parser",
".",
"parseFi... | Raxml provides an option to fit model params to a tree,
selected with -f e.
The output is different and needs a different parser. | [
"Raxml",
"provides",
"an",
"option",
"to",
"fit",
"model",
"params",
"to",
"a",
"tree",
"selected",
"with",
"-",
"f",
"e",
".",
"The",
"output",
"is",
"different",
"and",
"needs",
"a",
"different",
"parser",
"."
] | python | train | 35.52 |
rigetti/grove | grove/tomography/process_tomography.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/process_tomography.py#L245-L252 | def to_kraus(self):
"""
Compute the Kraus operator representation of the estimated process.
:return: The process as a list of Kraus operators.
:rytpe: List[np.array]
"""
return [k.data.toarray() for k in qt.to_kraus(self.sop)] | [
"def",
"to_kraus",
"(",
"self",
")",
":",
"return",
"[",
"k",
".",
"data",
".",
"toarray",
"(",
")",
"for",
"k",
"in",
"qt",
".",
"to_kraus",
"(",
"self",
".",
"sop",
")",
"]"
] | Compute the Kraus operator representation of the estimated process.
:return: The process as a list of Kraus operators.
:rytpe: List[np.array] | [
"Compute",
"the",
"Kraus",
"operator",
"representation",
"of",
"the",
"estimated",
"process",
"."
] | python | train | 33.5 |
tradenity/python-sdk | tradenity/resources/discount_coupon.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/discount_coupon.py#L436-L456 | def create_discount_coupon(cls, discount_coupon, **kwargs):
"""Create DiscountCoupon
Create a new DiscountCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_discount_coupon(discount... | [
"def",
"create_discount_coupon",
"(",
"cls",
",",
"discount_coupon",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_discount... | Create DiscountCoupon
Create a new DiscountCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_discount_coupon(discount_coupon, async=True)
>>> result = thread.get()
:param ... | [
"Create",
"DiscountCoupon"
] | python | train | 43.904762 |
DistrictDataLabs/yellowbrick | yellowbrick/style/rcmod.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/style/rcmod.py#L239-L256 | def set_style(style=None, rc=None):
"""
Set the aesthetic style of the plots.
This affects things like the color of the axes, whether a grid is
enabled by default, and other aesthetic elements.
Parameters
----------
style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}
... | [
"def",
"set_style",
"(",
"style",
"=",
"None",
",",
"rc",
"=",
"None",
")",
":",
"style_object",
"=",
"_axes_style",
"(",
"style",
",",
"rc",
")",
"mpl",
".",
"rcParams",
".",
"update",
"(",
"style_object",
")"
] | Set the aesthetic style of the plots.
This affects things like the color of the axes, whether a grid is
enabled by default, and other aesthetic elements.
Parameters
----------
style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of ... | [
"Set",
"the",
"aesthetic",
"style",
"of",
"the",
"plots",
"."
] | python | train | 37.222222 |
saltstack/salt | salt/modules/keystone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystone.py#L138-L154 | def api_version(profile=None, **connection_args):
'''
Returns the API version derived from endpoint's response.
CLI Example:
.. code-block:: bash
salt '*' keystone.api_version
'''
kwargs = _get_kwargs(profile=profile, **connection_args)
auth_url = kwargs.get('auth_url', kwargs.get... | [
"def",
"api_version",
"(",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kwargs",
"=",
"_get_kwargs",
"(",
"profile",
"=",
"profile",
",",
"*",
"*",
"connection_args",
")",
"auth_url",
"=",
"kwargs",
".",
"get",
"(",
"'auth_url'",
... | Returns the API version derived from endpoint's response.
CLI Example:
.. code-block:: bash
salt '*' keystone.api_version | [
"Returns",
"the",
"API",
"version",
"derived",
"from",
"endpoint",
"s",
"response",
"."
] | python | train | 31.352941 |
MoseleyBioinformaticsLab/nmrstarlib | nmrstarlib/csviewer.py | https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/csviewer.py#L70-L122 | def csview(self, view=False):
"""View chemical shift values organized by amino acid residue.
:param view: Open in default image viewer or save file in current working directory quietly.
:type view: :py:obj:`True` or :py:obj:`False`
:return: None
:rtype: :py:obj:`None`
""... | [
"def",
"csview",
"(",
"self",
",",
"view",
"=",
"False",
")",
":",
"for",
"starfile",
"in",
"fileio",
".",
"read_files",
"(",
"self",
".",
"from_path",
")",
":",
"chains",
"=",
"starfile",
".",
"chem_shifts_by_residue",
"(",
"amino_acids",
"=",
"self",
"... | View chemical shift values organized by amino acid residue.
:param view: Open in default image viewer or save file in current working directory quietly.
:type view: :py:obj:`True` or :py:obj:`False`
:return: None
:rtype: :py:obj:`None` | [
"View",
"chemical",
"shift",
"values",
"organized",
"by",
"amino",
"acid",
"residue",
"."
] | python | train | 51.226415 |
saltstack/salt | salt/fileserver/s3fs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/s3fs.py#L657-L736 | def _get_file_from_s3(metadata, saltenv, bucket_name, path, cached_file_path):
'''
Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, path_style, https_enable = _get_s3_key()
# c... | [
"def",
"_get_file_from_s3",
"(",
"metadata",
",",
"saltenv",
",",
"bucket_name",
",",
"path",
",",
"cached_file_path",
")",
":",
"key",
",",
"keyid",
",",
"service_url",
",",
"verify_ssl",
",",
"kms_keyid",
",",
"location",
",",
"path_style",
",",
"https_enabl... | Checks the local cache for the file, if it's old or missing go grab the
file from S3 and update the cache | [
"Checks",
"the",
"local",
"cache",
"for",
"the",
"file",
"if",
"it",
"s",
"old",
"or",
"missing",
"go",
"grab",
"the",
"file",
"from",
"S3",
"and",
"update",
"the",
"cache"
] | python | train | 44.1625 |
awslabs/sockeye | sockeye/image_captioning/train.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/image_captioning/train.py#L254-L266 | def get_preinit_encoders(encoders: List[encoder.Encoder]) -> List[Tuple[str, mx.init.Initializer]]:
"""
Get initializers from encoders. Some encoders might be initialized from pretrained models.
:param encoders: List of encoders
:return: The list of initializers
"""
init = [] # type: List[Tupl... | [
"def",
"get_preinit_encoders",
"(",
"encoders",
":",
"List",
"[",
"encoder",
".",
"Encoder",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"mx",
".",
"init",
".",
"Initializer",
"]",
"]",
":",
"init",
"=",
"[",
"]",
"# type: List[Tuple[str, mx.i... | Get initializers from encoders. Some encoders might be initialized from pretrained models.
:param encoders: List of encoders
:return: The list of initializers | [
"Get",
"initializers",
"from",
"encoders",
".",
"Some",
"encoders",
"might",
"be",
"initialized",
"from",
"pretrained",
"models",
"."
] | python | train | 41.153846 |
GiulioRossetti/dynetx | dynetx/classes/dyngraph.py | https://github.com/GiulioRossetti/dynetx/blob/634e2b38f8950885aebfa079dad7d5e8d7563f1d/dynetx/classes/dyngraph.py#L577-L600 | def neighbors_iter(self, n, t=None):
"""Return an iterator over all neighbors of node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned an iterator over the neighbors of the node on the ... | [
"def",
"neighbors_iter",
"(",
"self",
",",
"n",
",",
"t",
"=",
"None",
")",
":",
"try",
":",
"if",
"t",
"is",
"None",
":",
"return",
"iter",
"(",
"self",
".",
"_adj",
"[",
"n",
"]",
")",
"else",
":",
"return",
"iter",
"(",
"[",
"i",
"for",
"i... | Return an iterator over all neighbors of node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned an iterator over the neighbors of the node on the flattened graph.
Examples
-----... | [
"Return",
"an",
"iterator",
"over",
"all",
"neighbors",
"of",
"node",
"n",
"at",
"time",
"t",
"."
] | python | train | 32.541667 |
devopshq/youtrack | youtrack/connection.py | https://github.com/devopshq/youtrack/blob/c4ec19aca253ae30ac8eee7976a2f330e480a73b/youtrack/connection.py#L498-L501 | def get_project(self, project_id):
""" http://confluence.jetbrains.net/display/YTD2/GET+project
"""
return youtrack.Project(self._get("/admin/project/" + urlquote(project_id)), self) | [
"def",
"get_project",
"(",
"self",
",",
"project_id",
")",
":",
"return",
"youtrack",
".",
"Project",
"(",
"self",
".",
"_get",
"(",
"\"/admin/project/\"",
"+",
"urlquote",
"(",
"project_id",
")",
")",
",",
"self",
")"
] | http://confluence.jetbrains.net/display/YTD2/GET+project | [
"http",
":",
"//",
"confluence",
".",
"jetbrains",
".",
"net",
"/",
"display",
"/",
"YTD2",
"/",
"GET",
"+",
"project"
] | python | train | 50.75 |
ionelmc/python-manhole | src/manhole/__init__.py | https://github.com/ionelmc/python-manhole/blob/6a519a1f25142b047e814c6d00f4ef404856a15d/src/manhole/__init__.py#L259-L281 | def handle_connection_exec(client):
"""
Alternate connection handler. No output redirection.
"""
class ExitExecLoop(Exception):
pass
def exit():
raise ExitExecLoop()
client.settimeout(None)
fh = os.fdopen(client.detach() if hasattr(client, 'detach') else client.fileno())
... | [
"def",
"handle_connection_exec",
"(",
"client",
")",
":",
"class",
"ExitExecLoop",
"(",
"Exception",
")",
":",
"pass",
"def",
"exit",
"(",
")",
":",
"raise",
"ExitExecLoop",
"(",
")",
"client",
".",
"settimeout",
"(",
"None",
")",
"fh",
"=",
"os",
".",
... | Alternate connection handler. No output redirection. | [
"Alternate",
"connection",
"handler",
".",
"No",
"output",
"redirection",
"."
] | python | train | 30.608696 |
iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L927-L939 | def _register_notification_callback(self, connection_handle, attribute_handle, callback, once=False):
"""Register a callback as a notification callback. It will be called if a notification with the matching
connection_handle and attribute_handle is received.
Args:
connection_handle ... | [
"def",
"_register_notification_callback",
"(",
"self",
",",
"connection_handle",
",",
"attribute_handle",
",",
"callback",
",",
"once",
"=",
"False",
")",
":",
"notification_id",
"=",
"(",
"connection_handle",
",",
"attribute_handle",
")",
"with",
"self",
".",
"no... | Register a callback as a notification callback. It will be called if a notification with the matching
connection_handle and attribute_handle is received.
Args:
connection_handle (int): The connection handle to watch
attribute_handle (int): The attribute handle to watch
... | [
"Register",
"a",
"callback",
"as",
"a",
"notification",
"callback",
".",
"It",
"will",
"be",
"called",
"if",
"a",
"notification",
"with",
"the",
"matching",
"connection_handle",
"and",
"attribute_handle",
"is",
"received",
"."
] | python | train | 63.461538 |
gplepage/gvar | src/gvar/__init__.py | https://github.com/gplepage/gvar/blob/d6671697319eb6280de3793c9a1c2b616c6f2ae0/src/gvar/__init__.py#L1059-L1099 | def analyze(self, count):
""" Analyze count data from :meth:`PDFHistogram.count`.
Turns an array of counts (see :meth:`PDFHistogram.count`) into a
histogram of probabilities, and estimates the mean, standard
deviation, and other statistical characteristics of the corresponding
... | [
"def",
"analyze",
"(",
"self",
",",
"count",
")",
":",
"if",
"numpy",
".",
"ndim",
"(",
"count",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'count must have dimension 1'",
")",
"if",
"len",
"(",
"count",
")",
"==",
"len",
"(",
"self",
".",
"mi... | Analyze count data from :meth:`PDFHistogram.count`.
Turns an array of counts (see :meth:`PDFHistogram.count`) into a
histogram of probabilities, and estimates the mean, standard
deviation, and other statistical characteristics of the corresponding
probability distribution.
Arg... | [
"Analyze",
"count",
"data",
"from",
":",
"meth",
":",
"PDFHistogram",
".",
"count",
"."
] | python | train | 41.853659 |
dlecocq/nsq-py | nsq/reader.py | https://github.com/dlecocq/nsq-py/blob/3ecacf6ab7719d38031179277113d875554a0c16/nsq/reader.py#L26-L42 | def distribute_ready(self):
'''Distribute the ready state across all of the connections'''
connections = [c for c in self.connections() if c.alive()]
if len(connections) > self._max_in_flight:
raise NotImplementedError(
'Max in flight must be greater than number of co... | [
"def",
"distribute_ready",
"(",
"self",
")",
":",
"connections",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"connections",
"(",
")",
"if",
"c",
".",
"alive",
"(",
")",
"]",
"if",
"len",
"(",
"connections",
")",
">",
"self",
".",
"_max_in_flight",
... | Distribute the ready state across all of the connections | [
"Distribute",
"the",
"ready",
"state",
"across",
"all",
"of",
"the",
"connections"
] | python | train | 53.411765 |
mcs07/ChemDataExtractor | chemdataextractor/cli/pos.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L73-L127 | def train(ctx, output, corpus, clusters):
"""Train POS Tagger."""
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+gen... | [
"def",
"train",
"(",
"ctx",
",",
"output",
",",
"corpus",
",",
"clusters",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.train'",
")",
"click",
".",
"echo",
"(",
"'Output: %s'",
"%",
"output",
")",
"click",
".",
"echo",
"(",
"'Corpus: %s'",
... | Train POS Tagger. | [
"Train",
"POS",
"Tagger",
"."
] | python | train | 43.690909 |
casacore/python-casacore | casacore/tables/table.py | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L819-L847 | def rownumbers(self, table=None):
"""Return a list containing the row numbers of this table.
This method can be useful after a selection or a sort.
It returns the row numbers of the rows in this table with respect
to the given table. If no table is given, the original table is used.
... | [
"def",
"rownumbers",
"(",
"self",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"None",
":",
"return",
"self",
".",
"_rownumbers",
"(",
"Table",
"(",
")",
")",
"return",
"self",
".",
"_rownumbers",
"(",
"table",
")"
] | Return a list containing the row numbers of this table.
This method can be useful after a selection or a sort.
It returns the row numbers of the rows in this table with respect
to the given table. If no table is given, the original table is used.
For example::
t = table('W53... | [
"Return",
"a",
"list",
"containing",
"the",
"row",
"numbers",
"of",
"this",
"table",
"."
] | python | train | 37.310345 |
androguard/androguard | androguard/cli/entry_points.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/cli/entry_points.py#L142-L247 | def arsc(input_,
file_,
output,
package,
locale,
type_,
id_,
list_packages,
list_locales,
list_types):
"""
Decode resources.arsc either directly from a given file or from an APK.
Example:
\b
$ androguard arsc app.... | [
"def",
"arsc",
"(",
"input_",
",",
"file_",
",",
"output",
",",
"package",
",",
"locale",
",",
"type_",
",",
"id_",
",",
"list_packages",
",",
"list_locales",
",",
"list_types",
")",
":",
"from",
"androguard",
".",
"core",
"import",
"androconf",
"from",
... | Decode resources.arsc either directly from a given file or from an APK.
Example:
\b
$ androguard arsc app.apk | [
"Decode",
"resources",
".",
"arsc",
"either",
"directly",
"from",
"a",
"given",
"file",
"or",
"from",
"an",
"APK",
"."
] | python | train | 29.933962 |
materialsproject/pymatgen | pymatgen/core/units.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/units.py#L488-L508 | def to(self, new_unit):
"""
Conversion to a new_unit. Right now, only supports 1 to 1 mapping of
units of each type.
Args:
new_unit: New unit type.
Returns:
A FloatWithUnit object in the new units.
Example usage:
>>> e = Energy(1.1, "eV"... | [
"def",
"to",
"(",
"self",
",",
"new_unit",
")",
":",
"return",
"FloatWithUnit",
"(",
"self",
"*",
"self",
".",
"unit",
".",
"get_conversion_factor",
"(",
"new_unit",
")",
",",
"unit_type",
"=",
"self",
".",
"_unit_type",
",",
"unit",
"=",
"new_unit",
")"... | Conversion to a new_unit. Right now, only supports 1 to 1 mapping of
units of each type.
Args:
new_unit: New unit type.
Returns:
A FloatWithUnit object in the new units.
Example usage:
>>> e = Energy(1.1, "eV")
>>> e = Energy(1.1, "Ha")
... | [
"Conversion",
"to",
"a",
"new_unit",
".",
"Right",
"now",
"only",
"supports",
"1",
"to",
"1",
"mapping",
"of",
"units",
"of",
"each",
"type",
"."
] | python | train | 26.285714 |
helixyte/everest | everest/url.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/url.py#L183-L192 | def make_order_string(cls, order_specification):
"""
Converts the given order specification to a CQL order expression.
"""
registry = get_current_registry()
visitor_cls = registry.getUtility(IOrderSpecificationVisitor,
name=EXPRESSION_KIN... | [
"def",
"make_order_string",
"(",
"cls",
",",
"order_specification",
")",
":",
"registry",
"=",
"get_current_registry",
"(",
")",
"visitor_cls",
"=",
"registry",
".",
"getUtility",
"(",
"IOrderSpecificationVisitor",
",",
"name",
"=",
"EXPRESSION_KINDS",
".",
"CQL",
... | Converts the given order specification to a CQL order expression. | [
"Converts",
"the",
"given",
"order",
"specification",
"to",
"a",
"CQL",
"order",
"expression",
"."
] | python | train | 43.3 |
tgbugs/pyontutils | pyontutils/combinators.py | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/combinators.py#L681-L707 | def serialize(self, subject, *objects_or_combinators):
""" object_combinators may also be URIRefs or Literals """
ec_s = rdflib.BNode()
if self.operator is not None:
if subject is not None:
yield subject, self.predicate, ec_s
yield from oc(ec_s)
... | [
"def",
"serialize",
"(",
"self",
",",
"subject",
",",
"*",
"objects_or_combinators",
")",
":",
"ec_s",
"=",
"rdflib",
".",
"BNode",
"(",
")",
"if",
"self",
".",
"operator",
"is",
"not",
"None",
":",
"if",
"subject",
"is",
"not",
"None",
":",
"yield",
... | object_combinators may also be URIRefs or Literals | [
"object_combinators",
"may",
"also",
"be",
"URIRefs",
"or",
"Literals"
] | python | train | 39.888889 |
PyCQA/astroid | astroid/scoped_nodes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/scoped_nodes.py#L1338-L1371 | def postinit(
self,
args,
body,
decorators=None,
returns=None,
type_comment_returns=None,
type_comment_args=None,
):
"""Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments or li... | [
"def",
"postinit",
"(",
"self",
",",
"args",
",",
"body",
",",
"decorators",
"=",
"None",
",",
"returns",
"=",
"None",
",",
"type_comment_returns",
"=",
"None",
",",
"type_comment_args",
"=",
"None",
",",
")",
":",
"self",
".",
"args",
"=",
"args",
"se... | Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments or list
:param body: The contents of the function body.
:type body: list(NodeNG)
:param decorators: The decorators that are applied to this
method or funct... | [
"Do",
"some",
"setup",
"after",
"initialisation",
"."
] | python | train | 31.794118 |
w1ll1am23/pubnubsub-handler | pubnubsubhandler.py | https://github.com/w1ll1am23/pubnubsub-handler/blob/0283c191d6042727f55a748f69a485d751f4cacb/pubnubsubhandler.py#L56-L77 | def add_subscription(self, channel, callback_function):
"""
Add a channel to subscribe to and a callback function to
run when the channel receives an update.
If channel already exists, create a new "subscription"
and append another callback function.
Args:
ch... | [
"def",
"add_subscription",
"(",
"self",
",",
"channel",
",",
"callback_function",
")",
":",
"if",
"channel",
"not",
"in",
"CHANNELS",
":",
"CHANNELS",
".",
"append",
"(",
"channel",
")",
"SUBSCRIPTIONS",
"[",
"channel",
"]",
"=",
"[",
"callback_function",
"]... | Add a channel to subscribe to and a callback function to
run when the channel receives an update.
If channel already exists, create a new "subscription"
and append another callback function.
Args:
channel (str): The channel to add a subscription too.
callback_fun... | [
"Add",
"a",
"channel",
"to",
"subscribe",
"to",
"and",
"a",
"callback",
"function",
"to",
"run",
"when",
"the",
"channel",
"receives",
"an",
"update",
".",
"If",
"channel",
"already",
"exists",
"create",
"a",
"new",
"subscription",
"and",
"append",
"another"... | python | train | 44.636364 |
gem/oq-engine | openquake/baselib/datastore.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/datastore.py#L285-L301 | def extend(self, key, array, **attrs):
"""
Extend the dataset associated to the given key; create it if needed
:param key: name of the dataset
:param array: array to store
:param attrs: a dictionary of attributes
"""
try:
dset = self.hdf5[key]
... | [
"def",
"extend",
"(",
"self",
",",
"key",
",",
"array",
",",
"*",
"*",
"attrs",
")",
":",
"try",
":",
"dset",
"=",
"self",
".",
"hdf5",
"[",
"key",
"]",
"except",
"KeyError",
":",
"dset",
"=",
"hdf5",
".",
"create",
"(",
"self",
".",
"hdf5",
",... | Extend the dataset associated to the given key; create it if needed
:param key: name of the dataset
:param array: array to store
:param attrs: a dictionary of attributes | [
"Extend",
"the",
"dataset",
"associated",
"to",
"the",
"given",
"key",
";",
"create",
"it",
"if",
"needed"
] | python | train | 33.117647 |
dbcli/athenacli | athenacli/packages/prompt_utils.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L9-L19 | def confirm_destructive_query(queries):
"""Check if the query is destructive and prompts the user to confirm.
Returns:
* None if the query is non-destructive or we can't prompt the user.
* True if the query is destructive and the user wants to proceed.
* False if the query is destructive and the use... | [
"def",
"confirm_destructive_query",
"(",
"queries",
")",
":",
"prompt_text",
"=",
"(",
"\"You're about to run a destructive command.\\n\"",
"\"Do you want to proceed? (y/n)\"",
")",
"if",
"is_destructive",
"(",
"queries",
")",
"and",
"sys",
".",
"stdin",
".",
"isatty",
... | Check if the query is destructive and prompts the user to confirm.
Returns:
* None if the query is non-destructive or we can't prompt the user.
* True if the query is destructive and the user wants to proceed.
* False if the query is destructive and the user doesn't want to proceed. | [
"Check",
"if",
"the",
"query",
"is",
"destructive",
"and",
"prompts",
"the",
"user",
"to",
"confirm",
".",
"Returns",
":",
"*",
"None",
"if",
"the",
"query",
"is",
"non",
"-",
"destructive",
"or",
"we",
"can",
"t",
"prompt",
"the",
"user",
".",
"*",
... | python | train | 51.181818 |
linkhub-sdk/popbill.py | popbill/taxinvoiceService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/taxinvoiceService.py#L203-L219 | def getInfo(self, CorpNum, MgtKeyType, MgtKey):
""" 상태정보 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
처리결과. consist of code and message
raise
... | [
"def",
"getInfo",
"(",
"self",
",",
"CorpNum",
",",
"MgtKeyType",
",",
"MgtKey",
")",
":",
"if",
"MgtKeyType",
"not",
"in",
"self",
".",
"__MgtKeyTypes",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호 형태가 올바르지 않습니다.\")",
"",
"if",
"MgtK... | 상태정보 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
처리결과. consist of code and message
raise
PopbillException | [
"상태정보",
"확인",
"args",
"CorpNum",
":",
"회원",
"사업자",
"번호",
"MgtKeyType",
":",
"관리번호",
"유형",
"one",
"of",
"[",
"SELL",
"BUY",
"TRUSTEE",
"]",
"MgtKey",
":",
"파트너",
"관리번호",
"return",
"처리결과",
".",
"consist",
"of",
"code",
"and",
"message",
"raise",
"Popbill... | python | train | 38.235294 |
gwastro/pycbc-glue | pycbc_glue/iterutils.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/iterutils.py#L337-L386 | def randindex(lo, hi, n = 1.):
"""
Yields integers in the range [lo, hi) where 0 <= lo < hi. Each
return value is a two-element tuple. The first element is the
random integer, the second is the natural logarithm of the
probability with which that integer will be chosen.
The CDF for the distribution from which ... | [
"def",
"randindex",
"(",
"lo",
",",
"hi",
",",
"n",
"=",
"1.",
")",
":",
"if",
"not",
"0",
"<=",
"lo",
"<",
"hi",
":",
"raise",
"ValueError",
"(",
"\"require 0 <= lo < hi: lo = %d, hi = %d\"",
"%",
"(",
"lo",
",",
"hi",
")",
")",
"if",
"n",
"<=",
"... | Yields integers in the range [lo, hi) where 0 <= lo < hi. Each
return value is a two-element tuple. The first element is the
random integer, the second is the natural logarithm of the
probability with which that integer will be chosen.
The CDF for the distribution from which the integers are drawn goes
as [inte... | [
"Yields",
"integers",
"in",
"the",
"range",
"[",
"lo",
"hi",
")",
"where",
"0",
"<",
"=",
"lo",
"<",
"hi",
".",
"Each",
"return",
"value",
"is",
"a",
"two",
"-",
"element",
"tuple",
".",
"The",
"first",
"element",
"is",
"the",
"random",
"integer",
... | python | train | 29.3 |
raphaelgyory/django-rest-messaging-centrifugo | rest_messaging_centrifugo/signals.py | https://github.com/raphaelgyory/django-rest-messaging-centrifugo/blob/f44022cd9fc83e84ab573fe8a8385c85f6e77380/rest_messaging_centrifugo/signals.py#L17-L33 | def publish_message_to_centrifugo(sender, instance, created, **kwargs):
""" Publishes each saved message to Centrifugo. """
if created is True:
client = Client("{0}api/".format(getattr(settings, "CENTRIFUGE_ADDRESS")), getattr(settings, "CENTRIFUGE_SECRET"))
# we ensure the client is still in th... | [
"def",
"publish_message_to_centrifugo",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
"is",
"True",
":",
"client",
"=",
"Client",
"(",
"\"{0}api/\"",
".",
"format",
"(",
"getattr",
"(",
"settings",
",",... | Publishes each saved message to Centrifugo. | [
"Publishes",
"each",
"saved",
"message",
"to",
"Centrifugo",
"."
] | python | train | 61.588235 |
rsgalloway/grit | grit/cmd/cli.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L68-L105 | def checkout(url, version=None):
"""
Checks out latest version of item or repository.
:param url: URL of repo or item to check out.
:param version: Version number to check out.
"""
from grit import Repo
r = Repo(url)
def _write(item):
log.debug('writing: %s' % item.name)
... | [
"def",
"checkout",
"(",
"url",
",",
"version",
"=",
"None",
")",
":",
"from",
"grit",
"import",
"Repo",
"r",
"=",
"Repo",
"(",
"url",
")",
"def",
"_write",
"(",
"item",
")",
":",
"log",
".",
"debug",
"(",
"'writing: %s'",
"%",
"item",
".",
"name",
... | Checks out latest version of item or repository.
:param url: URL of repo or item to check out.
:param version: Version number to check out. | [
"Checks",
"out",
"latest",
"version",
"of",
"item",
"or",
"repository",
"."
] | python | train | 26.815789 |
log2timeline/plaso | plaso/parsers/cups_ipp.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/cups_ipp.py#L162-L182 | def _GetStringValue(self, data_dict, name, default_value=None):
"""Retrieves a specific string value from the data dict.
Args:
data_dict (dict[str, list[str]): values per name.
name (str): name of the value to retrieve.
default_value (Optional[object]): value to return if the name has no valu... | [
"def",
"_GetStringValue",
"(",
"self",
",",
"data_dict",
",",
"name",
",",
"default_value",
"=",
"None",
")",
":",
"values",
"=",
"data_dict",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",
"values",
":",
"return",
"default_value",
"for",
"index... | Retrieves a specific string value from the data dict.
Args:
data_dict (dict[str, list[str]): values per name.
name (str): name of the value to retrieve.
default_value (Optional[object]): value to return if the name has no value
set in data_dict.
Returns:
str: value represente... | [
"Retrieves",
"a",
"specific",
"string",
"value",
"from",
"the",
"data",
"dict",
"."
] | python | train | 29.666667 |
explosion/spaCy | spacy/lang/fa/lex_attrs.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/fa/lex_attrs.py#L84-L101 | def like_num(text):
"""
check if text resembles a number
"""
text = (
text.replace(",", "")
.replace(".", "")
.replace("،", "")
.replace("٫", "")
.replace("/", "")
)
if text.isdigit():
return True
if text in _num_words:
return True
... | [
"def",
"like_num",
"(",
"text",
")",
":",
"text",
"=",
"(",
"text",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"،\",",
" ",
"\")",
"",
".",
"replace",
"(",
"\"٫\",",
" ",... | check if text resembles a number | [
"check",
"if",
"text",
"resembles",
"a",
"number"
] | python | train | 20.333333 |
devision-io/metasdk | metasdk/services/FeedService.py | https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/services/FeedService.py#L87-L97 | def datasource_process(self, datasource_id):
"""
deprecated
Запускает настроенные обработки в фиде
:param datasource_id: uuid
"""
# TODO Выпилить потом класс используется для другого
# TODO без applicationId не выбираются поля сущностей. Подумать на сколько это НЕ... | [
"def",
"datasource_process",
"(",
"self",
",",
"datasource_id",
")",
":",
"# TODO Выпилить потом класс используется для другого",
"# TODO без applicationId не выбираются поля сущностей. Подумать на сколько это НЕ нормально",
"response",
"=",
"self",
".",
"__app",
".",
"native_api_cal... | deprecated
Запускает настроенные обработки в фиде
:param datasource_id: uuid | [
"deprecated",
"Запускает",
"настроенные",
"обработки",
"в",
"фиде",
":",
"param",
"datasource_id",
":",
"uuid"
] | python | train | 52.818182 |
apache/incubator-superset | superset/cli.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L149-L157 | def version(verbose):
"""Prints the current version number"""
print(Fore.BLUE + '-=' * 15)
print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format(
version=config.get('VERSION_STRING')))
print(Fore.BLUE + '-=' * 15)
if verbose:
print('[DB] : ' + '{}'.format(db.engine))
p... | [
"def",
"version",
"(",
"verbose",
")",
":",
"print",
"(",
"Fore",
".",
"BLUE",
"+",
"'-='",
"*",
"15",
")",
"print",
"(",
"Fore",
".",
"YELLOW",
"+",
"'Superset '",
"+",
"Fore",
".",
"CYAN",
"+",
"'{version}'",
".",
"format",
"(",
"version",
"=",
"... | Prints the current version number | [
"Prints",
"the",
"current",
"version",
"number"
] | python | train | 37 |
tasdikrahman/vocabulary | vocabulary/vocabulary.py | https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L329-L353 | def usage_example(phrase, format='json'):
"""Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid... | [
"def",
"usage_example",
"(",
"phrase",
",",
"format",
"=",
"'json'",
")",
":",
"base_url",
"=",
"Vocabulary",
".",
"__get_api_link",
"(",
"\"urbandict\"",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"action",
"=",
"\"define\"",
",",
"word",
"=",
"phra... | Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase | [
"Takes",
"the",
"source",
"phrase",
"and",
"queries",
"it",
"to",
"the",
"urbandictionary",
"API"
] | python | train | 48.32 |
cmheisel/better-project-forecast | better/lib.py | https://github.com/cmheisel/better-project-forecast/blob/9bcba88d70c174ecedec09a020b02ac530bc4734/better/lib.py#L30-L56 | def forecast(self, throughputs, backlog_size, num_simulations=10000, max_periods=10000, seed=None):
"""Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, sto... | [
"def",
"forecast",
"(",
"self",
",",
"throughputs",
",",
"backlog_size",
",",
"num_simulations",
"=",
"10000",
",",
"max_periods",
"=",
"10000",
",",
"seed",
"=",
"None",
")",
":",
"self",
".",
"_check_throughputs",
"(",
"throughputs",
")",
"results",
"=",
... | Forecasts how long a backlog will take to complete given the historical values provided.
Arguments:
throughputs(List[int]): Number of units completed per unit of time (stories per week, story points per month, etc.)
backlog_size(int): Units in the backlog (stories, points, etc.)
... | [
"Forecasts",
"how",
"long",
"a",
"backlog",
"will",
"take",
"to",
"complete",
"given",
"the",
"historical",
"values",
"provided",
".",
"Arguments",
":",
"throughputs",
"(",
"List",
"[",
"int",
"]",
")",
":",
"Number",
"of",
"units",
"completed",
"per",
"un... | python | train | 43.481481 |
RedHatInsights/insights-core | insights/parsers/ps.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/ps.py#L125-L135 | def fuzzy_match(self, proc):
"""
Are there any commands that contain the given text?
Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.
.. note::
'proc' can match anywhere in the command path, name or arguments.
"""
ret... | [
"def",
"fuzzy_match",
"(",
"self",
",",
"proc",
")",
":",
"return",
"any",
"(",
"proc",
"in",
"row",
"[",
"self",
".",
"command_name",
"]",
"for",
"row",
"in",
"self",
".",
"data",
")"
] | Are there any commands that contain the given text?
Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.
.. note::
'proc' can match anywhere in the command path, name or arguments. | [
"Are",
"there",
"any",
"commands",
"that",
"contain",
"the",
"given",
"text?"
] | python | train | 33.636364 |
MeirKriheli/django-bidi-utils | bidiutils/templatetags/bidiutils_tags.py | https://github.com/MeirKriheli/django-bidi-utils/blob/48a8c481fe728fbccf486582999e79454195036e/bidiutils/templatetags/bidiutils_tags.py#L10-L42 | def add_direction(value, arg=u"rtl_only"):
"""Adds direction to the element
:arguments:
arg
* rtl_only: Add the direction only in case of a
right-to-left language (default)
* both: add the direction in both case
* ltr_only: Add the direction only in cas... | [
"def",
"add_direction",
"(",
"value",
",",
"arg",
"=",
"u\"rtl_only\"",
")",
":",
"if",
"arg",
"==",
"u'rtl_only'",
":",
"directions",
"=",
"(",
"u''",
",",
"u'_rtl'",
")",
"elif",
"arg",
"==",
"u'both'",
":",
"directions",
"=",
"(",
"u'_ltr'",
",",
"u... | Adds direction to the element
:arguments:
arg
* rtl_only: Add the direction only in case of a
right-to-left language (default)
* both: add the direction in both case
* ltr_only: Add the direction only in case of a
left-to-right language
{... | [
"Adds",
"direction",
"to",
"the",
"element"
] | python | test | 34.515152 |
ARMmbed/mbed-cloud-sdk-python | scripts/generate_news.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/generate_news.py#L35-L61 | def main():
"""Writes out newsfile if significant version bump"""
last_known = '0'
if os.path.isfile(metafile):
with open(metafile) as fh:
last_known = fh.read()
import mbed_cloud
current = mbed_cloud.__version__
# how significant a change in version scheme should trigger a... | [
"def",
"main",
"(",
")",
":",
"last_known",
"=",
"'0'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"metafile",
")",
":",
"with",
"open",
"(",
"metafile",
")",
"as",
"fh",
":",
"last_known",
"=",
"fh",
".",
"read",
"(",
")",
"import",
"mbed_cloud"... | Writes out newsfile if significant version bump | [
"Writes",
"out",
"newsfile",
"if",
"significant",
"version",
"bump"
] | python | train | 36.407407 |
tensorflow/cleverhans | examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L198-L212 | def find_by_id(self, submission_id):
"""Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found.
"""
return self._attacks.get(
submission_id,
self._defense... | [
"def",
"find_by_id",
"(",
"self",
",",
"submission_id",
")",
":",
"return",
"self",
".",
"_attacks",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_defenses",
".",
"get",
"(",
"submission_id",
",",
"self",
".",
"_targeted_attacks",
".",
"get",
"(",
... | Finds submission by ID.
Args:
submission_id: ID of the submission
Returns:
SubmissionDescriptor with information about submission or None if
submission is not found. | [
"Finds",
"submission",
"by",
"ID",
"."
] | python | train | 26.733333 |
ulfalizer/Kconfiglib | kconfiglib.py | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/kconfiglib.py#L4828-L4868 | def set_value(self, value):
"""
Sets the user value (mode) of the choice. Like for Symbol.set_value(),
the visibility might truncate the value. Choices without the 'optional'
attribute (is_optional) can never be in n mode, but 0/"n" is still
accepted since it's not a malformed va... | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"user_value",
":",
"# We know the value must be valid if it was successfully set",
"# previously",
"self",
".",
"_was_set",
"=",
"True",
"return",
"True",
"if",
"not",
"(",
... | Sets the user value (mode) of the choice. Like for Symbol.set_value(),
the visibility might truncate the value. Choices without the 'optional'
attribute (is_optional) can never be in n mode, but 0/"n" is still
accepted since it's not a malformed value (though it will have no
effect).
... | [
"Sets",
"the",
"user",
"value",
"(",
"mode",
")",
"of",
"the",
"choice",
".",
"Like",
"for",
"Symbol",
".",
"set_value",
"()",
"the",
"visibility",
"might",
"truncate",
"the",
"value",
".",
"Choices",
"without",
"the",
"optional",
"attribute",
"(",
"is_opt... | python | train | 39.95122 |
twisted/axiom | twisted/plugins/axiom_plugins.py | https://github.com/twisted/axiom/blob/7de70bc8fe1bb81f9c2339fba8daec9eb2e92b68/twisted/plugins/axiom_plugins.py#L49-L61 | def makeService(cls, options):
"""
Create an L{IService} for the database specified by the given
configuration.
"""
from axiom.store import Store
jm = options['journal-mode']
if jm is not None:
jm = jm.decode('ascii')
store = Store(options['dbd... | [
"def",
"makeService",
"(",
"cls",
",",
"options",
")",
":",
"from",
"axiom",
".",
"store",
"import",
"Store",
"jm",
"=",
"options",
"[",
"'journal-mode'",
"]",
"if",
"jm",
"is",
"not",
"None",
":",
"jm",
"=",
"jm",
".",
"decode",
"(",
"'ascii'",
")",... | Create an L{IService} for the database specified by the given
configuration. | [
"Create",
"an",
"L",
"{",
"IService",
"}",
"for",
"the",
"database",
"specified",
"by",
"the",
"given",
"configuration",
"."
] | python | train | 36.230769 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/text_problems.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L677-L691 | def text2text_generate_encoded(sample_generator,
vocab,
targets_vocab=None,
has_inputs=True,
inputs_prefix="",
targets_prefix=""):
"""Encode Text2Text samples from... | [
"def",
"text2text_generate_encoded",
"(",
"sample_generator",
",",
"vocab",
",",
"targets_vocab",
"=",
"None",
",",
"has_inputs",
"=",
"True",
",",
"inputs_prefix",
"=",
"\"\"",
",",
"targets_prefix",
"=",
"\"\"",
")",
":",
"targets_vocab",
"=",
"targets_vocab",
... | Encode Text2Text samples from the generator with the vocab. | [
"Encode",
"Text2Text",
"samples",
"from",
"the",
"generator",
"with",
"the",
"vocab",
"."
] | python | train | 46.933333 |
universalcore/unicore.distribute | unicore/distribute/utils.py | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L28-L48 | def get_list(self, section, option):
"""
This allows for loading of Pyramid list style configuration
options:
[foo]
bar =
baz
qux
zap
``get_list('foo', 'bar')`` returns ``['baz', 'qux', 'zap']``
:param str section:
... | [
"def",
"get_list",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"section",
",",
"option",
")",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"(",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
... | This allows for loading of Pyramid list style configuration
options:
[foo]
bar =
baz
qux
zap
``get_list('foo', 'bar')`` returns ``['baz', 'qux', 'zap']``
:param str section:
The section to read.
:param str option:
... | [
"This",
"allows",
"for",
"loading",
"of",
"Pyramid",
"list",
"style",
"configuration",
"options",
":"
] | python | train | 26.190476 |
MacHu-GWU/pathlib_mate-project | pathlib_mate/mate_path_filters.py | https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_path_filters.py#L132-L141 | def n_subfile(self):
"""
Count how many files in this directory (doesn't include files in
sub folders).
"""
self.assert_is_dir_and_exists()
n = 0
for _ in self.select_file(recursive=False):
n += 1
return n | [
"def",
"n_subfile",
"(",
"self",
")",
":",
"self",
".",
"assert_is_dir_and_exists",
"(",
")",
"n",
"=",
"0",
"for",
"_",
"in",
"self",
".",
"select_file",
"(",
"recursive",
"=",
"False",
")",
":",
"n",
"+=",
"1",
"return",
"n"
] | Count how many files in this directory (doesn't include files in
sub folders). | [
"Count",
"how",
"many",
"files",
"in",
"this",
"directory",
"(",
"doesn",
"t",
"include",
"files",
"in",
"sub",
"folders",
")",
"."
] | python | valid | 27.2 |
glormph/msstitch | src/app/writers/pycolator.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/writers/pycolator.py#L4-L37 | def write_percolator_xml(staticxml, feats, fn):
"""Given the static percolator xml root and process info nodes, and all
psms and peptides as iterators in a dict {'peptide': pep_iterator, 'psm':
psm_iterator}, this generates percolator out data into a file."""
# First get xml until psms opening element ... | [
"def",
"write_percolator_xml",
"(",
"staticxml",
",",
"feats",
",",
"fn",
")",
":",
"# First get xml until psms opening element is found.",
"etree",
".",
"SubElement",
"(",
"staticxml",
",",
"'psms'",
")",
".",
"text",
"=",
"'***psms***'",
"root",
"=",
"etree",
".... | Given the static percolator xml root and process info nodes, and all
psms and peptides as iterators in a dict {'peptide': pep_iterator, 'psm':
psm_iterator}, this generates percolator out data into a file. | [
"Given",
"the",
"static",
"percolator",
"xml",
"root",
"and",
"process",
"info",
"nodes",
"and",
"all",
"psms",
"and",
"peptides",
"as",
"iterators",
"in",
"a",
"dict",
"{",
"peptide",
":",
"pep_iterator",
"psm",
":",
"psm_iterator",
"}",
"this",
"generates"... | python | train | 36.176471 |
jxtech/wechatpy | wechatpy/client/api/user.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/user.py#L148-L178 | def get_batch(self, user_list):
"""
批量获取用户基本信息
开发者可通过该接口来批量获取用户基本信息。最多支持一次拉取100条。
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
:param user_list: user_list,支持“使用示例”中两种输入格式
:return: 用户信息的 list
使用示例::
from wechatpy i... | [
"def",
"get_batch",
"(",
"self",
",",
"user_list",
")",
":",
"if",
"all",
"(",
"(",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
"for",
"x",
"in",
"user_list",
")",
")",
":",
"user_list",
"=",
"[",
"{",
"'openid'",
":",
"oid",
"}",... | 批量获取用户基本信息
开发者可通过该接口来批量获取用户基本信息。最多支持一次拉取100条。
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
:param user_list: user_list,支持“使用示例”中两种输入格式
:return: 用户信息的 list
使用示例::
from wechatpy import WeChatClient
client = WeChatClien... | [
"批量获取用户基本信息",
"开发者可通过该接口来批量获取用户基本信息。最多支持一次拉取100条。"
] | python | train | 29.967742 |
jeffknupp/sandman | sandman/model/utils.py | https://github.com/jeffknupp/sandman/blob/253ea4d15cbccd9f0016d66fedd7478614cc0b2f/sandman/model/utils.py#L46-L63 | def add_pk_if_required(db, table, name):
"""Return a class deriving from our Model class as well as the SQLAlchemy
model.
:param `sqlalchemy.schema.Table` table: table to create primary key for
:param table: table to create primary key for
"""
db.metadata.reflect(bind=db.engine)
cls_dict ... | [
"def",
"add_pk_if_required",
"(",
"db",
",",
"table",
",",
"name",
")",
":",
"db",
".",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"db",
".",
"engine",
")",
"cls_dict",
"=",
"{",
"'__tablename__'",
":",
"name",
"}",
"if",
"not",
"table",
".",
"pri... | Return a class deriving from our Model class as well as the SQLAlchemy
model.
:param `sqlalchemy.schema.Table` table: table to create primary key for
:param table: table to create primary key for | [
"Return",
"a",
"class",
"deriving",
"from",
"our",
"Model",
"class",
"as",
"well",
"as",
"the",
"SQLAlchemy",
"model",
"."
] | python | train | 36.333333 |
stevepeak/tornpsql | tornpsql/__init__.py | https://github.com/stevepeak/tornpsql/blob/a109d0f95d6432d0e3b5eba1c9854357ba527f27/tornpsql/__init__.py#L145-L148 | def _reregister_types(self):
"""Registers existing types for a new connection"""
for _type in self._register_types:
psycopg2.extensions.register_type(psycopg2.extensions.new_type(*_type)) | [
"def",
"_reregister_types",
"(",
"self",
")",
":",
"for",
"_type",
"in",
"self",
".",
"_register_types",
":",
"psycopg2",
".",
"extensions",
".",
"register_type",
"(",
"psycopg2",
".",
"extensions",
".",
"new_type",
"(",
"*",
"_type",
")",
")"
] | Registers existing types for a new connection | [
"Registers",
"existing",
"types",
"for",
"a",
"new",
"connection"
] | python | train | 53 |
Unidata/MetPy | metpy/io/nexrad.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/io/nexrad.py#L652-L657 | def reduce_lists(d):
"""Replace single item lists in a dictionary with the single item."""
for field in d:
old_data = d[field]
if len(old_data) == 1:
d[field] = old_data[0] | [
"def",
"reduce_lists",
"(",
"d",
")",
":",
"for",
"field",
"in",
"d",
":",
"old_data",
"=",
"d",
"[",
"field",
"]",
"if",
"len",
"(",
"old_data",
")",
"==",
"1",
":",
"d",
"[",
"field",
"]",
"=",
"old_data",
"[",
"0",
"]"
] | Replace single item lists in a dictionary with the single item. | [
"Replace",
"single",
"item",
"lists",
"in",
"a",
"dictionary",
"with",
"the",
"single",
"item",
"."
] | python | train | 33.833333 |
ageitgey/face_recognition | face_recognition/api.py | https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/face_recognition/api.py#L135-L151 | def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128):
"""
Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector
If you are using a GPU, this can give you much faster results since the GPU
can process batches of images at once. If you aren'... | [
"def",
"batch_face_locations",
"(",
"images",
",",
"number_of_times_to_upsample",
"=",
"1",
",",
"batch_size",
"=",
"128",
")",
":",
"def",
"convert_cnn_detections_to_css",
"(",
"detections",
")",
":",
"return",
"[",
"_trim_css_to_bounds",
"(",
"_rect_to_css",
"(",
... | Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector
If you are using a GPU, this can give you much faster results since the GPU
can process batches of images at once. If you aren't using a GPU, you don't need this function.
:param img: A list of images (each as a num... | [
"Returns",
"an",
"2d",
"array",
"of",
"bounding",
"boxes",
"of",
"human",
"faces",
"in",
"a",
"image",
"using",
"the",
"cnn",
"face",
"detector",
"If",
"you",
"are",
"using",
"a",
"GPU",
"this",
"can",
"give",
"you",
"much",
"faster",
"results",
"since",... | python | train | 62.117647 |
foremast/foremast | src/foremast/elb/create_elb.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/elb/create_elb.py#L220-L276 | def configure_attributes(self, json_data):
"""Configure load balancer attributes such as idle timeout, connection draining, etc
Args:
json_data (json): return data from ELB upsert
"""
env = boto3.session.Session(profile_name=self.env, region_name=self.region)
elbclie... | [
"def",
"configure_attributes",
"(",
"self",
",",
"json_data",
")",
":",
"env",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"profile_name",
"=",
"self",
".",
"env",
",",
"region_name",
"=",
"self",
".",
"region",
")",
"elbclient",
"=",
"env",
".",
... | Configure load balancer attributes such as idle timeout, connection draining, etc
Args:
json_data (json): return data from ELB upsert | [
"Configure",
"load",
"balancer",
"attributes",
"such",
"as",
"idle",
"timeout",
"connection",
"draining",
"etc"
] | python | train | 50.45614 |
sphinx-gallery/sphinx-gallery | sphinx_gallery/py_source_parser.py | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/py_source_parser.py#L124-L144 | def extract_file_config(content):
"""
Pull out the file-specific config specified in the docstring.
"""
prop_pat = re.compile(
r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$",
re.MULTILINE)
file_conf = {}
for match in re.finditer(prop_pat, content):
name = match... | [
"def",
"extract_file_config",
"(",
"content",
")",
":",
"prop_pat",
"=",
"re",
".",
"compile",
"(",
"r\"^\\s*#\\s*sphinx_gallery_([A-Za-z0-9_]+)\\s*=\\s*(.+)\\s*$\"",
",",
"re",
".",
"MULTILINE",
")",
"file_conf",
"=",
"{",
"}",
"for",
"match",
"in",
"re",
".",
... | Pull out the file-specific config specified in the docstring. | [
"Pull",
"out",
"the",
"file",
"-",
"specific",
"config",
"specified",
"in",
"the",
"docstring",
"."
] | python | train | 30.428571 |
saltstack/salt | salt/modules/pkgng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgng.py#L1326-L1407 | def check(jail=None,
chroot=None,
root=None,
depends=False,
recompute=False,
checksum=False):
'''
Sanity checks installed packages
jail
Perform the sanity check in the specified jail
CLI Example:
.. code-block:: bash
s... | [
"def",
"check",
"(",
"jail",
"=",
"None",
",",
"chroot",
"=",
"None",
",",
"root",
"=",
"None",
",",
"depends",
"=",
"False",
",",
"recompute",
"=",
"False",
",",
"checksum",
"=",
"False",
")",
":",
"if",
"not",
"any",
"(",
"(",
"depends",
",",
"... | Sanity checks installed packages
jail
Perform the sanity check in the specified jail
CLI Example:
.. code-block:: bash
salt '*' pkg.check jail=<jail name or id>
chroot
Perform the sanity check in the specified chroot (ignored if ``jail``
is specified)
... | [
"Sanity",
"checks",
"installed",
"packages"
] | python | train | 20.02439 |
googleapis/oauth2client | oauth2client/contrib/sqlalchemy.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/sqlalchemy.py#L154-L168 | def locked_put(self, credentials):
"""Write a credentials to the SQLAlchemy datastore.
Args:
credentials: :class:`oauth2client.Credentials`
"""
filters = {self.key_name: self.key_value}
query = self.session.query(self.model_class).filter_by(**filters)
entity ... | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"filters",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"query",
"=",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model_class",
")",
".",
"filter_by"... | Write a credentials to the SQLAlchemy datastore.
Args:
credentials: :class:`oauth2client.Credentials` | [
"Write",
"a",
"credentials",
"to",
"the",
"SQLAlchemy",
"datastore",
"."
] | python | valid | 32.333333 |
geopy/geopy | geopy/geocoders/geonames.py | https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/geocoders/geonames.py#L195-L296 | def reverse(
self,
query,
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
feature_code=None,
lang=None,
find_nearby_type='findNearbyPlaceName',
):
"""
Return an address by location point.
.. vers... | [
"def",
"reverse",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"DEFAULT_SENTINEL",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
"feature_code",
"=",
"None",
",",
"lang",
"=",
"None",
",",
"find_nearby_type",
"=",
"'findNearbyPlaceName'",
",",
")",
":",... | Return an address by location point.
.. versionadded:: 1.2.0
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latit... | [
"Return",
"an",
"address",
"by",
"location",
"point",
"."
] | python | train | 39.686275 |
mensi/gittornado | gittornado/__init__.py | https://github.com/mensi/gittornado/blob/adf86b5537064337c806cce0e71eacaabc8bb610/gittornado/__init__.py#L71-L77 | def check_auth(self):
"""Check authentication/authorization of client"""
# access permissions
if self.auth is not None:
return self.auth(self.request)
return self.public_readble, self.public_writable | [
"def",
"check_auth",
"(",
"self",
")",
":",
"# access permissions",
"if",
"self",
".",
"auth",
"is",
"not",
"None",
":",
"return",
"self",
".",
"auth",
"(",
"self",
".",
"request",
")",
"return",
"self",
".",
"public_readble",
",",
"self",
".",
"public_w... | Check authentication/authorization of client | [
"Check",
"authentication",
"/",
"authorization",
"of",
"client"
] | python | train | 34 |
bitesofcode/projex | projex/enum.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/enum.py#L139-L160 | def displayText(self, value, blank='', joiner=', '):
"""
Returns the display text for the value associated with
the inputted text. This will result in a comma separated
list of labels for the value, or the blank text provided if
no text is found.
:param val... | [
"def",
"displayText",
"(",
"self",
",",
"value",
",",
"blank",
"=",
"''",
",",
"joiner",
"=",
"', '",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"''",
"labels",
"=",
"[",
"]",
"for",
"key",
",",
"my_value",
"in",
"sorted",
"(",
"self",
... | Returns the display text for the value associated with
the inputted text. This will result in a comma separated
list of labels for the value, or the blank text provided if
no text is found.
:param value | <variant>
blank | <str>
jo... | [
"Returns",
"the",
"display",
"text",
"for",
"the",
"value",
"associated",
"with",
"the",
"inputted",
"text",
".",
"This",
"will",
"result",
"in",
"a",
"comma",
"separated",
"list",
"of",
"labels",
"for",
"the",
"value",
"or",
"the",
"blank",
"text",
"provi... | python | train | 32.954545 |
saltstack/salt | salt/returners/highstate_return.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/highstate_return.py#L272-L280 | def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out) | [
"def",
"_generate_html",
"(",
"data",
",",
"out",
")",
":",
"print",
"(",
"'<html>'",
",",
"file",
"=",
"out",
")",
"print",
"(",
"'<body>'",
",",
"file",
"=",
"out",
")",
"_generate_html_table",
"(",
"data",
",",
"out",
",",
"0",
")",
"print",
"(",
... | Generate report data as HTML | [
"Generate",
"report",
"data",
"as",
"HTML"
] | python | train | 25.777778 |
idlesign/uwsgiconf | uwsgiconf/options/routing_routers.py | https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/options/routing_routers.py#L929-L962 | def device_add_rule(self, direction, action, src, dst, target=None):
"""Adds a tuntap device rule.
To be used in a vassal.
:param str|unicode direction: Direction:
* in
* out.
:param str|unicode action: Action:
* allow
* deny
... | [
"def",
"device_add_rule",
"(",
"self",
",",
"direction",
",",
"action",
",",
"src",
",",
"dst",
",",
"target",
"=",
"None",
")",
":",
"value",
"=",
"[",
"direction",
",",
"src",
",",
"dst",
",",
"action",
"]",
"if",
"target",
":",
"value",
".",
"ap... | Adds a tuntap device rule.
To be used in a vassal.
:param str|unicode direction: Direction:
* in
* out.
:param str|unicode action: Action:
* allow
* deny
* route
* gateway.
:param str|unicode src: Source/mask.
... | [
"Adds",
"a",
"tuntap",
"device",
"rule",
"."
] | python | train | 21.323529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.