Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
ManagementUtility.autocomplete | (self) |
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
... |
Output completion suggestions for BASH. | def autocomplete(self):
"""
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BA... | [
"def",
"autocomplete",
"(",
"self",
")",
":",
"# Don't complete if user hasn't sourced bash_completion file.",
"if",
"'DJANGO_AUTO_COMPLETE'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"cwords",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
".",
"spli... | [
207,
4
] | [
280,
19
] | python | en | ['en', 'error', 'th'] | False |
ManagementUtility.execute | (self) |
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
|
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
| def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
"""
try:
subcommand = self.argv[1]
except IndexError:
subcommand = 'help' # Display... | [
"def",
"execute",
"(",
"self",
")",
":",
"try",
":",
"subcommand",
"=",
"self",
".",
"argv",
"[",
"1",
"]",
"except",
"IndexError",
":",
"subcommand",
"=",
"'help'",
"# Display help if no arguments were given.",
"# Preprocess options to extract --settings and --pythonpa... | [
282,
4
] | [
354,
67
] | python | en | ['en', 'error', 'th'] | False |
sendfile | (request, filename, **kwargs) |
Dummy sendfile backend implementation.
|
Dummy sendfile backend implementation.
| def sendfile(request, filename, **kwargs):
"""
Dummy sendfile backend implementation.
"""
return HttpResponse('Dummy backend response') | [
"def",
"sendfile",
"(",
"request",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"HttpResponse",
"(",
"'Dummy backend response'",
")"
] | [
3,
0
] | [
7,
49
] | python | en | ['en', 'error', 'th'] | False |
localize | (value) |
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
|
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
| def localize(value):
"""
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
"""
return force_text(formats.localize(value, use_l10n=True)) | [
"def",
"localize",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"formats",
".",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"True",
")",
")"
] | [
8,
0
] | [
13,
61
] | python | en | ['en', 'error', 'th'] | False |
unlocalize | (value) |
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
|
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
| def unlocalize(value):
"""
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
"""
return force_text(value) | [
"def",
"unlocalize",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"value",
")"
] | [
17,
0
] | [
22,
28
] | python | en | ['en', 'error', 'th'] | False |
localize_tag | (parser, token) |
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`.
Sample usage::
{% localize off %}
var pi = {{ 3.1415 }};
{% endlocalize %}
|
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`. | def localize_tag(parser, token):
"""
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`.
Sample usage::
{% localize off %}
var pi = {{ 3.1415 }};
{% endlocalize %}
"""
use_l10n = None
bits = list(token.split_contents())
... | [
"def",
"localize_tag",
"(",
"parser",
",",
"token",
")",
":",
"use_l10n",
"=",
"None",
"bits",
"=",
"list",
"(",
"token",
".",
"split_contents",
"(",
")",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"use_l10n",
"=",
"True",
"elif",
"len",
"... | [
42,
0
] | [
63,
43
] | python | en | ['en', 'error', 'th'] | False |
Envelope.__init__ | (self, *args) |
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
|
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
| def __init__(self, *args):
"""
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
"""
if len(args) == 1:
if isinstance(args[0], OGREnvelope):
# OGREnvelope (a ctypes Structure) was passed... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"OGREnvelope",
")",
":",
"# OGREnvelope (a ctypes Structure) was passed in.",
"self",
".",
"_e... | [
36,
4
] | [
65,
66
] | python | en | ['en', 'error', 'th'] | False |
Envelope.__eq__ | (self, other) |
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
|
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
| def __eq__(self, other):
"""
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
"""
if isinstance(other, Envelope):
return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \
(self.max_x == ... | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Envelope",
")",
":",
"return",
"(",
"self",
".",
"min_x",
"==",
"other",
".",
"min_x",
")",
"and",
"(",
"self",
".",
"min_y",
"==",
"other",
".",
"min_y",... | [
67,
4
] | [
79,
87
] | python | en | ['en', 'error', 'th'] | False |
Envelope.__str__ | (self) | Returns a string representation of the tuple. | Returns a string representation of the tuple. | def __str__(self):
"Returns a string representation of the tuple."
return str(self.tuple) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"tuple",
")"
] | [
81,
4
] | [
83,
30
] | python | en | ['en', 'en', 'en'] | True |
Envelope._from_sequence | (self, seq) | Initializes the C OGR Envelope structure from the given sequence. | Initializes the C OGR Envelope structure from the given sequence. | def _from_sequence(self, seq):
"Initializes the C OGR Envelope structure from the given sequence."
self._envelope = OGREnvelope()
self._envelope.MinX = seq[0]
self._envelope.MinY = seq[1]
self._envelope.MaxX = seq[2]
self._envelope.MaxY = seq[3] | [
"def",
"_from_sequence",
"(",
"self",
",",
"seq",
")",
":",
"self",
".",
"_envelope",
"=",
"OGREnvelope",
"(",
")",
"self",
".",
"_envelope",
".",
"MinX",
"=",
"seq",
"[",
"0",
"]",
"self",
".",
"_envelope",
".",
"MinY",
"=",
"seq",
"[",
"1",
"]",
... | [
85,
4
] | [
91,
36
] | python | en | ['en', 'en', 'en'] | True |
Envelope.expand_to_include | (self, *args) |
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
|
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
| def expand_to_include(self, *args):
"""
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
"""
# We provide a number of different signatures for this method,
# and the logic here is all ab... | [
"def",
"expand_to_include",
"(",
"self",
",",
"*",
"args",
")",
":",
"# We provide a number of different signatures for this method,",
"# and the logic here is all about converting them into a",
"# 4-tuple single parameter which does the actual work of",
"# expanding the envelope.",
"if",
... | [
93,
4
] | [
133,
85
] | python | en | ['en', 'error', 'th'] | False |
Envelope.min_x | (self) | Returns the value of the minimum X coordinate. | Returns the value of the minimum X coordinate. | def min_x(self):
"Returns the value of the minimum X coordinate."
return self._envelope.MinX | [
"def",
"min_x",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MinX"
] | [
136,
4
] | [
138,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.min_y | (self) | Returns the value of the minimum Y coordinate. | Returns the value of the minimum Y coordinate. | def min_y(self):
"Returns the value of the minimum Y coordinate."
return self._envelope.MinY | [
"def",
"min_y",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MinY"
] | [
141,
4
] | [
143,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.max_x | (self) | Returns the value of the maximum X coordinate. | Returns the value of the maximum X coordinate. | def max_x(self):
"Returns the value of the maximum X coordinate."
return self._envelope.MaxX | [
"def",
"max_x",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MaxX"
] | [
146,
4
] | [
148,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.max_y | (self) | Returns the value of the maximum Y coordinate. | Returns the value of the maximum Y coordinate. | def max_y(self):
"Returns the value of the maximum Y coordinate."
return self._envelope.MaxY | [
"def",
"max_y",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MaxY"
] | [
151,
4
] | [
153,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.ur | (self) | Returns the upper-right coordinate. | Returns the upper-right coordinate. | def ur(self):
"Returns the upper-right coordinate."
return (self.max_x, self.max_y) | [
"def",
"ur",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
")"
] | [
156,
4
] | [
158,
39
] | python | en | ['en', 'en', 'en'] | True |
Envelope.ll | (self) | Returns the lower-left coordinate. | Returns the lower-left coordinate. | def ll(self):
"Returns the lower-left coordinate."
return (self.min_x, self.min_y) | [
"def",
"ll",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
")"
] | [
161,
4
] | [
163,
39
] | python | en | ['en', 'en', 'en'] | True |
Envelope.tuple | (self) | Returns a tuple representing the envelope. | Returns a tuple representing the envelope. | def tuple(self):
"Returns a tuple representing the envelope."
return (self.min_x, self.min_y, self.max_x, self.max_y) | [
"def",
"tuple",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
")"
] | [
166,
4
] | [
168,
63
] | python | en | ['en', 'en', 'en'] | True |
Envelope.wkt | (self) | Returns WKT representing a Polygon for this envelope. | Returns WKT representing a Polygon for this envelope. | def wkt(self):
"Returns WKT representing a Polygon for this envelope."
# TODO: Fix significant figures.
return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \
(self.min_x, self.min_y, self.min_x, self.max_y,
self.max_x, self.max_y, self.max_x, self.min_y,
... | [
"def",
"wkt",
"(",
"self",
")",
":",
"# TODO: Fix significant figures.",
"return",
"'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))'",
"%",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"min_x",
",",
"self",
".",
"max_y",
",",
"self",
".",
... | [
171,
4
] | [
177,
39
] | python | en | ['en', 'en', 'en'] | True |
_wrapper | (args=None) | Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer every time an entrypoint gets
moved.
To alleviate this pain, and... | Central wrapper for all old entrypoints. | def _wrapper(args=None):
# type: (Optional[List[str]]) -> int
"""Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer ... | [
"def",
"_wrapper",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING: pip is being invoked by an old script wrapper. This will \"",
"\"fail in a future version of pip.\\n\"",
"\"Please see https://github.... | [
9,
0
] | [
30,
21
] | python | en | ['en', 'en', 'en'] | True |
sunpower_fetch | (sunpower_monitor) | Basic data fetch routine to get and reformat sunpower data to a dict of device type and serial # | Basic data fetch routine to get and reformat sunpower data to a dict of device type and serial # | def sunpower_fetch(sunpower_monitor):
"""Basic data fetch routine to get and reformat sunpower data to a dict of device type and serial #"""
try:
sunpower_data = sunpower_monitor.device_list()
_LOGGER.info("got data %s", sunpower_data)
data = {}
# Convert data into indexable form... | [
"def",
"sunpower_fetch",
"(",
"sunpower_monitor",
")",
":",
"try",
":",
"sunpower_data",
"=",
"sunpower_monitor",
".",
"device_list",
"(",
")",
"_LOGGER",
".",
"info",
"(",
"\"got data %s\"",
",",
"sunpower_data",
")",
"data",
"=",
"{",
"}",
"# Convert data into... | [
32,
0
] | [
46,
37
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Set up the sunpower component. | Set up the sunpower component. | async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the sunpower component."""
hass.data.setdefault(DOMAIN, {})
conf = config.get(DOMAIN)
if not conf:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"... | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"conf",
"=",
"config",
".",
"get",
"(",
"DOMAIN",
")",
"if",
"not",
"... | [
49,
0
] | [
64,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up sunpower from a config entry. | Set up sunpower from a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up sunpower from a config entry."""
entry_id = entry.entry_id
hass.data[DOMAIN].setdefault(entry_id, {})
sunpower_monitor = SunPowerMonitor(entry.data[SUNPOWER_HOST])
async def async_update_data():
"""Fetch data f... | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"entry_id",
"=",
"entry",
".",
"entry_id",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"setdefault",
"(",
"entry_id",
",",
"{",
"}",
")"... | [
67,
0
] | [
106,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistant, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
... | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload... | [
109,
0
] | [
122,
20
] | python | en | ['en', 'es', 'en'] | True |
TestBlockStore.test_deadlock | (self) |
This test was added because the store was deadlocking in certain situations, when fetching and
adding blocks repeatedly. The issue was patched.
|
This test was added because the store was deadlocking in certain situations, when fetching and
adding blocks repeatedly. The issue was patched.
| async def test_deadlock(self):
"""
This test was added because the store was deadlocking in certain situations, when fetching and
adding blocks repeatedly. The issue was patched.
"""
blocks = bt.get_consecutive_blocks(10)
db_filename = Path("blockchain_test.db")
d... | [
"async",
"def",
"test_deadlock",
"(",
"self",
")",
":",
"blocks",
"=",
"bt",
".",
"get_consecutive_blocks",
"(",
"10",
")",
"db_filename",
"=",
"Path",
"(",
"\"blockchain_test.db\"",
")",
"db_filename_2",
"=",
"Path",
"(",
"\"blockchain_test2.db\"",
")",
"if",
... | [
85,
4
] | [
128,
30
] | python | en | ['en', 'error', 'th'] | False |
_get_all_permissions | (opts) |
Returns (codename, name) for all permissions in the given opts.
|
Returns (codename, name) for all permissions in the given opts.
| def _get_all_permissions(opts):
"""
Returns (codename, name) for all permissions in the given opts.
"""
builtin = _get_builtin_permissions(opts)
custom = list(opts.permissions)
return builtin + custom | [
"def",
"_get_all_permissions",
"(",
"opts",
")",
":",
"builtin",
"=",
"_get_builtin_permissions",
"(",
"opts",
")",
"custom",
"=",
"list",
"(",
"opts",
".",
"permissions",
")",
"return",
"builtin",
"+",
"custom"
] | [
16,
0
] | [
22,
27
] | python | en | ['en', 'error', 'th'] | False |
_get_builtin_permissions | (opts) |
Returns (codename, name) for all autogenerated permissions.
By default, this is ('add', 'change', 'delete')
|
Returns (codename, name) for all autogenerated permissions.
By default, this is ('add', 'change', 'delete')
| def _get_builtin_permissions(opts):
"""
Returns (codename, name) for all autogenerated permissions.
By default, this is ('add', 'change', 'delete')
"""
perms = []
for action in opts.default_permissions:
perms.append((
get_permission_codename(action, opts),
'Can %s... | [
"def",
"_get_builtin_permissions",
"(",
"opts",
")",
":",
"perms",
"=",
"[",
"]",
"for",
"action",
"in",
"opts",
".",
"default_permissions",
":",
"perms",
".",
"append",
"(",
"(",
"get_permission_codename",
"(",
"action",
",",
"opts",
")",
",",
"'Can %s %s'"... | [
25,
0
] | [
36,
16
] | python | en | ['en', 'error', 'th'] | False |
get_system_username | () |
Try to determine the current system user's username.
:returns: The username as a unicode string, or an empty string if the
username could not be determined.
|
Try to determine the current system user's username. | def get_system_username():
"""
Try to determine the current system user's username.
:returns: The username as a unicode string, or an empty string if the
username could not be determined.
"""
try:
result = getpass.getuser()
except (ImportError, KeyError):
# KeyError will... | [
"def",
"get_system_username",
"(",
")",
":",
"try",
":",
"result",
"=",
"getpass",
".",
"getuser",
"(",
")",
"except",
"(",
"ImportError",
",",
"KeyError",
")",
":",
"# KeyError will be raised by os.getpwuid() (called by getuser())",
"# if there is no corresponding entry ... | [
88,
0
] | [
108,
17
] | python | en | ['en', 'error', 'th'] | False |
get_default_username | (check_db=True) |
Try to determine the current system user's username to use as a default.
:param check_db: If ``True``, requires that the username does not match an
existing ``auth.User`` (otherwise returns an empty string).
:returns: The username, or an empty string if no username can be
determined.
|
Try to determine the current system user's username to use as a default. | def get_default_username(check_db=True):
"""
Try to determine the current system user's username to use as a default.
:param check_db: If ``True``, requires that the username does not match an
existing ``auth.User`` (otherwise returns an empty string).
:returns: The username, or an empty string... | [
"def",
"get_default_username",
"(",
"check_db",
"=",
"True",
")",
":",
"# This file is used in apps.py, it should not trigger models import.",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"models",
"as",
"auth_app",
"# If the User model has been swapped out, we can'... | [
111,
0
] | [
152,
27
] | python | en | ['en', 'error', 'th'] | False |
debugError | (_logger: logging.Logger, msg: Any) | Log error messages. | Log error messages. | def debugError(_logger: logging.Logger, msg: Any) -> None:
"""Log error messages."""
if pyppeteer.DEBUG:
_logger.error(msg)
else:
_logger.debug(msg) | [
"def",
"debugError",
"(",
"_logger",
":",
"logging",
".",
"Logger",
",",
"msg",
":",
"Any",
")",
"->",
"None",
":",
"if",
"pyppeteer",
".",
"DEBUG",
":",
"_logger",
".",
"error",
"(",
"msg",
")",
"else",
":",
"_logger",
".",
"debug",
"(",
"msg",
")... | [
20,
0
] | [
25,
26
] | python | da | ['da', 'da', 'en'] | True |
evaluationString | (fun: str, *args: Any) | Convert function and arguments to str. | Convert function and arguments to str. | def evaluationString(fun: str, *args: Any) -> str:
"""Convert function and arguments to str."""
_args = ', '.join([
json.dumps('undefined' if arg is None else arg) for arg in args
])
expr = f'({fun})({_args})'
return expr | [
"def",
"evaluationString",
"(",
"fun",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"str",
":",
"_args",
"=",
"', '",
".",
"join",
"(",
"[",
"json",
".",
"dumps",
"(",
"'undefined'",
"if",
"arg",
"is",
"None",
"else",
"arg",
")",
"for",
"... | [
28,
0
] | [
34,
15
] | python | en | ['en', 'en', 'en'] | True |
getExceptionMessage | (exceptionDetails: dict) | Get exception message from `exceptionDetails` object. | Get exception message from `exceptionDetails` object. | def getExceptionMessage(exceptionDetails: dict) -> str:
"""Get exception message from `exceptionDetails` object."""
exception = exceptionDetails.get('exception')
if exception:
return exception.get('description') or exception.get('value')
message = exceptionDetails.get('text', '')
stackTrace ... | [
"def",
"getExceptionMessage",
"(",
"exceptionDetails",
":",
"dict",
")",
"->",
"str",
":",
"exception",
"=",
"exceptionDetails",
".",
"get",
"(",
"'exception'",
")",
"if",
"exception",
":",
"return",
"exception",
".",
"get",
"(",
"'description'",
")",
"or",
... | [
37,
0
] | [
53,
18
] | python | en | ['en', 'en', 'en'] | True |
addEventListener | (emitter: EventEmitter, eventName: str, handler: Callable
) | Add handler to the emitter and return emitter/handler. | Add handler to the emitter and return emitter/handler. | def addEventListener(emitter: EventEmitter, eventName: str, handler: Callable
) -> Dict[str, Any]:
"""Add handler to the emitter and return emitter/handler."""
emitter.on(eventName, handler)
return {'emitter': emitter, 'eventName': eventName, 'handler': handler} | [
"def",
"addEventListener",
"(",
"emitter",
":",
"EventEmitter",
",",
"eventName",
":",
"str",
",",
"handler",
":",
"Callable",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"emitter",
".",
"on",
"(",
"eventName",
",",
"handler",
")",
"return",
"... | [
56,
0
] | [
60,
75
] | python | en | ['en', 'no', 'en'] | True |
removeEventListeners | (listeners: List[dict]) | Remove listeners from emitter. | Remove listeners from emitter. | def removeEventListeners(listeners: List[dict]) -> None:
"""Remove listeners from emitter."""
for listener in listeners:
emitter = listener['emitter']
eventName = listener['eventName']
handler = listener['handler']
emitter.remove_listener(eventName, handler)
listeners.clear() | [
"def",
"removeEventListeners",
"(",
"listeners",
":",
"List",
"[",
"dict",
"]",
")",
"->",
"None",
":",
"for",
"listener",
"in",
"listeners",
":",
"emitter",
"=",
"listener",
"[",
"'emitter'",
"]",
"eventName",
"=",
"listener",
"[",
"'eventName'",
"]",
"ha... | [
63,
0
] | [
70,
21
] | python | en | ['en', 'en', 'en'] | True |
valueFromRemoteObject | (remoteObject: Dict) | Serialize value of remote object. | Serialize value of remote object. | def valueFromRemoteObject(remoteObject: Dict) -> Any:
"""Serialize value of remote object."""
if remoteObject.get('objectId'):
raise ElementHandleError('Cannot extract value when objectId is given')
value = remoteObject.get('unserializableValue')
if value:
if value == '-0':
r... | [
"def",
"valueFromRemoteObject",
"(",
"remoteObject",
":",
"Dict",
")",
"->",
"Any",
":",
"if",
"remoteObject",
".",
"get",
"(",
"'objectId'",
")",
":",
"raise",
"ElementHandleError",
"(",
"'Cannot extract value when objectId is given'",
")",
"value",
"=",
"remoteObj... | [
82,
0
] | [
99,
36
] | python | en | ['en', 'en', 'en'] | True |
releaseObject | (client: CDPSession, remoteObject: dict
) | Release remote object. | Release remote object. | def releaseObject(client: CDPSession, remoteObject: dict
) -> Awaitable:
"""Release remote object."""
objectId = remoteObject.get('objectId')
fut_none = client._loop.create_future()
fut_none.set_result(None)
if not objectId:
return fut_none
try:
return client.se... | [
"def",
"releaseObject",
"(",
"client",
":",
"CDPSession",
",",
"remoteObject",
":",
"dict",
")",
"->",
"Awaitable",
":",
"objectId",
"=",
"remoteObject",
".",
"get",
"(",
"'objectId'",
")",
"fut_none",
"=",
"client",
".",
"_loop",
".",
"create_future",
"(",
... | [
102,
0
] | [
118,
19
] | python | en | ['en', 'en', 'en'] | True |
waitForEvent | (emitter: EventEmitter, eventName: str, # noqa: C901
predicate: Callable[[Any], bool], timeout: float,
loop: asyncio.AbstractEventLoop) | Wait for an event emitted from the emitter. | Wait for an event emitted from the emitter. | def waitForEvent(emitter: EventEmitter, eventName: str, # noqa: C901
predicate: Callable[[Any], bool], timeout: float,
loop: asyncio.AbstractEventLoop) -> Awaitable:
"""Wait for an event emitted from the emitter."""
promise = loop.create_future()
def resolveCallback(targe... | [
"def",
"waitForEvent",
"(",
"emitter",
":",
"EventEmitter",
",",
"eventName",
":",
"str",
",",
"# noqa: C901",
"predicate",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"bool",
"]",
",",
"timeout",
":",
"float",
",",
"loop",
":",
"asyncio",
".",
"Abstract... | [
121,
0
] | [
153,
18
] | python | en | ['en', 'en', 'en'] | True |
get_positive_int | (obj: dict, name: str) | Get and check the value of name in obj is positive integer. | Get and check the value of name in obj is positive integer. | def get_positive_int(obj: dict, name: str) -> int:
"""Get and check the value of name in obj is positive integer."""
value = obj[name]
if not isinstance(value, int):
raise TypeError(
f'{name} must be integer: {type(value)}')
elif value < 0:
raise ValueError(
f'{na... | [
"def",
"get_positive_int",
"(",
"obj",
":",
"dict",
",",
"name",
":",
"str",
")",
"->",
"int",
":",
"value",
"=",
"obj",
"[",
"name",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"f'{name} must be integ... | [
156,
0
] | [
165,
16
] | python | en | ['en', 'en', 'en'] | True |
is_jsfunc | (func: str) | Heuristically check function or expression. | Heuristically check function or expression. | def is_jsfunc(func: str) -> bool: # not in puppeteer
"""Heuristically check function or expression."""
func = func.strip()
if func.startswith('function') or func.startswith('async '):
return True
elif '=>' in func:
return True
return False | [
"def",
"is_jsfunc",
"(",
"func",
":",
"str",
")",
"->",
"bool",
":",
"# not in puppeteer",
"func",
"=",
"func",
".",
"strip",
"(",
")",
"if",
"func",
".",
"startswith",
"(",
"'function'",
")",
"or",
"func",
".",
"startswith",
"(",
"'async '",
")",
":",... | [
168,
0
] | [
175,
16
] | python | en | ['en', 'en', 'en'] | True |
all_views | () |
returns a set of all views in the app
|
returns a set of all views in the app
| def all_views():
"""
returns a set of all views in the app
"""
patterns = set()
url_views = set()
# Add recursive URL patterns
unprocessed = set(api_patterns)
while unprocessed:
to_process = unprocessed.copy()
unprocessed = set()
for pattern in to_process:
... | [
"def",
"all_views",
"(",
")",
":",
"patterns",
"=",
"set",
"(",
")",
"url_views",
"=",
"set",
"(",
")",
"# Add recursive URL patterns",
"unprocessed",
"=",
"set",
"(",
"api_patterns",
")",
"while",
"unprocessed",
":",
"to_process",
"=",
"unprocessed",
".",
"... | [
24,
0
] | [
47,
20
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection.host | (self) |
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In add... |
Getter method to remove any trailing dots that indicate the hostname is an FQDN. | def host(self):
"""
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name th... | [
"def",
"host",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dns_host",
".",
"rstrip",
"(",
"\".\"",
")"
] | [
127,
4
] | [
143,
41
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection.host | (self, value) |
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
|
Setter for the `host` property. | def host(self, value):
"""
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
"""
self._dns_host = value | [
"def",
"host",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_dns_host",
"=",
"value"
] | [
146,
4
] | [
153,
30
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection._new_conn | (self) | Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
| Establish a socket connection and set nodelay settings on it. | def _new_conn(self):
"""Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw["source_address"] = self.source_address
if self.socket_options:
extra_kw["soc... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"\"source_address\"",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"\"so... | [
155,
4
] | [
184,
19
] | python | en | ['en', 'st', 'en'] | True |
HTTPConnection.request_chunked | (self, method, url, body=None, headers=None) |
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
|
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
| def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = headers or {}
header_keys = set([six.ensure_str(k.lower()) for k in headers])
... | [
"def",
"request_chunked",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"header_keys",
"=",
"set",
"(",
"[",
"six",
".",
"ensure_str",
"(",
"k",
"... | [
235,
4
] | [
272,
31
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnection.set_cert | (
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
ca_cert_data=None,
) |
This method should only be called once, before the connection is used.
|
This method should only be called once, before the connection is used.
| def set_cert(
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
ca_cert_data=None,
):
"""
This method should only be c... | [
"def",
"set_cert",
"(",
"self",
",",
"key_file",
"=",
"None",
",",
"cert_file",
"=",
"None",
",",
"cert_reqs",
"=",
"None",
",",
"key_password",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"assert_hostname",
"=",
"None",
",",
"assert_fingerprint",
"=",... | [
317,
4
] | [
348,
40
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnection._connect_tls_proxy | (self, hostname, conn) |
Establish a TLS connection to the proxy using the provided SSL context.
|
Establish a TLS connection to the proxy using the provided SSL context.
| def _connect_tls_proxy(self, hostname, conn):
"""
Establish a TLS connection to the proxy using the provided SSL context.
"""
proxy_config = self.proxy_config
ssl_context = proxy_config.ssl_context
if ssl_context:
# If the user provided a proxy context, we ass... | [
"def",
"_connect_tls_proxy",
"(",
"self",
",",
"hostname",
",",
"conn",
")",
":",
"proxy_config",
"=",
"self",
".",
"proxy_config",
"ssl_context",
"=",
"proxy_config",
".",
"ssl_context",
"if",
"ssl_context",
":",
"# If the user provided a proxy context, we assume CA an... | [
470,
4
] | [
502,
9
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.wait | (self, timeout=1) |
Waits for the application to stop itself and returns any exceptions.
|
Waits for the application to stop itself and returns any exceptions.
| async def wait(self, timeout=1):
"""
Waits for the application to stop itself and returns any exceptions.
"""
try:
async with async_timeout(timeout):
try:
await self.future
self.future.result()
except asy... | [
"async",
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"try",
":",
"async",
"with",
"async_timeout",
"(",
"timeout",
")",
":",
"try",
":",
"await",
"self",
".",
"future",
"self",
".",
"future",
".",
"result",
"(",
")",
"except",
"... | [
22,
4
] | [
39,
24
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.send_input | (self, message) |
Sends a single message to the application
|
Sends a single message to the application
| async def send_input(self, message):
"""
Sends a single message to the application
"""
# Give it the message
await self.input_queue.put(message) | [
"async",
"def",
"send_input",
"(",
"self",
",",
"message",
")",
":",
"# Give it the message",
"await",
"self",
".",
"input_queue",
".",
"put",
"(",
"message",
")"
] | [
56,
4
] | [
61,
43
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.receive_output | (self, timeout=1) |
Receives a single message from the application, with optional timeout.
|
Receives a single message from the application, with optional timeout.
| async def receive_output(self, timeout=1):
"""
Receives a single message from the application, with optional timeout.
"""
# Make sure there's not an exception to raise from the task
if self.future.done():
self.future.result()
# Wait and receive the message
... | [
"async",
"def",
"receive_output",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"# Make sure there's not an exception to raise from the task",
"if",
"self",
".",
"future",
".",
"done",
"(",
")",
":",
"self",
".",
"future",
".",
"result",
"(",
")",
"# Wait a... | [
63,
4
] | [
84,
19
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.receive_nothing | (self, timeout=0.1, interval=0.01) |
Checks that there is no message to receive in the given time.
|
Checks that there is no message to receive in the given time.
| async def receive_nothing(self, timeout=0.1, interval=0.01):
"""
Checks that there is no message to receive in the given time.
"""
# `interval` has precedence over `timeout`
start = time.monotonic()
while time.monotonic() - start < timeout:
if not self.output_... | [
"async",
"def",
"receive_nothing",
"(",
"self",
",",
"timeout",
"=",
"0.1",
",",
"interval",
"=",
"0.01",
")",
":",
"# `interval` has precedence over `timeout`",
"start",
"=",
"time",
".",
"monotonic",
"(",
")",
"while",
"time",
".",
"monotonic",
"(",
")",
"... | [
86,
4
] | [
96,
40
] | python | en | ['en', 'error', 'th'] | False |
total_seconds | (d) | Return total number of seconds of a timedelta as a float. | Return total number of seconds of a timedelta as a float. | def total_seconds(d):
"""Return total number of seconds of a timedelta as a float."""
return d.days * 24 * 60 * 60 + d.seconds + d.microseconds / 1000000.0 | [
"def",
"total_seconds",
"(",
"d",
")",
":",
"return",
"d",
".",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"+",
"d",
".",
"seconds",
"+",
"d",
".",
"microseconds",
"/",
"1000000.0"
] | [
30,
0
] | [
32,
73
] | python | en | ['en', 'en', 'en'] | True |
one_time | (method: Callable[[], ReturnT]) |
Use this decorator with extreme caution.
The function you wrap should have no dependency
on any arguments (no args, no kwargs) nor should
it depend on any global state.
|
Use this decorator with extreme caution.
The function you wrap should have no dependency
on any arguments (no args, no kwargs) nor should
it depend on any global state.
| def one_time(method: Callable[[], ReturnT]) -> Callable[[], ReturnT]:
"""
Use this decorator with extreme caution.
The function you wrap should have no dependency
on any arguments (no args, no kwargs) nor should
it depend on any global state.
"""
val = None
def cache_wrapper() -> Return... | [
"def",
"one_time",
"(",
"method",
":",
"Callable",
"[",
"[",
"]",
",",
"ReturnT",
"]",
")",
"->",
"Callable",
"[",
"[",
"]",
",",
"ReturnT",
"]",
":",
"val",
"=",
"None",
"def",
"cache_wrapper",
"(",
")",
"->",
"ReturnT",
":",
"nonlocal",
"val",
"i... | [
66,
0
] | [
81,
24
] | python | en | ['en', 'error', 'th'] | False |
rewrite_local_links_to_relative | (db_data: Optional[DbData], link: str) | If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window.
| If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window.
| def rewrite_local_links_to_relative(db_data: Optional[DbData], link: str) -> str:
"""If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window.
"""
if db_data:
realm_uri_prefix = db_data["realm_uri"] + "/"
if (
... | [
"def",
"rewrite_local_links_to_relative",
"(",
"db_data",
":",
"Optional",
"[",
"DbData",
"]",
",",
"link",
":",
"str",
")",
"->",
"str",
":",
"if",
"db_data",
":",
"realm_uri_prefix",
"=",
"db_data",
"[",
"\"realm_uri\"",
"]",
"+",
"\"/\"",
"if",
"(",
"li... | [
235,
0
] | [
248,
15
] | python | en | ['en', 'en', 'en'] | True |
sanitize_url | (url: str) |
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
|
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
| def sanitize_url(url: str) -> Optional[str]:
"""
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
"""
try:
parts = urllib.parse.urlparse(url.replace(" ", "%20"))
scheme, netloc, path, params, query, fragment = parts
except... | [
"def",
"sanitize_url",
"(",
"url",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"parts",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
".",
"replace",
"(",
"\" \"",
",",
"\"%20\"",
")",
")",
"scheme",
",",
"netlo... | [
1528,
0
] | [
1580,
83
] | python | en | ['en', 'error', 'th'] | False |
prepare_linkifier_pattern | (source: str) | Augment a linkifier so it only matches after start-of-string,
whitespace, or opening delimiters, won't match if there are word
characters directly after, and saves what was matched as
OUTER_CAPTURE_GROUP. | Augment a linkifier so it only matches after start-of-string,
whitespace, or opening delimiters, won't match if there are word
characters directly after, and saves what was matched as
OUTER_CAPTURE_GROUP. | def prepare_linkifier_pattern(source: str) -> str:
"""Augment a linkifier so it only matches after start-of-string,
whitespace, or opening delimiters, won't match if there are word
characters directly after, and saves what was matched as
OUTER_CAPTURE_GROUP."""
return fr"""(?<![^\s'"\(,:<])(?P<{OUTE... | [
"def",
"prepare_linkifier_pattern",
"(",
"source",
":",
"str",
")",
"->",
"str",
":",
"return",
"fr\"\"\"(?<![^\\s'\"\\(,:<])(?P<{OUTER_CAPTURE_GROUP}>{source})(?!\\w)\"\"\""
] | [
1768,
0
] | [
1773,
77
] | python | en | ['en', 'en', 'en'] | True |
do_convert | (
content: str,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
message: Optional[Message] = None,
message_realm: Optional[Realm] = None,
sent_by_bot: bool = False,
translate_emoticons: bool = False,
mention_data: Optional[MentionData] = None,
email_gateway: bool = F... | Convert Markdown to HTML, with Zulip-specific settings and hacks. | Convert Markdown to HTML, with Zulip-specific settings and hacks. | def do_convert(
content: str,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
message: Optional[Message] = None,
message_realm: Optional[Realm] = None,
sent_by_bot: bool = False,
translate_emoticons: bool = False,
mention_data: Optional[MentionData] = None,
email_gat... | [
"def",
"do_convert",
"(",
"content",
":",
"str",
",",
"realm_alert_words_automaton",
":",
"Optional",
"[",
"ahocorasick",
".",
"Automaton",
"]",
"=",
"None",
",",
"message",
":",
"Optional",
"[",
"Message",
"]",
"=",
"None",
",",
"message_realm",
":",
"Optio... | [
2379,
0
] | [
2495,
39
] | python | en | ['en', 'en', 'en'] | True |
InlineInterestingLinkProcessor.twitter_text | (
self,
text: str,
urls: List[Dict[str, str]],
user_mentions: List[Dict[str, Any]],
media: List[Dict[str, Any]],
) |
Use data from the Twitter API to turn links, mentions and media into A
tags. Also convert Unicode emojis to images.
This works by using the URLs, user_mentions and media data from
the twitter API and searching for Unicode emojis in the text using
`UNICODE_EMOJI_RE`.
Th... |
Use data from the Twitter API to turn links, mentions and media into A
tags. Also convert Unicode emojis to images. | def twitter_text(
self,
text: str,
urls: List[Dict[str, str]],
user_mentions: List[Dict[str, Any]],
media: List[Dict[str, Any]],
) -> Element:
"""
Use data from the Twitter API to turn links, mentions and media into A
tags. Also convert Unicode emojis ... | [
"def",
"twitter_text",
"(",
"self",
",",
"text",
":",
"str",
",",
"urls",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
",",
"user_mentions",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"media",
":",
"List",
"... | [
878,
4
] | [
997,
16
] | python | en | ['en', 'error', 'th'] | False |
MarkdownListPreprocessor.run | (self, lines: List[str]) | Insert a newline between a paragraph and ulist if missing | Insert a newline between a paragraph and ulist if missing | def run(self, lines: List[str]) -> List[str]:
"""Insert a newline between a paragraph and ulist if missing"""
inserts = 0
in_code_fence: bool = False
open_fences: List[Fence] = []
copy = lines[:]
for i in range(len(lines) - 1):
# Ignore anything that is inside... | [
"def",
"run",
"(",
"self",
",",
"lines",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"inserts",
"=",
"0",
"in_code_fence",
":",
"bool",
"=",
"False",
"open_fences",
":",
"List",
"[",
"Fence",
"]",
"=",
"[",
"]",
"copy",... | [
1722,
4
] | [
1759,
19
] | python | en | ['en', 'en', 'en'] | True |
supervisor_service_command | (command, service='*', communicate=True) |
example use pattern of supervisorctl:
# supervisorctl restart tower-processes:receiver tower-processes:factcacher
|
example use pattern of supervisorctl:
# supervisorctl restart tower-processes:receiver tower-processes:factcacher
| def supervisor_service_command(command, service='*', communicate=True):
"""
example use pattern of supervisorctl:
# supervisorctl restart tower-processes:receiver tower-processes:factcacher
"""
args = ['supervisorctl']
supervisor_config_path = os.getenv('SUPERVISOR_WEB_CONFIG_PATH', None)
i... | [
"def",
"supervisor_service_command",
"(",
"command",
",",
"service",
"=",
"'*'",
",",
"communicate",
"=",
"True",
")",
":",
"args",
"=",
"[",
"'supervisorctl'",
"]",
"supervisor_config_path",
"=",
"os",
".",
"getenv",
"(",
"'SUPERVISOR_WEB_CONFIG_PATH'",
",",
"N... | [
12,
0
] | [
38,
97
] | python | en | ['en', 'error', 'th'] | False |
reject_check | (accessor, job_config) |
Check if an image passes the quality checks.
If not, a rejection reason is returned.
args:
accessor: a TKP accessor representing the image
job_config: parset file location with quality check parameters
Returns:
(rejection ID, description) if rejected, else None
|
Check if an image passes the quality checks. | def reject_check(accessor, job_config):
"""
Check if an image passes the quality checks.
If not, a rejection reason is returned.
args:
accessor: a TKP accessor representing the image
job_config: parset file location with quality check parameters
Returns:
(rejection ID, des... | [
"def",
"reject_check",
"(",
"accessor",
",",
"job_config",
")",
":",
"rejected",
"=",
"reject_check_generic_data",
"(",
"accessor",
")",
"if",
"rejected",
":",
"return",
"rejected",
"if",
"isinstance",
"(",
"accessor",
",",
"AartfaacCasaImage",
")",
":",
"reject... | [
18,
0
] | [
47,
25
] | python | en | ['en', 'error', 'th'] | False |
reject_image | (image_id, reason, comment) |
Adds a rejection for an image to the database
|
Adds a rejection for an image to the database
| def reject_image(image_id, reason, comment):
"""
Adds a rejection for an image to the database
"""
session = Database().Session()
tkp.db.quality.reject(image_id, reason, comment,session)
session.commit() | [
"def",
"reject_image",
"(",
"image_id",
",",
"reason",
",",
"comment",
")",
":",
"session",
"=",
"Database",
"(",
")",
".",
"Session",
"(",
")",
"tkp",
".",
"db",
".",
"quality",
".",
"reject",
"(",
"image_id",
",",
"reason",
",",
"comment",
",",
"se... | [
50,
0
] | [
56,
20
] | python | en | ['en', 'error', 'th'] | False |
WalletCoinStore.get_coin_record | (self, coin_name: bytes32) | Returns CoinRecord with specified coin id. | Returns CoinRecord with specified coin id. | async def get_coin_record(self, coin_name: bytes32) -> Optional[WalletCoinRecord]:
""" Returns CoinRecord with specified coin id. """
if coin_name in self.coin_record_cache:
return self.coin_record_cache[coin_name]
cursor = await self.db_connection.execute("SELECT * from coin_record ... | [
"async",
"def",
"get_coin_record",
"(",
"self",
",",
"coin_name",
":",
"bytes32",
")",
"->",
"Optional",
"[",
"WalletCoinRecord",
"]",
":",
"if",
"coin_name",
"in",
"self",
".",
"coin_record_cache",
":",
"return",
"self",
".",
"coin_record_cache",
"[",
"coin_n... | [
144,
4
] | [
154,
45
] | python | en | ['en', 'en', 'en'] | True |
WalletCoinStore.get_first_coin_height | (self) | Returns height of first confirmed coin | Returns height of first confirmed coin | async def get_first_coin_height(self) -> Optional[uint32]:
""" Returns height of first confirmed coin"""
cursor = await self.db_connection.execute("SELECT MIN(confirmed_height) FROM coin_record;")
row = await cursor.fetchone()
await cursor.close()
if row is not None and row[0] i... | [
"async",
"def",
"get_first_coin_height",
"(",
"self",
")",
"->",
"Optional",
"[",
"uint32",
"]",
":",
"cursor",
"=",
"await",
"self",
".",
"db_connection",
".",
"execute",
"(",
"\"SELECT MIN(confirmed_height) FROM coin_record;\"",
")",
"row",
"=",
"await",
"cursor... | [
156,
4
] | [
165,
19
] | python | en | ['en', 'en', 'en'] | True |
WalletCoinStore.get_unspent_coins_at_height | (self, height: Optional[uint32] = None) |
Returns set of CoinRecords that have not been spent yet. If a height is specified,
We can also return coins that were unspent at this height (but maybe spent later).
Finally, the coins must be confirmed at the height or less.
|
Returns set of CoinRecords that have not been spent yet. If a height is specified,
We can also return coins that were unspent at this height (but maybe spent later).
Finally, the coins must be confirmed at the height or less.
| async def get_unspent_coins_at_height(self, height: Optional[uint32] = None) -> Set[WalletCoinRecord]:
"""
Returns set of CoinRecords that have not been spent yet. If a height is specified,
We can also return coins that were unspent at this height (but maybe spent later).
Finally, the co... | [
"async",
"def",
"get_unspent_coins_at_height",
"(",
"self",
",",
"height",
":",
"Optional",
"[",
"uint32",
"]",
"=",
"None",
")",
"->",
"Set",
"[",
"WalletCoinRecord",
"]",
":",
"if",
"height",
"is",
"None",
":",
"all_unspent",
"=",
"set",
"(",
")",
"for... | [
167,
4
] | [
187,
30
] | python | en | ['en', 'error', 'th'] | False |
WalletCoinStore.get_unspent_coins_for_wallet | (self, wallet_id: int) | Returns set of CoinRecords that have not been spent yet for a wallet. | Returns set of CoinRecords that have not been spent yet for a wallet. | async def get_unspent_coins_for_wallet(self, wallet_id: int) -> Set[WalletCoinRecord]:
""" Returns set of CoinRecords that have not been spent yet for a wallet. """
if wallet_id in self.unspent_coin_wallet_cache:
wallet_coins: Dict[bytes32, WalletCoinRecord] = self.unspent_coin_wallet_cache[... | [
"async",
"def",
"get_unspent_coins_for_wallet",
"(",
"self",
",",
"wallet_id",
":",
"int",
")",
"->",
"Set",
"[",
"WalletCoinRecord",
"]",
":",
"if",
"wallet_id",
"in",
"self",
".",
"unspent_coin_wallet_cache",
":",
"wallet_coins",
":",
"Dict",
"[",
"bytes32",
... | [
189,
4
] | [
195,
24
] | python | en | ['en', 'en', 'en'] | True |
WalletCoinStore.get_all_coins | (self) | Returns set of all CoinRecords. | Returns set of all CoinRecords. | async def get_all_coins(self) -> Set[WalletCoinRecord]:
""" Returns set of all CoinRecords."""
cursor = await self.db_connection.execute("SELECT * from coin_record")
rows = await cursor.fetchall()
await cursor.close()
return set(self.coin_record_from_row(row) for row in rows) | [
"async",
"def",
"get_all_coins",
"(",
"self",
")",
"->",
"Set",
"[",
"WalletCoinRecord",
"]",
":",
"cursor",
"=",
"await",
"self",
".",
"db_connection",
".",
"execute",
"(",
"\"SELECT * from coin_record\"",
")",
"rows",
"=",
"await",
"cursor",
".",
"fetchall",... | [
197,
4
] | [
203,
66
] | python | en | ['en', 'en', 'en'] | True |
WalletCoinStore.get_coin_records_by_puzzle_hash | (self, puzzle_hash: bytes32) | Returns a list of all coin records with the given puzzle hash | Returns a list of all coin records with the given puzzle hash | async def get_coin_records_by_puzzle_hash(self, puzzle_hash: bytes32) -> List[WalletCoinRecord]:
"""Returns a list of all coin records with the given puzzle hash"""
cursor = await self.db_connection.execute("SELECT * from coin_record WHERE puzzle_hash=?", (puzzle_hash.hex(),))
rows = await curso... | [
"async",
"def",
"get_coin_records_by_puzzle_hash",
"(",
"self",
",",
"puzzle_hash",
":",
"bytes32",
")",
"->",
"List",
"[",
"WalletCoinRecord",
"]",
":",
"cursor",
"=",
"await",
"self",
".",
"db_connection",
".",
"execute",
"(",
"\"SELECT * from coin_record WHERE pu... | [
206,
4
] | [
212,
63
] | python | en | ['en', 'en', 'en'] | True |
WalletCoinStore.rollback_to_block | (self, height: int) |
Rolls back the blockchain to block_index. All blocks confirmed after this point
are removed from the LCA. All coins confirmed after this point are removed.
All coins spent after this point are set to unspent. Can be -1 (rollback all)
|
Rolls back the blockchain to block_index. All blocks confirmed after this point
are removed from the LCA. All coins confirmed after this point are removed.
All coins spent after this point are set to unspent. Can be -1 (rollback all)
| async def rollback_to_block(self, height: int):
"""
Rolls back the blockchain to block_index. All blocks confirmed after this point
are removed from the LCA. All coins confirmed after this point are removed.
All coins spent after this point are set to unspent. Can be -1 (rollback all)
... | [
"async",
"def",
"rollback_to_block",
"(",
"self",
",",
"height",
":",
"int",
")",
":",
"# Delete from storage",
"delete_queue",
":",
"List",
"[",
"WalletCoinRecord",
"]",
"=",
"[",
"]",
"for",
"coin_name",
",",
"coin_record",
"in",
"self",
".",
"coin_record_ca... | [
214,
4
] | [
251,
24
] | python | en | ['en', 'error', 'th'] | False |
parse_rgi_meta | (version=None) | Read the meta information (region and sub-region names) | Read the meta information (region and sub-region names) | def parse_rgi_meta(version=None):
"""Read the meta information (region and sub-region names)"""
global _RGI_METADATA
if version is None:
version = cfg.PARAMS['rgi_version']
if version in _RGI_METADATA:
return _RGI_METADATA[version]
# Parse RGI metadata
reg_names = pd.read_csv... | [
"def",
"parse_rgi_meta",
"(",
"version",
"=",
"None",
")",
":",
"global",
"_RGI_METADATA",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"cfg",
".",
"PARAMS",
"[",
"'rgi_version'",
"]",
"if",
"version",
"in",
"_RGI_METADATA",
":",
"return",
"_RGI_METAD... | [
58,
0
] | [
87,
33
] | python | en | ['en', 'en', 'en'] | True |
query_yes_no | (question, default="yes") | Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return... | Ask a yes/no question via raw_input() and return their answer. | def query_yes_no(question, default="yes"): # pragma: no cover
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meanin... | [
"def",
"query_yes_no",
"(",
"question",
",",
"default",
"=",
"\"yes\"",
")",
":",
"# pragma: no cover",
"valid",
"=",
"{",
"\"yes\"",
":",
"True",
",",
"\"y\"",
":",
"True",
",",
"\"ye\"",
":",
"True",
",",
"\"no\"",
":",
"False",
",",
"\"n\"",
":",
"F... | [
90,
0
] | [
122,
50
] | python | en | ['en', 'en', 'en'] | True |
tolist | (arg, length=None) | Makes sure that arg is a list. | Makes sure that arg is a list. | def tolist(arg, length=None):
"""Makes sure that arg is a list."""
if isinstance(arg, str):
arg = [arg]
try:
# Shapely stuff
arg = arg.geoms
except AttributeError:
pass
try:
(e for e in arg)
except TypeError:
arg = [arg]
arg = list(arg)
... | [
"def",
"tolist",
"(",
"arg",
",",
"length",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"arg",
"=",
"[",
"arg",
"]",
"try",
":",
"# Shapely stuff",
"arg",
"=",
"arg",
".",
"geoms",
"except",
"AttributeError",
":",
"... | [
125,
0
] | [
154,
14
] | python | en | ['en', 'en', 'en'] | True |
haversine | (lon1, lat1, lon2, lat2) | Great circle distance between two (or more) points on Earth
Parameters
----------
lon1 : float
scalar or array of point(s) longitude
lat1 : float
scalar or array of point(s) longitude
lon2 : float
scalar or array of point(s) longitude
lat2 : float
scalar or array of ... | Great circle distance between two (or more) points on Earth | def haversine(lon1, lat1, lon2, lat2):
"""Great circle distance between two (or more) points on Earth
Parameters
----------
lon1 : float
scalar or array of point(s) longitude
lat1 : float
scalar or array of point(s) longitude
lon2 : float
scalar or array of point(s) longitu... | [
"def",
"haversine",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
":",
"# convert decimal degrees to radians",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
"=",
"map",
"(",
"np",
".",
"radians",
",",
"[",
"lon1",
",",
"lat1",
",",
"lon2",
... | [
157,
0
] | [
191,
22
] | python | en | ['en', 'en', 'en'] | True |
interp_nans | (array, default=None) | Interpolate NaNs using np.interp.
np.interp is reasonable in that it does not extrapolate, it replaces
NaNs at the bounds with the closest valid value.
| Interpolate NaNs using np.interp. | def interp_nans(array, default=None):
"""Interpolate NaNs using np.interp.
np.interp is reasonable in that it does not extrapolate, it replaces
NaNs at the bounds with the closest valid value.
"""
_tmp = array.copy()
nans, x = np.isnan(array), lambda z: z.nonzero()[0]
if np.all(nans):
... | [
"def",
"interp_nans",
"(",
"array",
",",
"default",
"=",
"None",
")",
":",
"_tmp",
"=",
"array",
".",
"copy",
"(",
")",
"nans",
",",
"x",
"=",
"np",
".",
"isnan",
"(",
"array",
")",
",",
"lambda",
"z",
":",
"z",
".",
"nonzero",
"(",
")",
"[",
... | [
194,
0
] | [
212,
15
] | python | en | ['en', 'gl', 'en'] | True |
apply_test_ref_tstars | (baseline='cru4') | Copy the testing ref tstars to the current working directory.
Used mostly for testing.
| Copy the testing ref tstars to the current working directory. | def apply_test_ref_tstars(baseline='cru4'):
"""Copy the testing ref tstars to the current working directory.
Used mostly for testing.
"""
if not os.path.exists(cfg.PATHS['working_dir']):
raise RuntimeError('Need a valid working_dir')
shutil.copyfile(get_demo_file(f'oggm_ref_tstars_rgi5_{bas... | [
"def",
"apply_test_ref_tstars",
"(",
"baseline",
"=",
"'cru4'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cfg",
".",
"PATHS",
"[",
"'working_dir'",
"]",
")",
":",
"raise",
"RuntimeError",
"(",
"'Need a valid working_dir'",
")",
"shutil",... | [
215,
0
] | [
228,
59
] | python | en | ['en', 'en', 'en'] | True |
smooth1d | (array, window_size=None, kernel='gaussian') | Apply a centered window smoothing to a 1D array.
Parameters
----------
array : ndarray
the array to apply the smoothing to
window_size : int
the size of the smoothing window
kernel : str
the type of smoothing (`gaussian`, `mean`)
Returns
-------
the smoothed arr... | Apply a centered window smoothing to a 1D array. | def smooth1d(array, window_size=None, kernel='gaussian'):
"""Apply a centered window smoothing to a 1D array.
Parameters
----------
array : ndarray
the array to apply the smoothing to
window_size : int
the size of the smoothing window
kernel : str
the type of smoothing (... | [
"def",
"smooth1d",
"(",
"array",
",",
"window_size",
"=",
"None",
",",
"kernel",
"=",
"'gaussian'",
")",
":",
"# some defaults",
"if",
"window_size",
"is",
"None",
":",
"if",
"len",
"(",
"array",
")",
">=",
"9",
":",
"window_size",
"=",
"9",
"elif",
"l... | [
231,
0
] | [
270,
59
] | python | en | ['en', 'en', 'en'] | True |
line_interpol | (line, dx) | Interpolates a shapely LineString to a regularly spaced one.
Shapely's interpolate function does not guaranty equally
spaced points in space. This is what this function is for.
We construct new points on the line but at constant distance from the
preceding one.
Parameters
----------
line:... | Interpolates a shapely LineString to a regularly spaced one. | def line_interpol(line, dx):
"""Interpolates a shapely LineString to a regularly spaced one.
Shapely's interpolate function does not guaranty equally
spaced points in space. This is what this function is for.
We construct new points on the line but at constant distance from the
preceding one.
... | [
"def",
"line_interpol",
"(",
"line",
",",
"dx",
")",
":",
"# First point is easy",
"points",
"=",
"[",
"line",
".",
"interpolate",
"(",
"dx",
"/",
"2.",
")",
"]",
"# Continue as long as line is not finished",
"while",
"True",
":",
"pref",
"=",
"points",
"[",
... | [
273,
0
] | [
333,
17
] | python | en | ['en', 'en', 'en'] | True |
md | (ref, data, axis=None) | Mean Deviation. | Mean Deviation. | def md(ref, data, axis=None):
"""Mean Deviation."""
return np.mean(np.asarray(data) - ref, axis=axis) | [
"def",
"md",
"(",
"ref",
",",
"data",
",",
"axis",
"=",
"None",
")",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"asarray",
"(",
"data",
")",
"-",
"ref",
",",
"axis",
"=",
"axis",
")"
] | [
336,
0
] | [
338,
53
] | python | en | ['en', 'de', 'en'] | False |
mad | (ref, data, axis=None) | Mean Absolute Deviation. | Mean Absolute Deviation. | def mad(ref, data, axis=None):
"""Mean Absolute Deviation."""
return np.mean(np.abs(np.asarray(data) - ref), axis=axis) | [
"def",
"mad",
"(",
"ref",
",",
"data",
",",
"axis",
"=",
"None",
")",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"abs",
"(",
"np",
".",
"asarray",
"(",
"data",
")",
"-",
"ref",
")",
",",
"axis",
"=",
"axis",
")"
] | [
341,
0
] | [
343,
61
] | python | en | ['en', 'en', 'en'] | True |
rmsd | (ref, data, axis=None) | Root Mean Square Deviation. | Root Mean Square Deviation. | def rmsd(ref, data, axis=None):
"""Root Mean Square Deviation."""
return np.sqrt(np.mean((np.asarray(ref) - data)**2, axis=axis)) | [
"def",
"rmsd",
"(",
"ref",
",",
"data",
",",
"axis",
"=",
"None",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"mean",
"(",
"(",
"np",
".",
"asarray",
"(",
"ref",
")",
"-",
"data",
")",
"**",
"2",
",",
"axis",
"=",
"axis",
")",
")... | [
346,
0
] | [
348,
67
] | python | en | ['en', 'en', 'en'] | True |
rmsd_bc | (ref, data) | Root Mean Squared Deviation of bias-corrected time series.
I.e: rmsd(ref - mean(ref), data - mean(data)).
| Root Mean Squared Deviation of bias-corrected time series. | def rmsd_bc(ref, data):
"""Root Mean Squared Deviation of bias-corrected time series.
I.e: rmsd(ref - mean(ref), data - mean(data)).
"""
return rmsd(ref - np.mean(ref), data - np.mean(data)) | [
"def",
"rmsd_bc",
"(",
"ref",
",",
"data",
")",
":",
"return",
"rmsd",
"(",
"ref",
"-",
"np",
".",
"mean",
"(",
"ref",
")",
",",
"data",
"-",
"np",
".",
"mean",
"(",
"data",
")",
")"
] | [
351,
0
] | [
356,
57
] | python | en | ['en', 'en', 'en'] | True |
rel_err | (ref, data) | Relative error. Ref should be non-zero | Relative error. Ref should be non-zero | def rel_err(ref, data):
"""Relative error. Ref should be non-zero"""
return (np.asarray(data) - ref) / ref | [
"def",
"rel_err",
"(",
"ref",
",",
"data",
")",
":",
"return",
"(",
"np",
".",
"asarray",
"(",
"data",
")",
"-",
"ref",
")",
"/",
"ref"
] | [
359,
0
] | [
361,
41
] | python | en | ['en', 'it', 'en'] | True |
corrcoef | (ref, data) | Peason correlation coefficient. | Peason correlation coefficient. | def corrcoef(ref, data):
"""Peason correlation coefficient."""
return np.corrcoef(ref, data)[0, 1] | [
"def",
"corrcoef",
"(",
"ref",
",",
"data",
")",
":",
"return",
"np",
".",
"corrcoef",
"(",
"ref",
",",
"data",
")",
"[",
"0",
",",
"1",
"]"
] | [
364,
0
] | [
366,
39
] | python | en | ['en', 'sr', 'it'] | False |
clip_scalar | (value, vmin, vmax) | A faster numpy.clip ON SCALARS ONLY.
See https://github.com/numpy/numpy/issues/14281
| A faster numpy.clip ON SCALARS ONLY. | def clip_scalar(value, vmin, vmax):
"""A faster numpy.clip ON SCALARS ONLY.
See https://github.com/numpy/numpy/issues/14281
"""
return vmin if value < vmin else vmax if value > vmax else value | [
"def",
"clip_scalar",
"(",
"value",
",",
"vmin",
",",
"vmax",
")",
":",
"return",
"vmin",
"if",
"value",
"<",
"vmin",
"else",
"vmax",
"if",
"value",
">",
"vmax",
"else",
"value"
] | [
369,
0
] | [
374,
68
] | python | en | ['en', 'en', 'en'] | True |
nicenumber | (number, binsize, lower=False) | Returns the next higher or lower "nice number", given by binsize.
Examples:
---------
>>> nicenumber(12, 10)
20
>>> nicenumber(19, 50)
50
>>> nicenumber(51, 50)
100
>>> nicenumber(51, 50, lower=True)
50
| Returns the next higher or lower "nice number", given by binsize. | def nicenumber(number, binsize, lower=False):
"""Returns the next higher or lower "nice number", given by binsize.
Examples:
---------
>>> nicenumber(12, 10)
20
>>> nicenumber(19, 50)
50
>>> nicenumber(51, 50)
100
>>> nicenumber(51, 50, lower=True)
50
"""
e, _ = div... | [
"def",
"nicenumber",
"(",
"number",
",",
"binsize",
",",
"lower",
"=",
"False",
")",
":",
"e",
",",
"_",
"=",
"divmod",
"(",
"number",
",",
"binsize",
")",
"if",
"lower",
":",
"return",
"e",
"*",
"binsize",
"else",
":",
"return",
"(",
"e",
"+",
"... | [
392,
0
] | [
411,
32
] | python | en | ['en', 'en', 'en'] | True |
signchange | (ts) | Detect sign changes in a time series.
http://stackoverflow.com/questions/2652368/how-to-detect-a-sign-change-
for-elements-in-a-numpy-array
Returns
-------
An array with 0s everywhere and 1's when the sign changes
| Detect sign changes in a time series. | def signchange(ts):
"""Detect sign changes in a time series.
http://stackoverflow.com/questions/2652368/how-to-detect-a-sign-change-
for-elements-in-a-numpy-array
Returns
-------
An array with 0s everywhere and 1's when the sign changes
"""
asign = np.sign(ts)
sz = asign == 0
w... | [
"def",
"signchange",
"(",
"ts",
")",
":",
"asign",
"=",
"np",
".",
"sign",
"(",
"ts",
")",
"sz",
"=",
"asign",
"==",
"0",
"while",
"sz",
".",
"any",
"(",
")",
":",
"asign",
"[",
"sz",
"]",
"=",
"np",
".",
"roll",
"(",
"asign",
",",
"1",
")"... | [
414,
0
] | [
432,
14
] | python | en | ['en', 'en', 'en'] | True |
polygon_intersections | (gdf) | Computes the intersections between all polygons in a GeoDataFrame.
Parameters
----------
gdf : Geopandas.GeoDataFrame
Returns
-------
a Geodataframe containing the intersections
| Computes the intersections between all polygons in a GeoDataFrame. | def polygon_intersections(gdf):
"""Computes the intersections between all polygons in a GeoDataFrame.
Parameters
----------
gdf : Geopandas.GeoDataFrame
Returns
-------
a Geodataframe containing the intersections
"""
out_cols = ['id_1', 'id_2', 'geometry']
out = gpd.GeoDataFra... | [
"def",
"polygon_intersections",
"(",
"gdf",
")",
":",
"out_cols",
"=",
"[",
"'id_1'",
",",
"'id_2'",
",",
"'geometry'",
"]",
"out",
"=",
"gpd",
".",
"GeoDataFrame",
"(",
"columns",
"=",
"out_cols",
")",
"gdf",
"=",
"gdf",
".",
"reset_index",
"(",
")",
... | [
435,
0
] | [
513,
14
] | python | en | ['en', 'en', 'en'] | True |
multipolygon_to_polygon | (geometry, gdir=None) | Sometimes an RGI geometry is a multipolygon: this should not happen.
Parameters
----------
geometry : shpg.Polygon or shpg.MultiPolygon
the geometry to check
gdir : GlacierDirectory, optional
for logging
Returns
-------
the corrected geometry
| Sometimes an RGI geometry is a multipolygon: this should not happen. | def multipolygon_to_polygon(geometry, gdir=None):
"""Sometimes an RGI geometry is a multipolygon: this should not happen.
Parameters
----------
geometry : shpg.Polygon or shpg.MultiPolygon
the geometry to check
gdir : GlacierDirectory, optional
for logging
Returns
-------
... | [
"def",
"multipolygon_to_polygon",
"(",
"geometry",
",",
"gdir",
"=",
"None",
")",
":",
"# Log",
"rid",
"=",
"gdir",
".",
"rgi_id",
"+",
"': '",
"if",
"gdir",
"is",
"not",
"None",
"else",
"''",
"if",
"'Multi'",
"in",
"geometry",
".",
"type",
":",
"parts... | [
516,
0
] | [
563,
19
] | python | en | ['en', 'en', 'en'] | True |
floatyear_to_date | (yr) | Converts a float year to an actual (year, month) pair.
Note that this doesn't account for leap years (365-day no leap calendar),
and that the months all have the same length.
Parameters
----------
yr : float
The floating year
| Converts a float year to an actual (year, month) pair. | def floatyear_to_date(yr):
"""Converts a float year to an actual (year, month) pair.
Note that this doesn't account for leap years (365-day no leap calendar),
and that the months all have the same length.
Parameters
----------
yr : float
The floating year
"""
try:
sec,... | [
"def",
"floatyear_to_date",
"(",
"yr",
")",
":",
"try",
":",
"sec",
",",
"out_y",
"=",
"math",
".",
"modf",
"(",
"yr",
")",
"out_y",
"=",
"int",
"(",
"out_y",
")",
"sec",
"=",
"round",
"(",
"sec",
"*",
"SEC_IN_YEAR",
")",
"if",
"sec",
"==",
"SEC_... | [
566,
0
] | [
595,
23
] | python | en | ['en', 'en', 'en'] | True |
date_to_floatyear | (y, m) | Converts an integer (year, month) pair to a float year.
Note that this doesn't account for leap years (365-day no leap calendar),
and that the months all have the same length.
Parameters
----------
y : int
the year
m : int
the month
| Converts an integer (year, month) pair to a float year. | def date_to_floatyear(y, m):
"""Converts an integer (year, month) pair to a float year.
Note that this doesn't account for leap years (365-day no leap calendar),
and that the months all have the same length.
Parameters
----------
y : int
the year
m : int
the month
"""
... | [
"def",
"date_to_floatyear",
"(",
"y",
",",
"m",
")",
":",
"return",
"(",
"np",
".",
"asanyarray",
"(",
"y",
")",
"+",
"(",
"np",
".",
"asanyarray",
"(",
"m",
")",
"-",
"1",
")",
"*",
"SEC_IN_MONTH",
"/",
"SEC_IN_YEAR",
")"
] | [
598,
0
] | [
613,
39
] | python | en | ['en', 'en', 'en'] | True |
hydrodate_to_calendardate | (y, m, start_month=None) | Converts a hydrological (year, month) pair to a calendar date.
Parameters
----------
y : int
the year
m : int
the month
start_month : int
the first month of the hydrological year
| Converts a hydrological (year, month) pair to a calendar date. | def hydrodate_to_calendardate(y, m, start_month=None):
"""Converts a hydrological (year, month) pair to a calendar date.
Parameters
----------
y : int
the year
m : int
the month
start_month : int
the first month of the hydrological year
"""
if start_month is Non... | [
"def",
"hydrodate_to_calendardate",
"(",
"y",
",",
"m",
",",
"start_month",
"=",
"None",
")",
":",
"if",
"start_month",
"is",
"None",
":",
"raise",
"InvalidParamsError",
"(",
"'In order to avoid confusion, we now force '",
"'callers of this function to specify the '",
"'h... | [
616,
0
] | [
653,
23
] | python | en | ['en', 'en', 'en'] | True |
calendardate_to_hydrodate | (y, m, start_month=None) | Converts a calendar (year, month) pair to a hydrological date.
Parameters
----------
y : int
the year
m : int
the month
start_month : int
the first month of the hydrological year
| Converts a calendar (year, month) pair to a hydrological date. | def calendardate_to_hydrodate(y, m, start_month=None):
"""Converts a calendar (year, month) pair to a hydrological date.
Parameters
----------
y : int
the year
m : int
the month
start_month : int
the first month of the hydrological year
"""
if start_month is Non... | [
"def",
"calendardate_to_hydrodate",
"(",
"y",
",",
"m",
",",
"start_month",
"=",
"None",
")",
":",
"if",
"start_month",
"is",
"None",
":",
"raise",
"InvalidParamsError",
"(",
"'In order to avoid confusion, we now force '",
"'callers of this function to specify the '",
"'h... | [
656,
0
] | [
692,
23
] | python | en | ['en', 'en', 'en'] | True |
monthly_timeseries | (y0, y1=None, ny=None, include_last_year=False) | Creates a monthly timeseries in units of float years.
Parameters
----------
| Creates a monthly timeseries in units of float years. | def monthly_timeseries(y0, y1=None, ny=None, include_last_year=False):
"""Creates a monthly timeseries in units of float years.
Parameters
----------
"""
if y1 is not None:
years = np.arange(np.floor(y0), np.floor(y1) + 1)
elif ny is not None:
years = np.arange(np.floor(y0), np... | [
"def",
"monthly_timeseries",
"(",
"y0",
",",
"y1",
"=",
"None",
",",
"ny",
"=",
"None",
",",
"include_last_year",
"=",
"False",
")",
":",
"if",
"y1",
"is",
"not",
"None",
":",
"years",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"floor",
"(",
"y0",
... | [
695,
0
] | [
713,
14
] | python | en | ['en', 'en', 'en'] | True |
filter_rgi_name | (name) | Remove spurious characters and trailing blanks from RGI glacier name.
This seems to be unnecessary with RGI V6
| Remove spurious characters and trailing blanks from RGI glacier name. | def filter_rgi_name(name):
"""Remove spurious characters and trailing blanks from RGI glacier name.
This seems to be unnecessary with RGI V6
"""
if name is None or len(name) == 0:
return ''
if name[-1] in ['À', 'È', 'è', '\x9c', '3', 'Ð', '°', '¾',
'\r', '\x93', '¤', '... | [
"def",
"filter_rgi_name",
"(",
"name",
")",
":",
"if",
"name",
"is",
"None",
"or",
"len",
"(",
"name",
")",
"==",
"0",
":",
"return",
"''",
"if",
"name",
"[",
"-",
"1",
"]",
"in",
"[",
"'À',",
" ",
"È', ",
"'",
"', '",
"\\",
"9c', '",
"3",
", '... | [
716,
0
] | [
730,
31
] | python | en | ['en', 'en', 'en'] | True |
shape_factor_huss | (widths, heights, is_rectangular) | Shape factor for lateral drag according to Huss and Farinotti (2012).
The shape factor is only applied for parabolic sections.
Parameters
----------
widths: ndarray of floats
widths of the sections
heights: float or ndarray of floats
height of the sections
is_rectangular: bool ... | Shape factor for lateral drag according to Huss and Farinotti (2012). | def shape_factor_huss(widths, heights, is_rectangular):
"""Shape factor for lateral drag according to Huss and Farinotti (2012).
The shape factor is only applied for parabolic sections.
Parameters
----------
widths: ndarray of floats
widths of the sections
heights: float or ndarray of ... | [
"def",
"shape_factor_huss",
"(",
"widths",
",",
"heights",
",",
"is_rectangular",
")",
":",
"# Ensure bool (for masking)",
"is_rect",
"=",
"is_rectangular",
".",
"astype",
"(",
"bool",
")",
"shape_factors",
"=",
"np",
".",
"ones",
"(",
"widths",
".",
"shape",
... | [
733,
0
] | [
765,
24
] | python | en | ['en', 'en', 'en'] | True |
shape_factor_adhikari | (widths, heights, is_rectangular) | Shape factor for lateral drag according to Adhikari (2012).
TODO: other factors could be used when sliding is included
Parameters
----------
widths: ndarray of floats
widths of the sections
heights: ndarray of floats
heights of the sections
is_rectangular: ndarray of bools
... | Shape factor for lateral drag according to Adhikari (2012). | def shape_factor_adhikari(widths, heights, is_rectangular):
"""Shape factor for lateral drag according to Adhikari (2012).
TODO: other factors could be used when sliding is included
Parameters
----------
widths: ndarray of floats
widths of the sections
heights: ndarray of floats
... | [
"def",
"shape_factor_adhikari",
"(",
"widths",
",",
"heights",
",",
"is_rectangular",
")",
":",
"# Ensure bool (for masking)",
"is_rectangular",
"=",
"is_rectangular",
".",
"astype",
"(",
"bool",
")",
"# Catch for division by 0 (corrected later)",
"with",
"warnings",
".",... | [
768,
0
] | [
807,
24
] | python | en | ['en', 'en', 'en'] | True |
cook_rgidf | (gi_gdf, o1_region, o2_region='01', version='60', ids=None,
bgndate='20009999', id_suffix='', assign_column_values=None) | Convert a glacier inventory into a dataset looking like the RGI (OGGM ready).
Parameters
----------
gi_gdf : :py:geopandas.GeoDataFrame
the GeoDataFrame of the user's glacier inventory.
o1_region : str
Glacier RGI region code, which is important for some OGGM applications.
For e... | Convert a glacier inventory into a dataset looking like the RGI (OGGM ready). | def cook_rgidf(gi_gdf, o1_region, o2_region='01', version='60', ids=None,
bgndate='20009999', id_suffix='', assign_column_values=None):
"""Convert a glacier inventory into a dataset looking like the RGI (OGGM ready).
Parameters
----------
gi_gdf : :py:geopandas.GeoDataFrame
the G... | [
"def",
"cook_rgidf",
"(",
"gi_gdf",
",",
"o1_region",
",",
"o2_region",
"=",
"'01'",
",",
"version",
"=",
"'60'",
",",
"ids",
"=",
"None",
",",
"bgndate",
"=",
"'20009999'",
",",
"id_suffix",
"=",
"''",
",",
"assign_column_values",
"=",
"None",
")",
":",... | [
810,
0
] | [
885,
23
] | python | en | ['en', 'en', 'en'] | True |
url_params_from_lookup_dict | (lookups) |
Converts the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
|
Converts the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
| def url_params_from_lookup_dict(lookups):
"""
Converts the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
"""
params = {}
if lookups and hasattr(lookups, 'items'):
items = []
for k, v in lookups.items():
if cal... | [
"def",
"url_params_from_lookup_dict",
"(",
"lookups",
")",
":",
"params",
"=",
"{",
"}",
"if",
"lookups",
"and",
"hasattr",
"(",
"lookups",
",",
"'items'",
")",
":",
"items",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"lookups",
".",
"items",
"(",
")... | [
99,
0
] | [
118,
17
] | python | en | ['en', 'error', 'th'] | False |
pageurl | (context, page, fallback=None) |
Outputs a page's URL as relative (/foo/bar/) if it's within the same site as the
current page, or absolute (http://example.com/foo/bar/) if not.
If kwargs contains a fallback view name and page is None, the fallback view url will be returned.
|
Outputs a page's URL as relative (/foo/bar/) if it's within the same site as the
current page, or absolute (http://example.com/foo/bar/) if not.
If kwargs contains a fallback view name and page is None, the fallback view url will be returned.
| def pageurl(context, page, fallback=None):
"""
Outputs a page's URL as relative (/foo/bar/) if it's within the same site as the
current page, or absolute (http://example.com/foo/bar/) if not.
If kwargs contains a fallback view name and page is None, the fallback view url will be returned.
"""
if... | [
"def",
"pageurl",
"(",
"context",
",",
"page",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"page",
"is",
"None",
"and",
"fallback",
":",
"return",
"resolve_url",
"(",
"fallback",
")",
"if",
"not",
"hasattr",
"(",
"page",
",",
"'relative_url'",
")",
"... | [
17,
0
] | [
44,
74
] | python | en | ['en', 'error', 'th'] | False |
slugurl | (context, slug) |
Returns the URL for the page that has the given slug.
First tries to find a page on the current site. If that fails or a request
is not available in the context, then returns the URL for the first page
that matches the slug on any site.
|
Returns the URL for the page that has the given slug. | def slugurl(context, slug):
"""
Returns the URL for the page that has the given slug.
First tries to find a page on the current site. If that fails or a request
is not available in the context, then returns the URL for the first page
that matches the slug on any site.
"""
page = None
t... | [
"def",
"slugurl",
"(",
"context",
",",
"slug",
")",
":",
"page",
"=",
"None",
"try",
":",
"site",
"=",
"Site",
".",
"find_for_request",
"(",
"context",
"[",
"'request'",
"]",
")",
"current_site",
"=",
"site",
"except",
"KeyError",
":",
"# No site object fo... | [
48,
0
] | [
74,
37
] | python | en | ['en', 'error', 'th'] | False |
include_block | (parser, token) |
Render the passed item of StreamField content, passing the current template context
if there's an identifiable way of doing so (i.e. if it has a `render_as_block` method).
|
Render the passed item of StreamField content, passing the current template context
if there's an identifiable way of doing so (i.e. if it has a `render_as_block` method).
| def include_block(parser, token):
"""
Render the passed item of StreamField content, passing the current template context
if there's an identifiable way of doing so (i.e. if it has a `render_as_block` method).
"""
tokens = token.split_contents()
try:
tag_name = tokens.pop(0)
blo... | [
"def",
"include_block",
"(",
"parser",
",",
"token",
")",
":",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"try",
":",
"tag_name",
"=",
"tokens",
".",
"pop",
"(",
"0",
")",
"block_var_token",
"=",
"tokens",
".",
"pop",
"(",
"0",
")",
"ex... | [
144,
0
] | [
173,
73
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.