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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Apps.set_available_apps | (self, available) |
Restricts the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in TransactionTestCase.
This method is safe is th... |
Restricts the set of installed apps used by get_app_config[s]. | def set_available_apps(self, available):
"""
Restricts the set of installed apps used by get_app_config[s].
available must be an iterable of application names.
set_available_apps() must be balanced with unset_available_apps().
Primarily used for performance optimization in Tra... | [
"def",
"set_available_apps",
"(",
"self",
",",
"available",
")",
":",
"available",
"=",
"set",
"(",
"available",
")",
"installed",
"=",
"set",
"(",
"app_config",
".",
"name",
"for",
"app_config",
"in",
"self",
".",
"get_app_configs",
"(",
")",
")",
"if",
... | [
292,
4
] | [
317,
26
] | python | en | ['en', 'error', 'th'] | False |
Apps.unset_available_apps | (self) |
Cancels a previous call to set_available_apps().
|
Cancels a previous call to set_available_apps().
| def unset_available_apps(self):
"""
Cancels a previous call to set_available_apps().
"""
self.app_configs = self.stored_app_configs.pop()
self.clear_cache() | [
"def",
"unset_available_apps",
"(",
"self",
")",
":",
"self",
".",
"app_configs",
"=",
"self",
".",
"stored_app_configs",
".",
"pop",
"(",
")",
"self",
".",
"clear_cache",
"(",
")"
] | [
319,
4
] | [
324,
26
] | python | en | ['en', 'error', 'th'] | False |
Apps.set_installed_apps | (self, installed) |
Enables a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exception.
Primarily used as a receiver of the sett... |
Enables a different set of installed apps for get_app_config[s]. | def set_installed_apps(self, installed):
"""
Enables a different set of installed apps for get_app_config[s].
installed must be an iterable in the same format as INSTALLED_APPS.
set_installed_apps() must be balanced with unset_installed_apps(),
even if it exits with an exceptio... | [
"def",
"set_installed_apps",
"(",
"self",
",",
"installed",
")",
":",
"if",
"not",
"self",
".",
"ready",
":",
"raise",
"AppRegistryNotReady",
"(",
"\"App registry isn't ready yet.\"",
")",
"self",
".",
"stored_app_configs",
".",
"append",
"(",
"self",
".",
"app_... | [
326,
4
] | [
349,
32
] | python | en | ['en', 'error', 'th'] | False |
Apps.unset_installed_apps | (self) |
Cancels a previous call to set_installed_apps().
|
Cancels a previous call to set_installed_apps().
| def unset_installed_apps(self):
"""
Cancels a previous call to set_installed_apps().
"""
self.app_configs = self.stored_app_configs.pop()
self.apps_ready = self.models_ready = self.ready = True
self.clear_cache() | [
"def",
"unset_installed_apps",
"(",
"self",
")",
":",
"self",
".",
"app_configs",
"=",
"self",
".",
"stored_app_configs",
".",
"pop",
"(",
")",
"self",
".",
"apps_ready",
"=",
"self",
".",
"models_ready",
"=",
"self",
".",
"ready",
"=",
"True",
"self",
"... | [
351,
4
] | [
357,
26
] | python | en | ['en', 'error', 'th'] | False |
Apps.clear_cache | (self) |
Clears all internal caches, for methods that alter the app registry.
This is mostly used in tests.
|
Clears all internal caches, for methods that alter the app registry. | def clear_cache(self):
"""
Clears all internal caches, for methods that alter the app registry.
This is mostly used in tests.
"""
# Call expire cache on each model. This will purge
# the relation tree and the fields cache.
self.get_models.cache_clear()
if... | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"# Call expire cache on each model. This will purge",
"# the relation tree and the fields cache.",
"self",
".",
"get_models",
".",
"cache_clear",
"(",
")",
"if",
"self",
".",
"ready",
":",
"# Circumvent self.get_models() to prevent... | [
359,
4
] | [
373,
47
] | python | en | ['en', 'error', 'th'] | False |
Apps.lazy_model_operation | (self, function, *model_keys) |
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed to this method must accept exactly n models as
arguments, w... |
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments. | def lazy_model_operation(self, function, *model_keys):
"""
Take a function and a number of ("app_label", "modelname") tuples, and
when all the corresponding models have been imported and registered,
call the function with the model classes as its arguments.
The function passed t... | [
"def",
"lazy_model_operation",
"(",
"self",
",",
"function",
",",
"*",
"model_keys",
")",
":",
"# Base case: no arguments, just execute the function.",
"if",
"not",
"model_keys",
":",
"function",
"(",
")",
"# Recursive case: take the head of model_keys, wait for the",
"# corr... | [
375,
4
] | [
412,
45
] | python | en | ['en', 'error', 'th'] | False |
Apps.do_pending_operations | (self, model) |
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of `Apps.register_model()`.
|
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of `Apps.register_model()`.
| def do_pending_operations(self, model):
"""
Take a newly-prepared model and pass it to each function waiting for
it. This is called at the very end of `Apps.register_model()`.
"""
key = model._meta.app_label, model._meta.model_name
for function in self._pending_operations... | [
"def",
"do_pending_operations",
"(",
"self",
",",
"model",
")",
":",
"key",
"=",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"_meta",
".",
"model_name",
"for",
"function",
"in",
"self",
".",
"_pending_operations",
".",
"pop",
"(",
"key",
... | [
414,
4
] | [
421,
27
] | python | en | ['en', 'error', 'th'] | False |
looks_like_ci | () |
Return whether it looks like pip is running under CI.
|
Return whether it looks like pip is running under CI.
| def looks_like_ci():
# type: () -> bool
"""
Return whether it looks like pip is running under CI.
"""
# We don't use the method of checking for a tty (e.g. using isatty())
# because some CI systems mimic a tty (e.g. Travis CI). Thus that
# method doesn't provide definitive information in ei... | [
"def",
"looks_like_ci",
"(",
")",
":",
"# type: () -> bool",
"# We don't use the method of checking for a tty (e.g. using isatty())",
"# because some CI systems mimic a tty (e.g. Travis CI). Thus that",
"# method doesn't provide definitive information in either direction.",
"return",
"any",
"... | [
86,
0
] | [
94,
71
] | python | en | ['en', 'error', 'th'] | False |
user_agent | () |
Return a string representing the user agent.
|
Return a string representing the user agent.
| def user_agent():
"""
Return a string representing the user agent.
"""
data = {
"installer": {"name": "pip", "version": __version__},
"python": platform.python_version(),
"implementation": {
"name": platform.python_implementation(),
},
}
if data["impl... | [
"def",
"user_agent",
"(",
")",
":",
"data",
"=",
"{",
"\"installer\"",
":",
"{",
"\"name\"",
":",
"\"pip\"",
",",
"\"version\"",
":",
"__version__",
"}",
",",
"\"python\"",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"\"implementation\"",
":",
"... | [
97,
0
] | [
174,
5
] | python | en | ['en', 'error', 'th'] | False |
PipSession.__init__ | (self, *args, **kwargs) |
:param trusted_hosts: Domains not to emit warnings for when not using
HTTPS.
|
:param trusted_hosts: Domains not to emit warnings for when not using
HTTPS.
| def __init__(self, *args, **kwargs):
"""
:param trusted_hosts: Domains not to emit warnings for when not using
HTTPS.
"""
retries = kwargs.pop("retries", 0)
cache = kwargs.pop("cache", None)
trusted_hosts = kwargs.pop("trusted_hosts", []) # type: List[str]
... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retries",
"=",
"kwargs",
".",
"pop",
"(",
"\"retries\"",
",",
"0",
")",
"cache",
"=",
"kwargs",
".",
"pop",
"(",
"\"cache\"",
",",
"None",
")",
"trusted_hosts",
"... | [
230,
4
] | [
304,
62
] | python | en | ['en', 'error', 'th'] | False |
PipSession.update_index_urls | (self, new_index_urls) |
:param new_index_urls: New index urls to update the authentication
handler with.
|
:param new_index_urls: New index urls to update the authentication
handler with.
| def update_index_urls(self, new_index_urls):
# type: (List[str]) -> None
"""
:param new_index_urls: New index urls to update the authentication
handler with.
"""
self.auth.index_urls = new_index_urls | [
"def",
"update_index_urls",
"(",
"self",
",",
"new_index_urls",
")",
":",
"# type: (List[str]) -> None",
"self",
".",
"auth",
".",
"index_urls",
"=",
"new_index_urls"
] | [
306,
4
] | [
312,
45
] | python | en | ['en', 'error', 'th'] | False |
PipSession.add_trusted_host | (self, host, source=None, suppress_logging=False) |
:param host: It is okay to provide a host that has previously been
added.
:param source: An optional source string, for logging where the host
string came from.
|
:param host: It is okay to provide a host that has previously been
added.
:param source: An optional source string, for logging where the host
string came from.
| def add_trusted_host(self, host, source=None, suppress_logging=False):
# type: (str, Optional[str], bool) -> None
"""
:param host: It is okay to provide a host that has previously been
added.
:param source: An optional source string, for logging where the host
str... | [
"def",
"add_trusted_host",
"(",
"self",
",",
"host",
",",
"source",
"=",
"None",
",",
"suppress_logging",
"=",
"False",
")",
":",
"# type: (str, Optional[str], bool) -> None",
"if",
"not",
"suppress_logging",
":",
"msg",
"=",
"'adding trusted host: {!r}'",
".",
"for... | [
314,
4
] | [
341,
13
] | python | en | ['en', 'error', 'th'] | False |
skip_if_json_module | (f) | Skip a test if a Python json module *is* available | Skip a test if a Python json module *is* available | def skip_if_json_module(f):
"""Skip a test if a Python json module *is* available"""
@wraps(f)
def skip_if_json_module_(self):
if psycopg2.extras.json is not None:
return self.skipTest("json module is available")
return f(self)
return skip_if_json_module_ | [
"def",
"skip_if_json_module",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"skip_if_json_module_",
"(",
"self",
")",
":",
"if",
"psycopg2",
".",
"extras",
".",
"json",
"is",
"not",
"None",
":",
"return",
"self",
".",
"skipTest",
"(",
"\"json... | [
829,
0
] | [
838,
31
] | python | en | ['en', 'en', 'en'] | True |
skip_if_no_json_module | (f) | Skip a test if no Python json module is available | Skip a test if no Python json module is available | def skip_if_no_json_module(f):
"""Skip a test if no Python json module is available"""
@wraps(f)
def skip_if_no_json_module_(self):
if psycopg2.extras.json is None:
return self.skipTest("json module not available")
return f(self)
return skip_if_no_json_module_ | [
"def",
"skip_if_no_json_module",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"skip_if_no_json_module_",
"(",
"self",
")",
":",
"if",
"psycopg2",
".",
"extras",
".",
"json",
"is",
"None",
":",
"return",
"self",
".",
"skipTest",
"(",
"\"json mo... | [
841,
0
] | [
850,
34
] | python | en | ['en', 'en', 'en'] | True |
skip_if_no_json_type | (f) | Skip a test if PostgreSQL json type is not available | Skip a test if PostgreSQL json type is not available | def skip_if_no_json_type(f):
"""Skip a test if PostgreSQL json type is not available"""
@wraps(f)
def skip_if_no_json_type_(self):
curs = self.conn.cursor()
curs.execute("select oid from pg_type where typname = 'json'")
if not curs.fetchone():
return self.skipTest("json n... | [
"def",
"skip_if_no_json_type",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"skip_if_no_json_type_",
"(",
"self",
")",
":",
"curs",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"curs",
".",
"execute",
"(",
"\"select oid from pg_type where ... | [
853,
0
] | [
864,
32
] | python | en | ['en', 'en', 'en'] | True |
bulk_create_users | (
realm: Realm,
users_raw: Set[Tuple[str, str, bool]],
bot_type: Optional[int] = None,
bot_owner: Optional[UserProfile] = None,
tos_version: Optional[str] = None,
timezone: str = "",
) |
Creates and saves a UserProfile with the given email.
Has some code based off of UserManage.create_user, but doesn't .save()
|
Creates and saves a UserProfile with the given email.
Has some code based off of UserManage.create_user, but doesn't .save()
| def bulk_create_users(
realm: Realm,
users_raw: Set[Tuple[str, str, bool]],
bot_type: Optional[int] = None,
bot_owner: Optional[UserProfile] = None,
tos_version: Optional[str] = None,
timezone: str = "",
) -> None:
"""
Creates and saves a UserProfile with the given email.
Has some co... | [
"def",
"bulk_create_users",
"(",
"realm",
":",
"Realm",
",",
"users_raw",
":",
"Set",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"bool",
"]",
"]",
",",
"bot_type",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"bot_owner",
":",
"Optional",
"[",... | [
10,
0
] | [
95,
61
] | python | en | ['en', 'error', 'th'] | False |
DataSource.__iter__ | (self) | Allows for iteration over the layers in a data source. | Allows for iteration over the layers in a data source. | def __iter__(self):
"Allows for iteration over the layers in a data source."
for i in range(self.layer_count):
yield self[i] | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"layer_count",
")",
":",
"yield",
"self",
"[",
"i",
"]"
] | [
88,
4
] | [
91,
25
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__getitem__ | (self, index) | Allows use of the index [] operator to get a layer at the index. | Allows use of the index [] operator to get a layer at the index. | def __getitem__(self, index):
"Allows use of the index [] operator to get a layer at the index."
if isinstance(index, six.string_types):
layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
if not layer:
raise OGRIndexError('invalid OGR Layer name given: "... | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"six",
".",
"string_types",
")",
":",
"layer",
"=",
"capi",
".",
"get_layer_by_name",
"(",
"self",
".",
"ptr",
",",
"force_bytes",
"(",
"index",
")",
")",... | [
93,
4
] | [
105,
33
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__len__ | (self) | Returns the number of layers within the data source. | Returns the number of layers within the data source. | def __len__(self):
"Returns the number of layers within the data source."
return self.layer_count | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"layer_count"
] | [
107,
4
] | [
109,
31
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__str__ | (self) | Returns OGR GetName and Driver for the Data Source. | Returns OGR GetName and Driver for the Data Source. | def __str__(self):
"Returns OGR GetName and Driver for the Data Source."
return '%s (%s)' % (self.name, str(self.driver)) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'%s (%s)'",
"%",
"(",
"self",
".",
"name",
",",
"str",
"(",
"self",
".",
"driver",
")",
")"
] | [
111,
4
] | [
113,
56
] | python | en | ['en', 'en', 'en'] | True |
DataSource.layer_count | (self) | Returns the number of layers in the data source. | Returns the number of layers in the data source. | def layer_count(self):
"Returns the number of layers in the data source."
return capi.get_layer_count(self._ptr) | [
"def",
"layer_count",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_layer_count",
"(",
"self",
".",
"_ptr",
")"
] | [
116,
4
] | [
118,
46
] | python | en | ['en', 'en', 'en'] | True |
DataSource.name | (self) | Returns the name of the data source. | Returns the name of the data source. | def name(self):
"Returns the name of the data source."
name = capi.get_ds_name(self._ptr)
return force_text(name, self.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_ds_name",
"(",
"self",
".",
"_ptr",
")",
"return",
"force_text",
"(",
"name",
",",
"self",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
121,
4
] | [
124,
65
] | python | en | ['en', 'en', 'en'] | True |
TargetPython.__init__ | (
self,
platforms=None, # type: Optional[List[str]]
py_version_info=None, # type: Optional[Tuple[int, ...]]
abis=None, # type: Optional[List[str]]
implementation=None, # type: Optional[str]
) |
:param platforms: A list of strings or None. If None, searches for
packages that are supported by the current system. Otherwise, will
find packages that can be built on the platforms passed in. These
packages will only be downloaded for distribution: they will
no... |
:param platforms: A list of strings or None. If None, searches for
packages that are supported by the current system. Otherwise, will
find packages that can be built on the platforms passed in. These
packages will only be downloaded for distribution: they will
no... | def __init__(
self,
platforms=None, # type: Optional[List[str]]
py_version_info=None, # type: Optional[Tuple[int, ...]]
abis=None, # type: Optional[List[str]]
implementation=None, # type: Optional[str]
):
# type: (...) -> None
"""
:param platforms:... | [
"def",
"__init__",
"(",
"self",
",",
"platforms",
"=",
"None",
",",
"# type: Optional[List[str]]",
"py_version_info",
"=",
"None",
",",
"# type: Optional[Tuple[int, ...]]",
"abis",
"=",
"None",
",",
"# type: Optional[List[str]]",
"implementation",
"=",
"None",
",",
"#... | [
29,
4
] | [
68,
31
] | python | en | ['en', 'error', 'th'] | False |
TargetPython.format_given | (self) |
Format the given, non-None attributes for display.
|
Format the given, non-None attributes for display.
| def format_given(self):
# type: () -> str
"""
Format the given, non-None attributes for display.
"""
display_version = None
if self._given_py_version_info is not None:
display_version = '.'.join(
str(part) for part in self._given_py_version_inf... | [
"def",
"format_given",
"(",
"self",
")",
":",
"# type: () -> str",
"display_version",
"=",
"None",
"if",
"self",
".",
"_given_py_version_info",
"is",
"not",
"None",
":",
"display_version",
"=",
"'.'",
".",
"join",
"(",
"str",
"(",
"part",
")",
"for",
"part",... | [
70,
4
] | [
90,
9
] | python | en | ['en', 'error', 'th'] | False |
TargetPython.get_tags | (self) |
Return the supported PEP 425 tags to check wheel candidates against.
The tags are returned in order of preference (most preferred first).
|
Return the supported PEP 425 tags to check wheel candidates against. | def get_tags(self):
# type: () -> List[Tag]
"""
Return the supported PEP 425 tags to check wheel candidates against.
The tags are returned in order of preference (most preferred first).
"""
if self._valid_tags is None:
# Pass versions=None if no py_version_in... | [
"def",
"get_tags",
"(",
"self",
")",
":",
"# type: () -> List[Tag]",
"if",
"self",
".",
"_valid_tags",
"is",
"None",
":",
"# Pass versions=None if no py_version_info was given since",
"# versions=None uses special default logic.",
"py_version_info",
"=",
"self",
".",
"_given_... | [
92,
4
] | [
116,
31
] | python | en | ['en', 'error', 'th'] | False |
ResourceMixin.accessible_objects | (cls, accessor, role_field) |
Use instead of `MyModel.objects` when you want to only consider
resources that a user has specific permissions for. For example:
MyModel.accessible_objects(user, 'read_role').filter(name__istartswith='bar');
NOTE: This should only be used for list type things. If you have a
spec... |
Use instead of `MyModel.objects` when you want to only consider
resources that a user has specific permissions for. For example:
MyModel.accessible_objects(user, 'read_role').filter(name__istartswith='bar');
NOTE: This should only be used for list type things. If you have a
spec... | def accessible_objects(cls, accessor, role_field):
"""
Use instead of `MyModel.objects` when you want to only consider
resources that a user has specific permissions for. For example:
MyModel.accessible_objects(user, 'read_role').filter(name__istartswith='bar');
NOTE: This should... | [
"def",
"accessible_objects",
"(",
"cls",
",",
"accessor",
",",
"role_field",
")",
":",
"return",
"ResourceMixin",
".",
"_accessible_objects",
"(",
"cls",
",",
"accessor",
",",
"role_field",
")"
] | [
51,
4
] | [
61,
75
] | python | en | ['en', 'error', 'th'] | False |
ResourceMixin.get_permissions | (self, accessor) |
Returns a string list of the roles a accessor has for a given resource.
An accessor can be either a User, Role, or an arbitrary resource that
contains one or more Roles associated with it.
|
Returns a string list of the roles a accessor has for a given resource.
An accessor can be either a User, Role, or an arbitrary resource that
contains one or more Roles associated with it.
| def get_permissions(self, accessor):
"""
Returns a string list of the roles a accessor has for a given resource.
An accessor can be either a User, Role, or an arbitrary resource that
contains one or more Roles associated with it.
"""
return get_roles_on_resource(self, ac... | [
"def",
"get_permissions",
"(",
"self",
",",
"accessor",
")",
":",
"return",
"get_roles_on_resource",
"(",
"self",
",",
"accessor",
")"
] | [
88,
4
] | [
95,
52
] | python | en | ['en', 'error', 'th'] | False |
SurveyJobTemplateMixin._update_unified_job_kwargs | (self, create_kwargs, kwargs) |
Combine extra_vars with variable precedence order:
JT extra_vars -> JT survey defaults -> runtime extra_vars
:param create_kwargs: key-worded arguments to be updated and later used for creating unified job.
:type create_kwargs: dict
:param kwargs: request parameters used to o... |
Combine extra_vars with variable precedence order:
JT extra_vars -> JT survey defaults -> runtime extra_vars | def _update_unified_job_kwargs(self, create_kwargs, kwargs):
"""
Combine extra_vars with variable precedence order:
JT extra_vars -> JT survey defaults -> runtime extra_vars
:param create_kwargs: key-worded arguments to be updated and later used for creating unified job.
:type... | [
"def",
"_update_unified_job_kwargs",
"(",
"self",
",",
"create_kwargs",
",",
"kwargs",
")",
":",
"# Job Template extra_vars",
"extra_vars",
"=",
"self",
".",
"extra_vars_dict",
"survey_defaults",
"=",
"{",
"}",
"# transform to dict",
"if",
"'extra_vars'",
"in",
"kwarg... | [
131,
4
] | [
180,
28
] | python | en | ['en', 'error', 'th'] | False |
SurveyJobTemplateMixin.pivot_spec | (spec) |
Utility method that will return a dictionary keyed off variable names
|
Utility method that will return a dictionary keyed off variable names
| def pivot_spec(spec):
"""
Utility method that will return a dictionary keyed off variable names
"""
pivoted = {}
for element_data in spec.get('spec', []):
if 'variable' in element_data:
pivoted[element_data['variable']] = element_data
return pi... | [
"def",
"pivot_spec",
"(",
"spec",
")",
":",
"pivoted",
"=",
"{",
"}",
"for",
"element_data",
"in",
"spec",
".",
"get",
"(",
"'spec'",
",",
"[",
"]",
")",
":",
"if",
"'variable'",
"in",
"element_data",
":",
"pivoted",
"[",
"element_data",
"[",
"'variabl... | [
333,
4
] | [
341,
22
] | python | en | ['en', 'error', 'th'] | False |
SurveyJobTemplateMixin.display_survey_spec | (self) |
Hide encrypted default passwords in survey specs
|
Hide encrypted default passwords in survey specs
| def display_survey_spec(self):
"""
Hide encrypted default passwords in survey specs
"""
survey_spec = deepcopy(self.survey_spec) if self.survey_spec else {}
for field in survey_spec.get('spec', []):
if field.get('type') == 'password':
if 'default' in f... | [
"def",
"display_survey_spec",
"(",
"self",
")",
":",
"survey_spec",
"=",
"deepcopy",
"(",
"self",
".",
"survey_spec",
")",
"if",
"self",
".",
"survey_spec",
"else",
"{",
"}",
"for",
"field",
"in",
"survey_spec",
".",
"get",
"(",
"'spec'",
",",
"[",
"]",
... | [
355,
4
] | [
364,
26
] | python | en | ['en', 'error', 'th'] | False |
SurveyJobMixin.display_extra_vars | (self) |
Hides fields marked as passwords in survey.
|
Hides fields marked as passwords in survey.
| def display_extra_vars(self):
"""
Hides fields marked as passwords in survey.
"""
if self.survey_passwords:
extra_vars = json.loads(self.extra_vars)
for key, value in self.survey_passwords.items():
if key in extra_vars:
extra_va... | [
"def",
"display_extra_vars",
"(",
"self",
")",
":",
"if",
"self",
".",
"survey_passwords",
":",
"extra_vars",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"extra_vars",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"survey_passwords",
".",
"items",
... | [
379,
4
] | [
390,
34
] | python | en | ['en', 'error', 'th'] | False |
SurveyJobMixin.decrypted_extra_vars | (self) |
Decrypts fields marked as passwords in survey.
|
Decrypts fields marked as passwords in survey.
| def decrypted_extra_vars(self):
"""
Decrypts fields marked as passwords in survey.
"""
if self.survey_passwords:
extra_vars = json.loads(self.extra_vars)
for key in self.survey_passwords:
value = extra_vars.get(key)
if value and isi... | [
"def",
"decrypted_extra_vars",
"(",
"self",
")",
":",
"if",
"self",
".",
"survey_passwords",
":",
"extra_vars",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"extra_vars",
")",
"for",
"key",
"in",
"self",
".",
"survey_passwords",
":",
"value",
"=",
"extra_v... | [
392,
4
] | [
404,
34
] | python | en | ['en', 'error', 'th'] | False |
ExecutionEnvironmentMixin.resolve_execution_environment | (self) |
Return the execution environment that should be used when executing a job.
|
Return the execution environment that should be used when executing a job.
| def resolve_execution_environment(self):
"""
Return the execution environment that should be used when executing a job.
"""
if self.execution_environment is not None:
return self.execution_environment
template = getattr(self, 'unified_job_template', None)
if t... | [
"def",
"resolve_execution_environment",
"(",
"self",
")",
":",
"if",
"self",
".",
"execution_environment",
"is",
"not",
"None",
":",
"return",
"self",
".",
"execution_environment",
"template",
"=",
"getattr",
"(",
"self",
",",
"'unified_job_template'",
",",
"None"... | [
464,
4
] | [
481,
50
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.__init__ | (self, file, offset, length) |
Create file object.
:param file: Existing file.
:param offset: Start of region, in bytes.
:param length: Size of region, in bytes.
|
Create file object. | def __init__(self, file, offset, length):
"""
Create file object.
:param file: Existing file.
:param offset: Start of region, in bytes.
:param length: Size of region, in bytes.
"""
self.fh = file
self.pos = 0
self.offset = offset
self.leng... | [
"def",
"__init__",
"(",
"self",
",",
"file",
",",
"offset",
",",
"length",
")",
":",
"self",
".",
"fh",
"=",
"file",
"self",
".",
"pos",
"=",
"0",
"self",
".",
"offset",
"=",
"offset",
"self",
".",
"length",
"=",
"length",
"self",
".",
"fh",
".",... | [
26,
4
] | [
38,
28
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.seek | (self, offset, mode=io.SEEK_SET) |
Move file pointer.
:param offset: Offset in bytes.
:param mode: Starting position. Use 0 for beginning of region, 1
for current offset, and 2 for end of region. You cannot move
the pointer outside the defined region.
|
Move file pointer. | def seek(self, offset, mode=io.SEEK_SET):
"""
Move file pointer.
:param offset: Offset in bytes.
:param mode: Starting position. Use 0 for beginning of region, 1
for current offset, and 2 for end of region. You cannot move
the pointer outside the defined region.
... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"mode",
"=",
"io",
".",
"SEEK_SET",
")",
":",
"if",
"mode",
"==",
"1",
":",
"self",
".",
"pos",
"=",
"self",
".",
"pos",
"+",
"offset",
"elif",
"mode",
"==",
"2",
":",
"self",
".",
"pos",
"=",
"... | [
46,
4
] | [
63,
44
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.tell | (self) |
Get current file pointer.
:returns: Offset from start of region, in bytes.
|
Get current file pointer. | def tell(self):
"""
Get current file pointer.
:returns: Offset from start of region, in bytes.
"""
return self.pos | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"pos"
] | [
65,
4
] | [
71,
23
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.read | (self, n=0) |
Read data.
:param n: Number of bytes to read. If omitted or zero,
read until end of region.
:returns: An 8-bit string.
|
Read data. | def read(self, n=0):
"""
Read data.
:param n: Number of bytes to read. If omitted or zero,
read until end of region.
:returns: An 8-bit string.
"""
if n:
n = min(n, self.length - self.pos)
else:
n = self.length - self.pos
... | [
"def",
"read",
"(",
"self",
",",
"n",
"=",
"0",
")",
":",
"if",
"n",
":",
"n",
"=",
"min",
"(",
"n",
",",
"self",
".",
"length",
"-",
"self",
".",
"pos",
")",
"else",
":",
"n",
"=",
"self",
".",
"length",
"-",
"self",
".",
"pos",
"if",
"n... | [
73,
4
] | [
88,
30
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.readline | (self) |
Read a line of text.
:returns: An 8-bit string.
|
Read a line of text. | def readline(self):
"""
Read a line of text.
:returns: An 8-bit string.
"""
s = b"" if "b" in self.fh.mode else ""
newline_character = b"\n" if "b" in self.fh.mode else "\n"
while True:
c = self.read(1)
if not c:
break
... | [
"def",
"readline",
"(",
"self",
")",
":",
"s",
"=",
"b\"\"",
"if",
"\"b\"",
"in",
"self",
".",
"fh",
".",
"mode",
"else",
"\"\"",
"newline_character",
"=",
"b\"\\n\"",
"if",
"\"b\"",
"in",
"self",
".",
"fh",
".",
"mode",
"else",
"\"\\n\"",
"while",
"... | [
90,
4
] | [
105,
16
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.readlines | (self) |
Read multiple lines of text.
:returns: A list of 8-bit strings.
|
Read multiple lines of text. | def readlines(self):
"""
Read multiple lines of text.
:returns: A list of 8-bit strings.
"""
lines = []
while True:
s = self.readline()
if not s:
break
lines.append(s)
return lines | [
"def",
"readlines",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"s",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"s",
":",
"break",
"lines",
".",
"append",
"(",
"s",
")",
"return",
"lines"
] | [
107,
4
] | [
119,
20
] | python | en | ['en', 'error', 'th'] | False |
gaussian_blur | (in_array, size) | Applies a Gaussian filter to a 2d array.
Parameters
----------
in_array : numpy.array
The array to smooth.
size : int
The half size of the smoothing window.
Returns
-------
a smoothed numpy.array
| Applies a Gaussian filter to a 2d array. | def gaussian_blur(in_array, size):
"""Applies a Gaussian filter to a 2d array.
Parameters
----------
in_array : numpy.array
The array to smooth.
size : int
The half size of the smoothing window.
Returns
-------
a smoothed numpy.array
"""
# expand in_array to fi... | [
"def",
"gaussian_blur",
"(",
"in_array",
",",
"size",
")",
":",
"# expand in_array to fit edge of kernel",
"padded_array",
"=",
"np",
".",
"pad",
"(",
"in_array",
",",
"size",
",",
"'symmetric'",
")",
"# build kernel",
"x",
",",
"y",
"=",
"np",
".",
"mgrid",
... | [
95,
0
] | [
119,
66
] | python | en | ['en', 'lb', 'en'] | True |
_interp_polygon | (polygon, dx) | Interpolates an irregular polygon to a regular step dx.
Interior geometries are also interpolated if they are longer then 3*dx,
otherwise they are ignored.
Parameters
----------
polygon: The shapely.geometry.Polygon instance to interpolate
dx : the step (float)
Returns
-------
an ... | Interpolates an irregular polygon to a regular step dx. | def _interp_polygon(polygon, dx):
"""Interpolates an irregular polygon to a regular step dx.
Interior geometries are also interpolated if they are longer then 3*dx,
otherwise they are ignored.
Parameters
----------
polygon: The shapely.geometry.Polygon instance to interpolate
dx : the step... | [
"def",
"_interp_polygon",
"(",
"polygon",
",",
"dx",
")",
":",
"# remove last (duplex) point to build a LineString from the LinearRing",
"line",
"=",
"shpg",
".",
"LineString",
"(",
"np",
".",
"asarray",
"(",
"polygon",
".",
"exterior",
".",
"xy",
")",
".",
"T",
... | [
122,
0
] | [
156,
40
] | python | en | ['en', 'su', 'en'] | True |
_polygon_to_pix | (polygon) | Transforms polygon coordinates to integer pixel coordinates. It makes
the geometry easier to handle and reduces the number of points.
Parameters
----------
polygon: the shapely.geometry.Polygon instance to transform.
Returns
-------
a shapely.geometry.Polygon class instance.
| Transforms polygon coordinates to integer pixel coordinates. It makes
the geometry easier to handle and reduces the number of points. | def _polygon_to_pix(polygon):
"""Transforms polygon coordinates to integer pixel coordinates. It makes
the geometry easier to handle and reduces the number of points.
Parameters
----------
polygon: the shapely.geometry.Polygon instance to transform.
Returns
-------
a shapely.geometry.P... | [
"def",
"_polygon_to_pix",
"(",
"polygon",
")",
":",
"def",
"project",
"(",
"x",
",",
"y",
")",
":",
"return",
"np",
".",
"rint",
"(",
"x",
")",
".",
"astype",
"(",
"np",
".",
"int64",
")",
",",
"np",
".",
"rint",
"(",
"y",
")",
".",
"astype",
... | [
159,
0
] | [
227,
14
] | python | en | ['en', 'ca', 'en'] | True |
glacier_grid_params | (gdir) | Define the glacier grid map based on the user params. | Define the glacier grid map based on the user params. | def glacier_grid_params(gdir):
"""Define the glacier grid map based on the user params."""
# Get the local map proj params and glacier extent
gdf = gdir.read_shapefile('outlines')
# Get the map proj
utm_proj = salem.check_crs(gdf.crs)
# Get glacier extent
xx, yy = gdf.iloc[0]['geometry'].... | [
"def",
"glacier_grid_params",
"(",
"gdir",
")",
":",
"# Get the local map proj params and glacier extent",
"gdf",
"=",
"gdir",
".",
"read_shapefile",
"(",
"'outlines'",
")",
"# Get the map proj",
"utm_proj",
"=",
"salem",
".",
"check_crs",
"(",
"gdf",
".",
"crs",
")... | [
230,
0
] | [
283,
41
] | python | en | ['en', 'en', 'en'] | True |
define_glacier_region | (gdir, entity=None, source=None) | Very first task after initialization: define the glacier's local grid.
Defines the local projection (Transverse Mercator), centered on the
glacier. There is some options to set the resolution of the local grid.
It can be adapted depending on the size of the glacier with::
dx (m) = d1 * AREA (km) +... | Very first task after initialization: define the glacier's local grid. | def define_glacier_region(gdir, entity=None, source=None):
"""Very first task after initialization: define the glacier's local grid.
Defines the local projection (Transverse Mercator), centered on the
glacier. There is some options to set the resolution of the local grid.
It can be adapted depending on... | [
"def",
"define_glacier_region",
"(",
"gdir",
",",
"entity",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"utm_proj",
",",
"nx",
",",
"ny",
",",
"ulx",
",",
"uly",
",",
"dx",
"=",
"glacier_grid_params",
"(",
"gdir",
")",
"# Back to lon, lat for DEM do... | [
287,
0
] | [
432,
60
] | python | en | ['en', 'en', 'en'] | True |
rasterio_to_gdir | (gdir, input_file, output_file_name,
resampling='cubic') | Reprojects a file that rasterio can read into the glacier directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
input_file : str
path to the file to reproject
output_file_name : str
name of the output file (must be in cfg.BASENAMES)
... | Reprojects a file that rasterio can read into the glacier directory. | def rasterio_to_gdir(gdir, input_file, output_file_name,
resampling='cubic'):
"""Reprojects a file that rasterio can read into the glacier directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
input_file : str
path to th... | [
"def",
"rasterio_to_gdir",
"(",
"gdir",
",",
"input_file",
",",
"output_file_name",
",",
"resampling",
"=",
"'cubic'",
")",
":",
"output_file",
"=",
"gdir",
".",
"get_filepath",
"(",
"output_file_name",
")",
"assert",
"'.tif'",
"in",
"output_file",
",",
"'output... | [
435,
0
] | [
488,
46
] | python | en | ['en', 'en', 'en'] | True |
read_geotiff_dem | (gdir) | Reads (and masks out) the DEM out of the gdir's geotiff file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
Returns
-------
2D np.float32 array
| Reads (and masks out) the DEM out of the gdir's geotiff file. | def read_geotiff_dem(gdir):
"""Reads (and masks out) the DEM out of the gdir's geotiff file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier directory
Returns
-------
2D np.float32 array
"""
with rasterio.open(gdir.get_filepath('dem'), 'r', driver... | [
"def",
"read_geotiff_dem",
"(",
"gdir",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"gdir",
".",
"get_filepath",
"(",
"'dem'",
")",
",",
"'r'",
",",
"driver",
"=",
"'GTiff'",
")",
"as",
"ds",
":",
"topo",
"=",
"ds",
".",
"read",
"(",
"1",
")",
... | [
491,
0
] | [
507,
15
] | python | en | ['en', 'en', 'en'] | True |
process_dem | (gdir) | Reads the DEM from the tiff, attempts to fill voids and apply smooth.
The data is then written to `gridded_data.nc`.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| Reads the DEM from the tiff, attempts to fill voids and apply smooth. | def process_dem(gdir):
"""Reads the DEM from the tiff, attempts to fill voids and apply smooth.
The data is then written to `gridded_data.nc`.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
"""
# open srtm tif-file:
dem = read_geotiff_de... | [
"def",
"process_dem",
"(",
"gdir",
")",
":",
"# open srtm tif-file:",
"dem",
"=",
"read_geotiff_dem",
"(",
"gdir",
")",
"# Grid",
"nx",
"=",
"gdir",
".",
"grid",
".",
"nx",
"ny",
"=",
"gdir",
".",
"grid",
".",
"ny",
"# Correct the DEM",
"valid_mask",
"=",
... | [
562,
0
] | [
660,
37
] | python | en | ['en', 'en', 'en'] | True |
glacier_masks | (gdir) | Makes a gridded mask of the glacier outlines that can be used by OGGM.
For a more robust solution (not OGGM compatible) see simple_glacier_masks.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| Makes a gridded mask of the glacier outlines that can be used by OGGM. | def glacier_masks(gdir):
"""Makes a gridded mask of the glacier outlines that can be used by OGGM.
For a more robust solution (not OGGM compatible) see simple_glacier_masks.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
"""
# In case nomina... | [
"def",
"glacier_masks",
"(",
"gdir",
")",
":",
"# In case nominal, just raise",
"if",
"gdir",
".",
"is_nominal",
":",
"raise",
"GeometryError",
"(",
"'{} is a nominal glacier.'",
".",
"format",
"(",
"gdir",
".",
"rgi_id",
")",
")",
"if",
"not",
"os",
".",
"pat... | [
664,
0
] | [
792,
46
] | python | en | ['en', 'en', 'en'] | True |
simple_glacier_masks | (gdir, write_hypsometry=False) | Compute glacier masks based on much simpler rules than OGGM's default.
This is therefore more robust: we use this function to compute glacier
hypsometries.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
write_hypsometry : bool
whether to ... | Compute glacier masks based on much simpler rules than OGGM's default. | def simple_glacier_masks(gdir, write_hypsometry=False):
"""Compute glacier masks based on much simpler rules than OGGM's default.
This is therefore more robust: we use this function to compute glacier
hypsometries.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to... | [
"def",
"simple_glacier_masks",
"(",
"gdir",
",",
"write_hypsometry",
"=",
"False",
")",
":",
"# In case nominal, just raise",
"if",
"gdir",
".",
"is_nominal",
":",
"raise",
"GeometryError",
"(",
"'{} is a nominal glacier.'",
".",
"format",
"(",
"gdir",
".",
"rgi_id"... | [
796,
0
] | [
959,
59
] | python | en | ['en', 'da', 'en'] | True |
rasterio_glacier_mask | (gdir, source=None) | Writes a 1-0 glacier mask GeoTiff with the same dimensions as dem.tif
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier in question
source : str
- None (default): the task reads `dem.tif` from the GDir root
- 'ALL': try to open any folder from `utils.D... | Writes a 1-0 glacier mask GeoTiff with the same dimensions as dem.tif | def rasterio_glacier_mask(gdir, source=None):
"""Writes a 1-0 glacier mask GeoTiff with the same dimensions as dem.tif
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
the glacier in question
source : str
- None (default): the task reads `dem.tif` from the GDir root
... | [
"def",
"rasterio_glacier_mask",
"(",
"gdir",
",",
"source",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"dempath",
"=",
"gdir",
".",
"get_filepath",
"(",
"'dem'",
")",
"elif",
"source",
"in",
"utils",
".",
"DEM_SOURCES",
":",
"dempath",
"="... | [
963,
0
] | [
1037,
37
] | python | en | ['en', 'en', 'en'] | True |
gridded_attributes | (gdir) | Adds attributes to the gridded file, useful for thickness interpolation.
This could be useful for distributed ice thickness models.
The raster data are added to the gridded_data file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| Adds attributes to the gridded file, useful for thickness interpolation. | def gridded_attributes(gdir):
"""Adds attributes to the gridded file, useful for thickness interpolation.
This could be useful for distributed ice thickness models.
The raster data are added to the gridded_data file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where ... | [
"def",
"gridded_attributes",
"(",
"gdir",
")",
":",
"# Variables",
"grids_file",
"=",
"gdir",
".",
"get_filepath",
"(",
"'gridded_data'",
")",
"with",
"ncDataset",
"(",
"grids_file",
")",
"as",
"nc",
":",
"topo_smoothed",
"=",
"nc",
".",
"variables",
"[",
"'... | [
1041,
0
] | [
1155,
30
] | python | en | ['en', 'en', 'en'] | True |
_all_inflows | (cls, cl) | Find all centerlines flowing into the centerline examined.
Parameters
----------
cls : list
all centerlines of the examined glacier
cline : Centerline
centerline to control
Returns
-------
list of strings of centerlines
| Find all centerlines flowing into the centerline examined. | def _all_inflows(cls, cl):
"""Find all centerlines flowing into the centerline examined.
Parameters
----------
cls : list
all centerlines of the examined glacier
cline : Centerline
centerline to control
Returns
-------
list of strings of centerlines
"""
ixs = [... | [
"def",
"_all_inflows",
"(",
"cls",
",",
"cl",
")",
":",
"ixs",
"=",
"[",
"str",
"(",
"cls",
".",
"index",
"(",
"cl",
".",
"inflows",
"[",
"i",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"cl",
".",
"inflows",
")",
")",
"]",
"... | [
1158,
0
] | [
1176,
14
] | python | en | ['en', 'en', 'en'] | True |
gridded_mb_attributes | (gdir) | Adds mass-balance related attributes to the gridded data file.
This could be useful for distributed ice thickness models.
The raster data are added to the gridded_data file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
| Adds mass-balance related attributes to the gridded data file. | def gridded_mb_attributes(gdir):
"""Adds mass-balance related attributes to the gridded data file.
This could be useful for distributed ice thickness models.
The raster data are added to the gridded_data file.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to writ... | [
"def",
"gridded_mb_attributes",
"(",
"gdir",
")",
":",
"from",
"oggm",
".",
"core",
".",
"massbalance",
"import",
"LinearMassBalance",
",",
"ConstantMassBalance",
"from",
"oggm",
".",
"core",
".",
"centerlines",
"import",
"line_inflows",
"# Get the input data",
"wit... | [
1180,
0
] | [
1391,
39
] | python | en | ['en', 'en', 'en'] | True |
merged_glacier_masks | (gdir, geometry) | Makes a gridded mask of a merged glacier outlines.
This is a simplified version of glacier_masks. We don't need fancy
corrections or smoothing here: The flowlines for the actual model run are
based on a proper call of glacier_masks.
This task is only to get outlines etc. for visualization!
Parame... | Makes a gridded mask of a merged glacier outlines. | def merged_glacier_masks(gdir, geometry):
"""Makes a gridded mask of a merged glacier outlines.
This is a simplified version of glacier_masks. We don't need fancy
corrections or smoothing here: The flowlines for the actual model run are
based on a proper call of glacier_masks.
This task is only to... | [
"def",
"merged_glacier_masks",
"(",
"gdir",
",",
"geometry",
")",
":",
"# open srtm tif-file:",
"dem",
"=",
"read_geotiff_dem",
"(",
"gdir",
")",
"if",
"np",
".",
"min",
"(",
"dem",
")",
"==",
"np",
".",
"max",
"(",
"dem",
")",
":",
"raise",
"RuntimeErro... | [
1394,
0
] | [
1507,
47
] | python | en | ['en', 'da', 'en'] | True |
gridded_data_var_to_geotiff | (gdir, varname, fname=None) | Writes a NetCDF variable to a georeferenced geotiff file.
The geotiff file will be written in the gdir directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
varname : str
variable name in gridded_data.nc
fname : str
output fil... | Writes a NetCDF variable to a georeferenced geotiff file. | def gridded_data_var_to_geotiff(gdir, varname, fname=None):
"""Writes a NetCDF variable to a georeferenced geotiff file.
The geotiff file will be written in the gdir directory.
Parameters
----------
gdir : :py:class:`oggm.GlacierDirectory`
where to write the data
varname : str
... | [
"def",
"gridded_data_var_to_geotiff",
"(",
"gdir",
",",
"varname",
",",
"fname",
"=",
"None",
")",
":",
"# Assign the output path",
"if",
"fname",
"is",
"None",
":",
"fname",
"=",
"varname",
"+",
"'.tif'",
"outpath",
"=",
"os",
".",
"path",
".",
"join",
"(... | [
1511,
0
] | [
1555,
30
] | python | en | ['en', 'en', 'en'] | True |
cc_puzzle_for_inner_puzzle | (mod_code, genesis_coin_checker, inner_puzzle) |
Given an inner puzzle, generate a puzzle program for a specific cc.
|
Given an inner puzzle, generate a puzzle program for a specific cc.
| def cc_puzzle_for_inner_puzzle(mod_code, genesis_coin_checker, inner_puzzle) -> Program:
"""
Given an inner puzzle, generate a puzzle program for a specific cc.
"""
return mod_code.curry(mod_code.get_tree_hash(), genesis_coin_checker, inner_puzzle) | [
"def",
"cc_puzzle_for_inner_puzzle",
"(",
"mod_code",
",",
"genesis_coin_checker",
",",
"inner_puzzle",
")",
"->",
"Program",
":",
"return",
"mod_code",
".",
"curry",
"(",
"mod_code",
".",
"get_tree_hash",
"(",
")",
",",
"genesis_coin_checker",
",",
"inner_puzzle",
... | [
37,
0
] | [
41,
87
] | python | en | ['en', 'error', 'th'] | False |
cc_puzzle_hash_for_inner_puzzle_hash | (mod_code, genesis_coin_checker, inner_puzzle_hash) |
Given an inner puzzle hash, calculate a puzzle program hash for a specific cc.
|
Given an inner puzzle hash, calculate a puzzle program hash for a specific cc.
| def cc_puzzle_hash_for_inner_puzzle_hash(mod_code, genesis_coin_checker, inner_puzzle_hash) -> bytes32:
"""
Given an inner puzzle hash, calculate a puzzle program hash for a specific cc.
"""
gcc_hash = genesis_coin_checker.get_tree_hash()
return mod_code.curry(mod_code.get_tree_hash(), gcc_hash, inn... | [
"def",
"cc_puzzle_hash_for_inner_puzzle_hash",
"(",
"mod_code",
",",
"genesis_coin_checker",
",",
"inner_puzzle_hash",
")",
"->",
"bytes32",
":",
"gcc_hash",
"=",
"genesis_coin_checker",
".",
"get_tree_hash",
"(",
")",
"return",
"mod_code",
".",
"curry",
"(",
"mod_cod... | [
45,
0
] | [
52,
5
] | python | en | ['en', 'error', 'th'] | False |
subtotals_for_deltas | (deltas) |
Given a list of deltas corresponding to input coins, create the "subtotals" list
needed in solutions spending those coins.
|
Given a list of deltas corresponding to input coins, create the "subtotals" list
needed in solutions spending those coins.
| def subtotals_for_deltas(deltas) -> List[int]:
"""
Given a list of deltas corresponding to input coins, create the "subtotals" list
needed in solutions spending those coins.
"""
subtotals = []
subtotal = 0
for delta in deltas:
subtotals.append(subtotal)
subtotal += delta
... | [
"def",
"subtotals_for_deltas",
"(",
"deltas",
")",
"->",
"List",
"[",
"int",
"]",
":",
"subtotals",
"=",
"[",
"]",
"subtotal",
"=",
"0",
"for",
"delta",
"in",
"deltas",
":",
"subtotals",
".",
"append",
"(",
"subtotal",
")",
"subtotal",
"+=",
"delta",
"... | [
64,
0
] | [
80,
20
] | python | en | ['en', 'error', 'th'] | False |
spend_bundle_for_spendable_ccs | (
mod_code: Program,
genesis_coin_checker: Program,
spendable_cc_list: List[SpendableCC],
inner_solutions: List[Program],
sigs: Optional[List[G2Element]] = [],
) |
Given a list of `SpendableCC` objects and inner solutions for those objects, create a `SpendBundle`
that spends all those coins. Note that it the signature is not calculated it, so the caller is responsible
for fixing it.
|
Given a list of `SpendableCC` objects and inner solutions for those objects, create a `SpendBundle`
that spends all those coins. Note that it the signature is not calculated it, so the caller is responsible
for fixing it.
| def spend_bundle_for_spendable_ccs(
mod_code: Program,
genesis_coin_checker: Program,
spendable_cc_list: List[SpendableCC],
inner_solutions: List[Program],
sigs: Optional[List[G2Element]] = [],
) -> SpendBundle:
"""
Given a list of `SpendableCC` objects and inner solutions for those objects,... | [
"def",
"spend_bundle_for_spendable_ccs",
"(",
"mod_code",
":",
"Program",
",",
"genesis_coin_checker",
":",
"Program",
",",
"spendable_cc_list",
":",
"List",
"[",
"SpendableCC",
"]",
",",
"inner_solutions",
":",
"List",
"[",
"Program",
"]",
",",
"sigs",
":",
"Op... | [
99,
0
] | [
165,
72
] | python | en | ['en', 'error', 'th'] | False |
is_cc_mod | (inner_f: Program) |
You may want to generalize this if different `CC_MOD` templates are supported.
|
You may want to generalize this if different `CC_MOD` templates are supported.
| def is_cc_mod(inner_f: Program):
"""
You may want to generalize this if different `CC_MOD` templates are supported.
"""
return inner_f == CC_MOD | [
"def",
"is_cc_mod",
"(",
"inner_f",
":",
"Program",
")",
":",
"return",
"inner_f",
"==",
"CC_MOD"
] | [
168,
0
] | [
172,
28
] | python | en | ['en', 'error', 'th'] | False |
uncurry_cc | (puzzle: Program) |
Take a puzzle and return `None` if it's not a `CC_MOD` cc, or
a triple of `mod_hash, genesis_coin_checker, inner_puzzle` if it is.
|
Take a puzzle and return `None` if it's not a `CC_MOD` cc, or
a triple of `mod_hash, genesis_coin_checker, inner_puzzle` if it is.
| def uncurry_cc(puzzle: Program) -> Optional[Tuple[Program, Program, Program]]:
"""
Take a puzzle and return `None` if it's not a `CC_MOD` cc, or
a triple of `mod_hash, genesis_coin_checker, inner_puzzle` if it is.
"""
r = puzzle.uncurry()
if r is None:
return r
inner_f, args = r
... | [
"def",
"uncurry_cc",
"(",
"puzzle",
":",
"Program",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"Program",
",",
"Program",
",",
"Program",
"]",
"]",
":",
"r",
"=",
"puzzle",
".",
"uncurry",
"(",
")",
"if",
"r",
"is",
"None",
":",
"return",
"r",
"inne... | [
183,
0
] | [
196,
55
] | python | en | ['en', 'error', 'th'] | False |
spendable_cc_list_from_coin_solution | (coin_solution: CoinSolution, hash_to_puzzle_f) |
Given a `CoinSolution`, extract out a list of `SpendableCC` objects.
Since `SpendableCC` needs to track the inner puzzles and a `Coin` only includes
puzzle hash, we also need a `hash_to_puzzle_f` function that turns puzzle hashes into
the corresponding puzzles. This is generally either a `dict` or som... |
Given a `CoinSolution`, extract out a list of `SpendableCC` objects. | def spendable_cc_list_from_coin_solution(coin_solution: CoinSolution, hash_to_puzzle_f) -> List[SpendableCC]:
"""
Given a `CoinSolution`, extract out a list of `SpendableCC` objects.
Since `SpendableCC` needs to track the inner puzzles and a `Coin` only includes
puzzle hash, we also need a `hash_to_pu... | [
"def",
"spendable_cc_list_from_coin_solution",
"(",
"coin_solution",
":",
"CoinSolution",
",",
"hash_to_puzzle_f",
")",
"->",
"List",
"[",
"SpendableCC",
"]",
":",
"spendable_cc_list",
"=",
"[",
"]",
"coin",
"=",
"coin_solution",
".",
"coin",
"puzzle",
"=",
"Progr... | [
212,
0
] | [
251,
28
] | python | en | ['en', 'error', 'th'] | False |
MissedMessageNotificationsTest.test_stream_watchers | (self) |
We used to have a bug with stream_watchers, where we set their flags to
None.
|
We used to have a bug with stream_watchers, where we set their flags to
None.
| def test_stream_watchers(self) -> None:
"""
We used to have a bug with stream_watchers, where we set their flags to
None.
"""
cordelia = self.example_user("cordelia")
hamlet = self.example_user("hamlet")
realm = hamlet.realm
stream_name = "Denmark"
... | [
"def",
"test_stream_watchers",
"(",
"self",
")",
"->",
"None",
":",
"cordelia",
"=",
"self",
".",
"example_user",
"(",
"\"cordelia\"",
")",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"realm",
"=",
"hamlet",
".",
"realm",
"stream_name... | [
155,
4
] | [
192,
9
] | python | en | ['en', 'error', 'th'] | False |
MissedMessageNotificationsTest.test_end_to_end_missedmessage_hook | (self) | Tests what arguments missedmessage_hook passes into maybe_enqueue_notifications.
Combined with the previous test, this ensures that the missedmessage_hook is correct | Tests what arguments missedmessage_hook passes into maybe_enqueue_notifications.
Combined with the previous test, this ensures that the missedmessage_hook is correct | def test_end_to_end_missedmessage_hook(self) -> None:
"""Tests what arguments missedmessage_hook passes into maybe_enqueue_notifications.
Combined with the previous test, this ensures that the missedmessage_hook is correct"""
user_profile = self.example_user("hamlet")
user_profile.enabl... | [
"def",
"test_end_to_end_missedmessage_hook",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"user_profile",
".",
"enable_online_push_notifications",
"=",
"False",
"user_profile",
".",
"save",
"(",
")",
... | [
194,
4
] | [
537,
40
] | python | en | ['en', 'en', 'en'] | True |
EventQueueTest.test_event_collapsing | (self) |
The update_message_flags events are special, because
they can be collapsed together. Given two umfe's, we:
* use the latest timestamp
* concatenate the messages
|
The update_message_flags events are special, because
they can be collapsed together. Given two umfe's, we:
* use the latest timestamp
* concatenate the messages
| def test_event_collapsing(self) -> None:
client = self.get_client_descriptor()
queue = client.event_queue
"""
The update_message_flags events are special, because
they can be collapsed together. Given two umfe's, we:
* use the latest timestamp
* concaten... | [
"def",
"test_event_collapsing",
"(",
"self",
")",
"->",
"None",
":",
"client",
"=",
"self",
".",
"get_client_descriptor",
"(",
")",
"queue",
"=",
"client",
".",
"event_queue",
"def",
"umfe",
"(",
"timestamp",
":",
"int",
",",
"messages",
":",
"List",
"[",
... | [
651,
4
] | [
737,
9
] | python | en | ['en', 'error', 'th'] | False |
EventQueueTest.test_collapse_event | (self) |
This mostly focues on the internals of
how we store "virtual_events" that we
can collapse if subsequent events are
of the same form. See the code in
EventQueue.push for more context.
|
This mostly focues on the internals of
how we store "virtual_events" that we
can collapse if subsequent events are
of the same form. See the code in
EventQueue.push for more context.
| def test_collapse_event(self) -> None:
"""
This mostly focues on the internals of
how we store "virtual_events" that we
can collapse if subsequent events are
of the same form. See the code in
EventQueue.push for more context.
"""
client = self.get_client_... | [
"def",
"test_collapse_event",
"(",
"self",
")",
"->",
"None",
":",
"client",
"=",
"self",
".",
"get_client_descriptor",
"(",
")",
"queue",
"=",
"client",
".",
"event_queue",
"queue",
".",
"push",
"(",
"{",
"\"type\"",
":",
"\"restart\"",
",",
"\"server_gener... | [
821,
4
] | [
863,
46
] | python | en | ['en', 'error', 'th'] | False |
CLI.get_config | (self, key) | Helper method for looking up the value of a --conf.xyz flag | Helper method for looking up the value of a --conf.xyz flag | def get_config(self, key):
"""Helper method for looking up the value of a --conf.xyz flag"""
return getattr(self.args, 'conf.{}'.format(key)) | [
"def",
"get_config",
"(",
"self",
",",
"key",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"args",
",",
"'conf.{}'",
".",
"format",
"(",
"key",
")",
")"
] | [
75,
4
] | [
77,
56
] | python | en | ['en', 'en', 'en'] | True |
CLI.authenticate | (self) | Configure the current session (or OAuth2.0 token) | Configure the current session (or OAuth2.0 token) | def authenticate(self):
"""Configure the current session (or OAuth2.0 token)"""
token = self.get_config('token')
if token:
self.root.connection.login(
None,
None,
token=token,
)
else:
config.use_sessions ... | [
"def",
"authenticate",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"get_config",
"(",
"'token'",
")",
"if",
"token",
":",
"self",
".",
"root",
".",
"connection",
".",
"login",
"(",
"None",
",",
"None",
",",
"token",
"=",
"token",
",",
")",
"e... | [
83,
4
] | [
94,
42
] | python | en | ['en', 'en', 'en'] | True |
CLI.connect | (self) | Fetch top-level resources from /api/v2 | Fetch top-level resources from /api/v2 | def connect(self):
"""Fetch top-level resources from /api/v2"""
config.base_url = self.get_config('host')
config.client_connection_attempts = 1
config.assume_untrusted = False
if self.get_config('insecure'):
config.assume_untrusted = True
config.credentials =... | [
"def",
"connect",
"(",
"self",
")",
":",
"config",
".",
"base_url",
"=",
"self",
".",
"get_config",
"(",
"'host'",
")",
"config",
".",
"client_connection_attempts",
"=",
"1",
"config",
".",
"assume_untrusted",
"=",
"False",
"if",
"self",
".",
"get_config",
... | [
96,
4
] | [
131,
17
] | python | en | ['en', 'en', 'en'] | True |
CLI.parse_resource | (self, skip_deprecated=False) | Attempt to parse the <resource> (e.g., jobs) specified on the CLI
If a valid resource is discovered, the user will be authenticated
(either via an OAuth2.0 token or session-based auth) and the remaining
CLI arguments will be processed (to determine the requested action
e.g., list, creat... | Attempt to parse the <resource> (e.g., jobs) specified on the CLI | def parse_resource(self, skip_deprecated=False):
"""Attempt to parse the <resource> (e.g., jobs) specified on the CLI
If a valid resource is discovered, the user will be authenticated
(either via an OAuth2.0 token or session-based auth) and the remaining
CLI arguments will be processed ... | [
"def",
"parse_resource",
"(",
"self",
",",
"skip_deprecated",
"=",
"False",
")",
":",
"self",
".",
"resource",
"=",
"parse_resource",
"(",
"self",
",",
"skip_deprecated",
"=",
"skip_deprecated",
")",
"if",
"self",
".",
"resource",
":",
"self",
".",
"authenti... | [
139,
4
] | [
185,
36
] | python | en | ['en', 'en', 'en'] | True |
CLI.parse_action | (self, page, from_sphinx=False) | Perform an HTTP OPTIONS request
This method performs an HTTP OPTIONS request to build a list of valid
actions, and (if provided) runs the code for the action specified on
the CLI
:param page: a awxkit.api.pages.TentativePage object representing the
top-level resour... | Perform an HTTP OPTIONS request | def parse_action(self, page, from_sphinx=False):
"""Perform an HTTP OPTIONS request
This method performs an HTTP OPTIONS request to build a list of valid
actions, and (if provided) runs the code for the action specified on
the CLI
:param page: a awxkit.api.pages.TentativePage o... | [
"def",
"parse_action",
"(",
"self",
",",
"page",
",",
"from_sphinx",
"=",
"False",
")",
":",
"subparsers",
"=",
"self",
".",
"subparsers",
"[",
"self",
".",
"resource",
"]",
".",
"add_subparsers",
"(",
"dest",
"=",
"'action'",
",",
"metavar",
"=",
"'acti... | [
187,
4
] | [
277,
51
] | python | en | ['en', 'en', 'en'] | True |
CLI.parse_args | (self, argv, env=None) | Configure the global parser.ArgumentParser object and apply
global flags (such as --help, authentication, and formatting arguments)
| Configure the global parser.ArgumentParser object and apply
global flags (such as --help, authentication, and formatting arguments)
| def parse_args(self, argv, env=None):
"""Configure the global parser.ArgumentParser object and apply
global flags (such as --help, authentication, and formatting arguments)
"""
env = env or os.environ
self.argv = argv
self.parser = HelpfulArgumentParser(add_help=False)
... | [
"def",
"parse_args",
"(",
"self",
",",
"argv",
",",
"env",
"=",
"None",
")",
":",
"env",
"=",
"env",
"or",
"os",
".",
"environ",
"self",
".",
"argv",
"=",
"argv",
"self",
".",
"parser",
"=",
"HelpfulArgumentParser",
"(",
"add_help",
"=",
"False",
")"... | [
279,
4
] | [
304,
67
] | python | en | ['en', 'en', 'en'] | True |
RedirectStreamTestCase.test_file_limit | (self) |
Check that we don't leave file handles unclosed.
|
Check that we don't leave file handles unclosed.
| def test_file_limit(self):
"""
Check that we don't leave file handles unclosed.
"""
max_files = resource.getrlimit(resource.RLIMIT_NOFILE)[1] # hard limit
dest = BytesIO()
for _ in range(max_files):
with redirect_stream(sys.__stdout__, dest):
p... | [
"def",
"test_file_limit",
"(",
"self",
")",
":",
"max_files",
"=",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
")",
"[",
"1",
"]",
"# hard limit",
"dest",
"=",
"BytesIO",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"max_files",
")"... | [
7,
4
] | [
15,
20
] | python | en | ['en', 'error', 'th'] | False |
VectorFilter.filter_vectors | (self, input_list) |
Returns subset of specified input list.
|
Returns subset of specified input list.
| def filter_vectors(self, input_list):
"""
Returns subset of specified input list.
"""
raise NotImplementedError | [
"def",
"filter_vectors",
"(",
"self",
",",
"input_list",
")",
":",
"raise",
"NotImplementedError"
] | [
51,
4
] | [
55,
33
] | python | en | ['en', 'error', 'th'] | False |
generate_objects | (artifacts, kwargs) | generate_objects takes a list of artifacts that are supported by
a create function and compares it to the kwargs passed in to the create
function. If a kwarg is found that is not in the artifacts list a RuntimeError
is raised.
| generate_objects takes a list of artifacts that are supported by
a create function and compares it to the kwargs passed in to the create
function. If a kwarg is found that is not in the artifacts list a RuntimeError
is raised.
| def generate_objects(artifacts, kwargs):
"""generate_objects takes a list of artifacts that are supported by
a create function and compares it to the kwargs passed in to the create
function. If a kwarg is found that is not in the artifacts list a RuntimeError
is raised.
"""
for k in kwargs.keys(... | [
"def",
"generate_objects",
"(",
"artifacts",
",",
"kwargs",
")",
":",
"for",
"k",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"artifacts",
":",
"raise",
"RuntimeError",
"(",
"'{} is not a valid argument'",
".",
"format",
"(",
"k",
... | [
5,
0
] | [
14,
53
] | python | en | ['en', 'en', 'en'] | True |
generate_role_objects | (objects) | generate_role_objects assembles a dictionary of all possible objects by name.
It will raise an exception if any of the objects share a name due to the fact that
it is to be used with apply_roles, which expects unique object names.
roles share a common name e.g. admin_role, member_role. This ensures that th... | generate_role_objects assembles a dictionary of all possible objects by name.
It will raise an exception if any of the objects share a name due to the fact that
it is to be used with apply_roles, which expects unique object names. | def generate_role_objects(objects):
"""generate_role_objects assembles a dictionary of all possible objects by name.
It will raise an exception if any of the objects share a name due to the fact that
it is to be used with apply_roles, which expects unique object names.
roles share a common name e.g. ad... | [
"def",
"generate_role_objects",
"(",
"objects",
")",
":",
"combined_objects",
"=",
"{",
"}",
"for",
"o",
"in",
"objects",
":",
"if",
"type",
"(",
"o",
")",
"is",
"dict",
":",
"for",
"k",
",",
"v",
"in",
"o",
".",
"items",
"(",
")",
":",
"if",
"co... | [
17,
0
] | [
39,
27
] | python | en | ['en', 'en', 'en'] | True |
CalculateGeneratorInputInfo | (params) | Calculate the generator specific info that gets fed to input (called by
gyp). | Calculate the generator specific info that gets fed to input (called by
gyp). | def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get("generator_flags", {})
if generator_flags.get("adjust_static_libraries", False):
global generator_wants_static_library_dependencies_adjusted
... | [
"def",
"CalculateGeneratorInputInfo",
"(",
"params",
")",
":",
"generator_flags",
"=",
"params",
".",
"get",
"(",
"\"generator_flags\"",
",",
"{",
"}",
")",
"if",
"generator_flags",
".",
"get",
"(",
"\"adjust_static_libraries\"",
",",
"False",
")",
":",
"global"... | [
56,
0
] | [
75,
5
] | python | en | ['en', 'en', 'en'] | True |
Simple115StateWrapper.observation | (self, observation) | Converts an observation into simple115 format.
Args:
observation: observation that the environment returns
Returns:
(N, 115) shaped representation, where N stands for the number of players
being controlled.
| Converts an observation into simple115 format. | def observation(self, observation):
"""Converts an observation into simple115 format.
Args:
observation: observation that the environment returns
Returns:
(N, 115) shaped representation, where N stands for the number of players
being controlled.
"""
final_obs = []
for obs in ... | [
"def",
"observation",
"(",
"self",
",",
"observation",
")",
":",
"final_obs",
"=",
"[",
"]",
"for",
"obs",
"in",
"observation",
":",
"o",
"=",
"[",
"]",
"o",
".",
"extend",
"(",
"obs",
"[",
"'left_team'",
"]",
".",
"flatten",
"(",
")",
")",
"o",
... | [
100,
2
] | [
145,
48
] | python | en | ['en', 'en', 'en'] | True |
MultiAgentStateWrapper.observation | (self, observation) | Converts an observation into multiagent format.
Args:
observation: observation that the environment returns
Returns:
(N, 4*(self.num_lteam_players+self.num_rteam_players)+16) shaped representation, where N stands for the number of players
being controlled.
| Converts an observation into multiagent format. | def observation(self, observation):
"""Converts an observation into multiagent format.
Args:
observation: observation that the environment returns
Returns:
(N, 4*(self.num_lteam_players+self.num_rteam_players)+16) shaped representation, where N stands for the number of players
being cont... | [
"def",
"observation",
"(",
"self",
",",
"observation",
")",
":",
"final_obs",
"=",
"{",
"}",
"final_obs",
"[",
"'full'",
"]",
"=",
"[",
"]",
"final_obs",
"[",
"'pos'",
"]",
"=",
"[",
"]",
"# The active player can be in the left or the right team.",
"for",
"i",... | [
160,
2
] | [
214,
55
] | python | en | ['en', 'en', 'en'] | True |
connection_from_url | (url, **kw) |
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must include the scheme. Port is optional.
... |
Given a url, return an :class:`.ConnectionPool` instance of its host. | def connection_from_url(url, **kw):
"""
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must... | [
"def",
"connection_from_url",
"(",
"url",
",",
"*",
"*",
"kw",
")",
":",
"scheme",
",",
"host",
",",
"port",
"=",
"get_host",
"(",
"url",
")",
"port",
"=",
"port",
"or",
"port_by_scheme",
".",
"get",
"(",
"scheme",
",",
"80",
")",
"if",
"scheme",
"... | [
1023,
0
] | [
1048,
56
] | python | en | ['en', 'error', 'th'] | False |
_normalize_host | (host, scheme) |
Normalize hosts for comparisons and use with sockets.
|
Normalize hosts for comparisons and use with sockets.
| def _normalize_host(host, scheme):
"""
Normalize hosts for comparisons and use with sockets.
"""
host = normalize_host(host, scheme)
# httplib doesn't like it when we include brackets in IPv6 addresses
# Specifically, if we include brackets but also pass the port then
# httplib crazily dou... | [
"def",
"_normalize_host",
"(",
"host",
",",
"scheme",
")",
":",
"host",
"=",
"normalize_host",
"(",
"host",
",",
"scheme",
")",
"# httplib doesn't like it when we include brackets in IPv6 addresses",
"# Specifically, if we include brackets but also pass the port then",
"# httplib... | [
1051,
0
] | [
1066,
15
] | python | en | ['en', 'error', 'th'] | False |
ConnectionPool.close | (self) |
Close all pooled connections and disable the pool.
|
Close all pooled connections and disable the pool.
| def close(self):
"""
Close all pooled connections and disable the pool.
"""
pass | [
"def",
"close",
"(",
"self",
")",
":",
"pass"
] | [
92,
4
] | [
96,
12
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._new_conn | (self) |
Return a fresh :class:`HTTPConnection`.
|
Return a fresh :class:`HTTPConnection`.
| def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.debug(
"Starting new HTTP connection (%d): %s:%s",
self.num_connections,
self.host,
self.port or "80",
)
conn = self... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Starting new HTTP connection (%d): %s:%s\"",
",",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
"or",
"\"... | [
221,
4
] | [
240,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._get_conn | (self, timeout=None) |
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and raising
:class:`urllib3.exceptions.... |
Get a connection. Will return a pooled connection if one is available. | def _get_conn(self, timeout=None):
"""
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and r... | [
"def",
"_get_conn",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"conn",
"=",
"None",
"try",
":",
"conn",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"block",
"=",
"self",
".",
"block",
",",
"timeout",
"=",
"timeout",
")",
"except",
"Attribut... | [
242,
4
] | [
279,
39
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._put_conn | (self, conn) |
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connec... |
Put a connection back into the pool. | def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
... | [
"def",
"_put_conn",
"(",
"self",
",",
"conn",
")",
":",
"try",
":",
"self",
".",
"pool",
".",
"put",
"(",
"conn",
",",
"block",
"=",
"False",
")",
"return",
"# Everything is dandy, done.",
"except",
"AttributeError",
":",
"# self.pool is None.",
"pass",
"exc... | [
281,
4
] | [
307,
24
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._validate_conn | (self, conn) |
Called right before a request is made, after the socket is created.
|
Called right before a request is made, after the socket is created.
| def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
pass | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"pass"
] | [
309,
4
] | [
313,
12
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._get_timeout | (self, timeout) | Helper that always returns a :class:`urllib3.util.Timeout` | Helper that always returns a :class:`urllib3.util.Timeout` | def _get_timeout(self, timeout):
""" Helper that always returns a :class:`urllib3.util.Timeout` """
if timeout is _Default:
return self.timeout.clone()
if isinstance(timeout, Timeout):
return timeout.clone()
else:
# User passed us an int/float. This i... | [
"def",
"_get_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
"is",
"_Default",
":",
"return",
"self",
".",
"timeout",
".",
"clone",
"(",
")",
"if",
"isinstance",
"(",
"timeout",
",",
"Timeout",
")",
":",
"return",
"timeout",
".",
"clo... | [
319,
4
] | [
329,
46
] | python | en | ['en', 'lb', 'en'] | True |
HTTPConnectionPool._raise_timeout | (self, err, url, timeout_value) | Is the error actually a timeout? Will raise a ReadTimeout or pass | Is the error actually a timeout? Will raise a ReadTimeout or pass | def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % timeout_value
)
# See t... | [
"def",
"_raise_timeout",
"(",
"self",
",",
"err",
",",
"url",
",",
"timeout_value",
")",
":",
"if",
"isinstance",
"(",
"err",
",",
"SocketTimeout",
")",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%... | [
331,
4
] | [
354,
13
] | python | en | ['en', 'en', 'en'] | True |
HTTPConnectionPool._make_request | (
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
) |
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same ... |
Perform a request on a given urllib connection object taken from our
pool. | def _make_request(
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:... | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"chunked",
"=",
"False",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",... | [
356,
4
] | [
473,
31
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.close | (self) |
Close all pooled connections and disable the pool.
|
Close all pooled connections and disable the pool.
| def close(self):
"""
Close all pooled connections and disable the pool.
"""
if self.pool is None:
return
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"pool",
"is",
"None",
":",
"return",
"# Disable access to the pool",
"old_pool",
",",
"self",
".",
"pool",
"=",
"self",
".",
"pool",
",",
"None",
"try",
":",
"while",
"True",
":",
"conn",
"=",
... | [
478,
4
] | [
494,
16
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.is_same_host | (self, url) |
Check if the given ``url`` is a member of the same host as this
connection pool.
|
Check if the given ``url`` is a member of the same host as this
connection pool.
| def is_same_host(self, url):
"""
Check if the given ``url`` is a member of the same host as this
connection pool.
"""
if url.startswith("/"):
return True
# TODO: Add optional support for socket.gethostbyname checking.
scheme, host, port = get_host(url... | [
"def",
"is_same_host",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"return",
"True",
"# TODO: Add optional support for socket.gethostbyname checking.",
"scheme",
",",
"host",
",",
"port",
"=",
"get_host",
"(",
"url"... | [
496,
4
] | [
515,
74
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.urlopen | (
self,
method,
url,
body=None,
headers=None,
retries=None,
redirect=True,
assert_same_host=True,
timeout=_Default,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw
) |
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethod... |
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details. | def urlopen(
self,
method,
url,
body=None,
headers=None,
retries=None,
redirect=True,
assert_same_host=True,
timeout=_Default,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw... | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"retries",
"=",
"None",
",",
"redirect",
"=",
"True",
",",
"assert_same_host",
"=",
"True",
",",
"timeout",
"=",
"_Default",
",",
"p... | [
517,
4
] | [
861,
23
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._prepare_conn | (self, conn) |
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
|
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
| def _prepare_conn(self, conn):
"""
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
"""
if isinstance(conn, VerifiedHTTPSConnection):
conn.set_cert(
key_file=self.key_file,
... | [
"def",
"_prepare_conn",
"(",
"self",
",",
"conn",
")",
":",
"if",
"isinstance",
"(",
"conn",
",",
"VerifiedHTTPSConnection",
")",
":",
"conn",
".",
"set_cert",
"(",
"key_file",
"=",
"self",
".",
"key_file",
",",
"key_password",
"=",
"self",
".",
"key_passw... | [
930,
4
] | [
948,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._prepare_proxy | (self, conn) |
Establishes a tunnel connection through HTTP CONNECT.
Tunnel connection is established early because otherwise httplib would
improperly set Host: header to proxy's IP:port.
|
Establishes a tunnel connection through HTTP CONNECT. | def _prepare_proxy(self, conn):
"""
Establishes a tunnel connection through HTTP CONNECT.
Tunnel connection is established early because otherwise httplib would
improperly set Host: header to proxy's IP:port.
"""
conn.set_tunnel(self._proxy_host, self.port, self.proxy_h... | [
"def",
"_prepare_proxy",
"(",
"self",
",",
"conn",
")",
":",
"conn",
".",
"set_tunnel",
"(",
"self",
".",
"_proxy_host",
",",
"self",
".",
"port",
",",
"self",
".",
"proxy_headers",
")",
"if",
"self",
".",
"proxy",
".",
"scheme",
"==",
"\"https\"",
":"... | [
950,
4
] | [
963,
22
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._new_conn | (self) |
Return a fresh :class:`http.client.HTTPSConnection`.
|
Return a fresh :class:`http.client.HTTPSConnection`.
| def _new_conn(self):
"""
Return a fresh :class:`http.client.HTTPSConnection`.
"""
self.num_connections += 1
log.debug(
"Starting new HTTPS connection (%d): %s:%s",
self.num_connections,
self.host,
self.port or "443",
)
... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Starting new HTTPS connection (%d): %s:%s\"",
",",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
"or",
"\... | [
965,
4
] | [
999,
39
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._validate_conn | (self, conn) |
Called right before a request is made, after the socket is created.
|
Called right before a request is made, after the socket is created.
| def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, "sock", None): # AppEngin... | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"super",
"(",
"HTTPSConnectionPool",
",",
"self",
")",
".",
"_validate_conn",
"(",
"conn",
")",
"# Force connect early to allow us to validate the connection.",
"if",
"not",
"getattr",
"(",
"conn",
",",
... | [
1001,
4
] | [
1020,
13
] | python | en | ['en', 'error', 'th'] | False |
NSeriesEntity.ContainmentTree | (self) |
Adding Fan and PowerSupply to Scalable CompTree
:return: JSON
|
Adding Fan and PowerSupply to Scalable CompTree
:return: JSON
| def ContainmentTree(self):
"""
Adding Fan and PowerSupply to Scalable CompTree
:return: JSON
"""
device_json = self.get_json_device()
ctree = self._build_ctree(self.protofactory.ctree, device_json)
fn = {"Fan":[]}
ps = {"PowerSupply":[]}
i... | [
"def",
"ContainmentTree",
"(",
"self",
")",
":",
"device_json",
"=",
"self",
".",
"get_json_device",
"(",
")",
"ctree",
"=",
"self",
".",
"_build_ctree",
"(",
"self",
".",
"protofactory",
".",
"ctree",
",",
"device_json",
")",
"fn",
"=",
"{",
"\"Fan\"",
... | [
439,
4
] | [
452,
20
] | python | en | ['en', 'ja', 'th'] | False |
ValidationError.__init__ | (self, message, code=None, params=None) |
The `message` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. What we define as
an "error" can be either a simple string or an instance of
ValidationError with its message attribute set, and what we define as
list or di... |
The `message` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. What we define as
an "error" can be either a simple string or an instance of
ValidationError with its message attribute set, and what we define as
list or di... | def __init__(self, message, code=None, params=None):
"""
The `message` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. What we define as
an "error" can be either a simple string or an instance of
ValidationError with its... | [
"def",
"__init__",
"(",
"self",
",",
"message",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"# PY2 can't pickle naive exception: http://bugs.python.org/issue1692335.",
"super",
"(",
"ValidationError",
",",
"self",
")",
".",
"__init__",
"(",
"me... | [
101,
4
] | [
147,
36
] | python | en | ['en', 'error', 'th'] | False |
convert_exception_to_response | (get_response) |
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 5... |
Wrap the given get_response callable in exception-to-response conversion. | def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate respo... | [
"def",
"convert_exception_to_response",
"(",
"get_response",
")",
":",
"@",
"wraps",
"(",
"get_response",
",",
"assigned",
"=",
"available_attrs",
"(",
"get_response",
")",
")",
"def",
"inner",
"(",
"request",
")",
":",
"try",
":",
"response",
"=",
"get_respon... | [
24,
0
] | [
44,
16
] | python | en | ['en', 'error', 'th'] | False |
handle_uncaught_exception | (request, resolver, exc_info) |
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
|
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
| def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
logger.error(
'Internal Server Error: %s', request.path,
exc_... | [
"def",
"handle_uncaught_exception",
"(",
"request",
",",
"resolver",
",",
"exc_info",
")",
":",
"if",
"settings",
".",
"DEBUG_PROPAGATE_EXCEPTIONS",
":",
"raise",
"logger",
".",
"error",
"(",
"'Internal Server Error: %s'",
",",
"request",
".",
"path",
",",
"exc_in... | [
123,
0
] | [
142,
42
] | 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.