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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
OGRGeomType.__init__ | (self, type_input) | Figure out the correct OGR Type based upon the input. | Figure out the correct OGR Type based upon the input. | def __init__(self, type_input):
"Figure out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
elif isinstance(type_input, str):
type_input = type_input.lower()
if type_input == 'geometry':
... | [
"def",
"__init__",
"(",
"self",
",",
"type_input",
")",
":",
"if",
"isinstance",
"(",
"type_input",
",",
"OGRGeomType",
")",
":",
"num",
"=",
"type_input",
".",
"num",
"elif",
"isinstance",
"(",
"type_input",
",",
"str",
")",
":",
"type_input",
"=",
"typ... | [
32,
4
] | [
51,
22
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__str__ | (self) | Return the value of the name property. | Return the value of the name property. | def __str__(self):
"Return the value of the name property."
return self.name | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | [
53,
4
] | [
55,
24
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__eq__ | (self, other) |
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
|
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
| def __eq__(self, other):
"""
Do an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, str):
return sel... | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"OGRGeomType",
")",
":",
"return",
"self",
".",
"num",
"==",
"other",
".",
"num",
"elif",
"isinstance",
"(",
"other",
",",
"str",
")",
":",
"return",
"self",... | [
57,
4
] | [
69,
24
] | python | en | ['en', 'error', 'th'] | False |
OGRGeomType.name | (self) | Return a short-hand string form of the OGR Geometry type. | Return a short-hand string form of the OGR Geometry type. | def name(self):
"Return a short-hand string form of the OGR Geometry type."
return self._types[self.num] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_types",
"[",
"self",
".",
"num",
"]"
] | [
72,
4
] | [
74,
36
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.django | (self) | Return the Django GeometryField for this OGR Type. | Return the Django GeometryField for this OGR Type. | def django(self):
"Return the Django GeometryField for this OGR Type."
s = self.name.replace('25D', '')
if s in ('LinearRing', 'None'):
return None
elif s == 'Unknown':
s = 'Geometry'
elif s == 'PointZ':
s = 'Point'
return s + 'Field' | [
"def",
"django",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"'25D'",
",",
"''",
")",
"if",
"s",
"in",
"(",
"'LinearRing'",
",",
"'None'",
")",
":",
"return",
"None",
"elif",
"s",
"==",
"'Unknown'",
":",
"s",
"=",
... | [
77,
4
] | [
86,
26
] | python | en | ['en', 'af', 'en'] | True |
OGRGeomType.to_multi | (self) |
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
|
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
| def to_multi(self):
"""
Transform Point, LineString, Polygon, and their 25D equivalents
to their Multi... counterpart.
"""
if self.name.startswith(('Point', 'LineString', 'Polygon')):
self.num += 3 | [
"def",
"to_multi",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
".",
"startswith",
"(",
"(",
"'Point'",
",",
"'LineString'",
",",
"'Polygon'",
")",
")",
":",
"self",
".",
"num",
"+=",
"3"
] | [
88,
4
] | [
94,
25
] | python | en | ['en', 'error', 'th'] | False |
check_password | (environ, username, password) |
Authenticate against Django's auth database.
mod_wsgi docs specify None, True, False as return value depending
on whether the user exists and authenticates.
|
Authenticate against Django's auth database. | def check_password(environ, username, password):
"""
Authenticate against Django's auth database.
mod_wsgi docs specify None, True, False as return value depending
on whether the user exists and authenticates.
"""
# db connection state is managed similarly to the wsgi handler
# as mod_wsgi ... | [
"def",
"check_password",
"(",
"environ",
",",
"username",
",",
"password",
")",
":",
"# db connection state is managed similarly to the wsgi handler",
"# as mod_wsgi may call these functions outside of a request/response cycle",
"db",
".",
"reset_queries",
"(",
")",
"try",
":",
... | [
6,
0
] | [
25,
34
] | python | en | ['en', 'error', 'th'] | False |
groups_for_user | (environ, username) |
Authorize a user based on groups
|
Authorize a user based on groups
| def groups_for_user(environ, username):
"""
Authorize a user based on groups
"""
db.reset_queries()
try:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return []
if not user.is_active:
ret... | [
"def",
"groups_for_user",
"(",
"environ",
",",
"username",
")",
":",
"db",
".",
"reset_queries",
"(",
")",
"try",
":",
"try",
":",
"user",
"=",
"UserModel",
".",
"_default_manager",
".",
"get_by_natural_key",
"(",
"username",
")",
"except",
"UserModel",
".",... | [
28,
0
] | [
42,
34
] | python | en | ['en', 'error', 'th'] | False |
api_github_webhook | (
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Any] = REQ(argument_type="body"),
branches: Optional[str] = REQ(default=None),
user_specified_topic: Optional[str] = REQ("topic", default=None),
) |
GitHub sends the event as an HTTP header. We have our
own Zulip-specific concept of an event that often maps
directly to the X_GITHUB_EVENT header's event, but we sometimes
refine it based on the payload.
|
GitHub sends the event as an HTTP header. We have our
own Zulip-specific concept of an event that often maps
directly to the X_GITHUB_EVENT header's event, but we sometimes
refine it based on the payload.
| def api_github_webhook(
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Any] = REQ(argument_type="body"),
branches: Optional[str] = REQ(default=None),
user_specified_topic: Optional[str] = REQ("topic", default=None),
) -> HttpResponse:
"""
GitHub sends the event as an HTT... | [
"def",
"api_github_webhook",
"(",
"request",
":",
"HttpRequest",
",",
"user_profile",
":",
"UserProfile",
",",
"payload",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"REQ",
"(",
"argument_type",
"=",
"\"body\"",
")",
",",
"branches",
":",
"Optional",
"[... | [
682,
0
] | [
717,
25
] | python | en | ['en', 'error', 'th'] | False |
get_zulip_event_name | (
header_event: str,
payload: Dict[str, Any],
branches: Optional[str],
) |
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle.
|
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER. | def get_zulip_event_name(
header_event: str,
payload: Dict[str, Any],
branches: Optional[str],
) -> Optional[str]:
"""
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle.
"""
if header_event == "pull_... | [
"def",
"get_zulip_event_name",
"(",
"header_event",
":",
"str",
",",
"payload",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"branches",
":",
"Optional",
"[",
"str",
"]",
",",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"header_event",
"==",
... | [
720,
0
] | [
778,
53
] | python | en | ['en', 'error', 'th'] | False |
_running_under_venv | () | Checks if sys.base_prefix and sys.prefix match.
This handles PEP 405 compliant virtual environments.
| Checks if sys.base_prefix and sys.prefix match. | def _running_under_venv():
# type: () -> bool
"""Checks if sys.base_prefix and sys.prefix match.
This handles PEP 405 compliant virtual environments.
"""
return sys.prefix != getattr(sys, "base_prefix", sys.prefix) | [
"def",
"_running_under_venv",
"(",
")",
":",
"# type: () -> bool",
"return",
"sys",
".",
"prefix",
"!=",
"getattr",
"(",
"sys",
",",
"\"base_prefix\"",
",",
"sys",
".",
"prefix",
")"
] | [
19,
0
] | [
25,
64
] | python | en | ['en', 'ht', 'en'] | True |
_running_under_regular_virtualenv | () | Checks if sys.real_prefix is set.
This handles virtual environments created with pypa's virtualenv.
| Checks if sys.real_prefix is set. | def _running_under_regular_virtualenv():
# type: () -> bool
"""Checks if sys.real_prefix is set.
This handles virtual environments created with pypa's virtualenv.
"""
# pypa/virtualenv case
return hasattr(sys, 'real_prefix') | [
"def",
"_running_under_regular_virtualenv",
"(",
")",
":",
"# type: () -> bool",
"# pypa/virtualenv case",
"return",
"hasattr",
"(",
"sys",
",",
"'real_prefix'",
")"
] | [
28,
0
] | [
35,
38
] | python | en | ['en', 'en', 'en'] | True |
running_under_virtualenv | () | Return True if we're running inside a virtualenv, False otherwise.
| Return True if we're running inside a virtualenv, False otherwise.
| def running_under_virtualenv():
# type: () -> bool
"""Return True if we're running inside a virtualenv, False otherwise.
"""
return _running_under_venv() or _running_under_regular_virtualenv() | [
"def",
"running_under_virtualenv",
"(",
")",
":",
"# type: () -> bool",
"return",
"_running_under_venv",
"(",
")",
"or",
"_running_under_regular_virtualenv",
"(",
")"
] | [
38,
0
] | [
42,
71
] | python | en | ['en', 'en', 'en'] | True |
_get_pyvenv_cfg_lines | () | Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
Returns None, if it could not read/access the file.
| Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines | def _get_pyvenv_cfg_lines():
# type: () -> Optional[List[str]]
"""Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
Returns None, if it could not read/access the file.
"""
pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg')
try:
with open(pyvenv_cfg_file) as f... | [
"def",
"_get_pyvenv_cfg_lines",
"(",
")",
":",
"# type: () -> Optional[List[str]]",
"pyvenv_cfg_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"prefix",
",",
"'pyvenv.cfg'",
")",
"try",
":",
"with",
"open",
"(",
"pyvenv_cfg_file",
")",
"as",
"f",... | [
45,
0
] | [
56,
19
] | python | en | ['en', 'en', 'en'] | True |
_no_global_under_venv | () | Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
PEP 405 specifies that when system site-packages are not supposed to be
visible from a virtual environment, `pyvenv.cfg` must contain the following
line:
include-system-site-packages = false
Additionally, log a warning if acce... | Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion | def _no_global_under_venv():
# type: () -> bool
"""Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
PEP 405 specifies that when system site-packages are not supposed to be
visible from a virtual environment, `pyvenv.cfg` must contain the following
line:
include-system-sit... | [
"def",
"_no_global_under_venv",
"(",
")",
":",
"# type: () -> bool",
"cfg_lines",
"=",
"_get_pyvenv_cfg_lines",
"(",
")",
"if",
"cfg_lines",
"is",
"None",
":",
"# We're not in a \"sane\" venv, so assume there is no system",
"# site-packages access (since that's PEP 405's default st... | [
59,
0
] | [
86,
16
] | python | en | ['en', 'en', 'en'] | True |
_no_global_under_regular_virtualenv | () | Check if "no-global-site-packages.txt" exists beside site.py
This mirrors logic in pypa/virtualenv for determining whether system
site-packages are visible in the virtual environment.
| Check if "no-global-site-packages.txt" exists beside site.py | def _no_global_under_regular_virtualenv():
# type: () -> bool
"""Check if "no-global-site-packages.txt" exists beside site.py
This mirrors logic in pypa/virtualenv for determining whether system
site-packages are visible in the virtual environment.
"""
site_mod_dir = os.path.dirname(os.path.abs... | [
"def",
"_no_global_under_regular_virtualenv",
"(",
")",
":",
"# type: () -> bool",
"site_mod_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"site",
".",
"__file__",
")",
")",
"no_global_site_packages_file",
"=",
"os",
... | [
89,
0
] | [
100,
55
] | python | en | ['en', 'en', 'en'] | True |
virtualenv_no_global | () | Returns a boolean, whether running in venv with no system site-packages.
| Returns a boolean, whether running in venv with no system site-packages.
| def virtualenv_no_global():
# type: () -> bool
"""Returns a boolean, whether running in venv with no system site-packages.
"""
# PEP 405 compliance needs to be checked first since virtualenv >=20 would
# return True for both checks, but is only able to use the PEP 405 config.
if _running_under_v... | [
"def",
"virtualenv_no_global",
"(",
")",
":",
"# type: () -> bool",
"# PEP 405 compliance needs to be checked first since virtualenv >=20 would",
"# return True for both checks, but is only able to use the PEP 405 config.",
"if",
"_running_under_venv",
"(",
")",
":",
"return",
"_no_globa... | [
103,
0
] | [
115,
16
] | python | en | ['en', 'en', 'en'] | True |
ContentTypeManager.get_for_model | (self, model, for_concrete_model=True) |
Return the ContentType object for a given model, creating the
ContentType if necessary. Lookups are cached so that subsequent lookups
for the same model don't hit the database.
|
Return the ContentType object for a given model, creating the
ContentType if necessary. Lookups are cached so that subsequent lookups
for the same model don't hit the database.
| def get_for_model(self, model, for_concrete_model=True):
"""
Return the ContentType object for a given model, creating the
ContentType if necessary. Lookups are cached so that subsequent lookups
for the same model don't hit the database.
"""
opts = self._get_opts(model, f... | [
"def",
"get_for_model",
"(",
"self",
",",
"model",
",",
"for_concrete_model",
"=",
"True",
")",
":",
"opts",
"=",
"self",
".",
"_get_opts",
"(",
"model",
",",
"for_concrete_model",
")",
"try",
":",
"return",
"self",
".",
"_get_from_cache",
"(",
"opts",
")"... | [
33,
4
] | [
59,
17
] | python | en | ['en', 'error', 'th'] | False |
ContentTypeManager.get_for_models | (self, *models, for_concrete_models=True) |
Given *models, return a dictionary mapping {model: content_type}.
|
Given *models, return a dictionary mapping {model: content_type}.
| def get_for_models(self, *models, for_concrete_models=True):
"""
Given *models, return a dictionary mapping {model: content_type}.
"""
results = {}
# Models that aren't already in the cache.
needed_app_labels = set()
needed_models = set()
# Mapping of opts... | [
"def",
"get_for_models",
"(",
"self",
",",
"*",
"models",
",",
"for_concrete_models",
"=",
"True",
")",
":",
"results",
"=",
"{",
"}",
"# Models that aren't already in the cache.",
"needed_app_labels",
"=",
"set",
"(",
")",
"needed_models",
"=",
"set",
"(",
")",... | [
61,
4
] | [
101,
22
] | python | en | ['en', 'error', 'th'] | False |
ContentTypeManager.get_for_id | (self, id) |
Lookup a ContentType by ID. Use the same shared cache as get_for_model
(though ContentTypes are obviously not created on-the-fly by get_by_id).
|
Lookup a ContentType by ID. Use the same shared cache as get_for_model
(though ContentTypes are obviously not created on-the-fly by get_by_id).
| def get_for_id(self, id):
"""
Lookup a ContentType by ID. Use the same shared cache as get_for_model
(though ContentTypes are obviously not created on-the-fly by get_by_id).
"""
try:
ct = self._cache[self.db][id]
except KeyError:
# This could raise... | [
"def",
"get_for_id",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"ct",
"=",
"self",
".",
"_cache",
"[",
"self",
".",
"db",
"]",
"[",
"id",
"]",
"except",
"KeyError",
":",
"# This could raise a DoesNotExist; that's correct behavior and will",
"# make sure that ... | [
103,
4
] | [
115,
17
] | python | en | ['en', 'error', 'th'] | False |
ContentTypeManager.clear_cache | (self) |
Clear out the content-type cache.
|
Clear out the content-type cache.
| def clear_cache(self):
"""
Clear out the content-type cache.
"""
self._cache.clear() | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"self",
".",
"_cache",
".",
"clear",
"(",
")"
] | [
117,
4
] | [
121,
27
] | python | en | ['en', 'error', 'th'] | False |
ContentTypeManager._add_to_cache | (self, using, ct) | Insert a ContentType into the cache. | Insert a ContentType into the cache. | def _add_to_cache(self, using, ct):
"""Insert a ContentType into the cache."""
# Note it's possible for ContentType objects to be stale; model_class() will return None.
# Hence, there is no reliance on model._meta.app_label here, just using the model fields instead.
key = (ct.app_label, ... | [
"def",
"_add_to_cache",
"(",
"self",
",",
"using",
",",
"ct",
")",
":",
"# Note it's possible for ContentType objects to be stale; model_class() will return None.",
"# Hence, there is no reliance on model._meta.app_label here, just using the model fields instead.",
"key",
"=",
"(",
"ct... | [
123,
4
] | [
129,
53
] | python | en | ['en', 'en', 'en'] | True |
ContentType.model_class | (self) | Return the model class for this type of content. | Return the model class for this type of content. | def model_class(self):
"""Return the model class for this type of content."""
try:
return apps.get_model(self.app_label, self.model)
except LookupError:
return None | [
"def",
"model_class",
"(",
"self",
")",
":",
"try",
":",
"return",
"apps",
".",
"get_model",
"(",
"self",
".",
"app_label",
",",
"self",
".",
"model",
")",
"except",
"LookupError",
":",
"return",
"None"
] | [
160,
4
] | [
165,
23
] | python | en | ['en', 'en', 'en'] | True |
ContentType.get_object_for_this_type | (self, **kwargs) |
Return an object of this type for the keyword arguments given.
Basically, this is a proxy around this object_type's get_object() model
method. The ObjectNotExist exception, if thrown, will not be caught,
so code that calls this method should catch it.
|
Return an object of this type for the keyword arguments given.
Basically, this is a proxy around this object_type's get_object() model
method. The ObjectNotExist exception, if thrown, will not be caught,
so code that calls this method should catch it.
| def get_object_for_this_type(self, **kwargs):
"""
Return an object of this type for the keyword arguments given.
Basically, this is a proxy around this object_type's get_object() model
method. The ObjectNotExist exception, if thrown, will not be caught,
so code that calls this me... | [
"def",
"get_object_for_this_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"model_class",
"(",
")",
".",
"_base_manager",
".",
"using",
"(",
"self",
".",
"_state",
".",
"db",
")",
".",
"get",
"(",
"*",
"*",
"kwargs",
")... | [
167,
4
] | [
174,
83
] | python | en | ['en', 'error', 'th'] | False |
ContentType.get_all_objects_for_this_type | (self, **kwargs) |
Return all objects of this type for the keyword arguments given.
|
Return all objects of this type for the keyword arguments given.
| def get_all_objects_for_this_type(self, **kwargs):
"""
Return all objects of this type for the keyword arguments given.
"""
return self.model_class()._base_manager.using(self._state.db).filter(**kwargs) | [
"def",
"get_all_objects_for_this_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"model_class",
"(",
")",
".",
"_base_manager",
".",
"using",
"(",
"self",
".",
"_state",
".",
"db",
")",
".",
"filter",
"(",
"*",
"*",
"kwarg... | [
176,
4
] | [
180,
86
] | python | en | ['en', 'error', 'th'] | False |
set_topic_mutes | (
user_profile: UserProfile,
muted_topics: List[List[str]],
date_muted: Optional[datetime.datetime] = None,
) |
This is only used in tests.
|
This is only used in tests.
| def set_topic_mutes(
user_profile: UserProfile,
muted_topics: List[List[str]],
date_muted: Optional[datetime.datetime] = None,
) -> None:
"""
This is only used in tests.
"""
MutedTopic.objects.filter(
user_profile=user_profile,
).delete()
if date_muted is None:
date... | [
"def",
"set_topic_mutes",
"(",
"user_profile",
":",
"UserProfile",
",",
"muted_topics",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"date_muted",
":",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
... | [
30,
0
] | [
55,
9
] | python | en | ['en', 'error', 'th'] | False |
jsma_symbolic | (x, y_target, model, theta, gamma, clip_min, clip_max) |
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices).
:param x: the input placeholder
:param y_target: the target tensor
:param model: a cleverhans.model.Model object.
:param theta: delta for each feature adjustment
:pa... |
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices). | def jsma_symbolic(x, y_target, model, theta, gamma, clip_min, clip_max):
"""
TensorFlow implementation of the JSMA (see https://arxiv.org/abs/1511.07528
for details about the algorithm design choices).
:param x: the input placeholder
:param y_target: the target tensor
:param model: a cleverhans... | [
"def",
"jsma_symbolic",
"(",
"x",
",",
"y_target",
",",
"model",
",",
"theta",
",",
"gamma",
",",
"clip_min",
",",
"clip_max",
")",
":",
"nb_classes",
"=",
"int",
"(",
"y_target",
".",
"shape",
"[",
"-",
"1",
"]",
".",
"value",
")",
"nb_features",
"=... | [
140,
0
] | [
295,
16
] | python | en | ['en', 'error', 'th'] | False |
SaliencyMapMethod.__init__ | (self, model, sess=None, dtypestr="float32", **kwargs) |
Create a SaliencyMapMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
|
Create a SaliencyMapMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
| def __init__(self, model, sess=None, dtypestr="float32", **kwargs):
"""
Create a SaliencyMapMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
super(SaliencyMapMethod, self).__init__(mode... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
"=",
"None",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"SaliencyMapMethod",
",",
"self",
")",
".",
"__init__",
"(",
"model",
",",
"sess",
",",
"dty... | [
29,
4
] | [
45,
9
] | python | en | ['en', 'error', 'th'] | False |
SaliencyMapMethod.generate | (self, x, **kwargs) |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
|
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"symbolic_impl",
":",
"# Create random targets if ... | [
47,
4
] | [
94,
20
] | python | en | ['en', 'error', 'th'] | False |
SaliencyMapMethod.parse_params | (
self,
theta=1.0,
gamma=1.0,
clip_min=0.0,
clip_max=1.0,
y_target=None,
symbolic_impl=True,
**kwargs
) |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param theta: (optional float) Perturbation introduced to modified
components (can be positive or negative)
:param gamma: (... |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes. | def parse_params(
self,
theta=1.0,
gamma=1.0,
clip_min=0.0,
clip_max=1.0,
y_target=None,
symbolic_impl=True,
**kwargs
):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.... | [
"def",
"parse_params",
"(",
"self",
",",
"theta",
"=",
"1.0",
",",
"gamma",
"=",
"1.0",
",",
"clip_min",
"=",
"0.0",
",",
"clip_max",
"=",
"1.0",
",",
"y_target",
"=",
"None",
",",
"symbolic_impl",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"s... | [
96,
4
] | [
131,
19
] | python | en | ['en', 'error', 'th'] | False |
pair_visual | (original, adversarial, figure=None) |
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same plot
:return: the matplot figure to reuse for future samp... |
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same plot
:return: the matplot figure to reuse for future samp... | def pair_visual(original, adversarial, figure=None):
"""
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same p... | [
"def",
"pair_visual",
"(",
"original",
",",
"adversarial",
",",
"figure",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# Squeeze the image to remove single-dimensional entries from array shape",
"original",
"=",
"np",
".",
"squeeze",
"("... | [
9,
0
] | [
49,
17
] | python | en | ['en', 'error', 'th'] | False |
grid_visual | (data) |
This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse
|
This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse
| def grid_visual(data):
"""
This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse
"""
import matplotlib.pyplot as plt
... | [
"def",
"grid_visual",
"(",
"data",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# Ensure interactive mode is disabled and initialize our graph",
"plt",
".",
"ioff",
"(",
")",
"figure",
"=",
"plt",
".",
"figure",
"(",
")",
"figure",
".",
"canvas... | [
52,
0
] | [
82,
17
] | python | en | ['en', 'error', 'th'] | False |
get_logits_over_interval | (
sess, model, x_data, fgsm_params, min_epsilon=-10.0, max_epsilon=10.0, num_points=21
) | Get logits when the input is perturbed in an interval in adv direction.
Args:
sess: Tf session
model: Model for which we wish to get logits.
x_data: Numpy array corresponding to single data.
point of shape [height, width, channels].
fgsm_params: Parameters for genera... | Get logits when the input is perturbed in an interval in adv direction. | def get_logits_over_interval(
sess, model, x_data, fgsm_params, min_epsilon=-10.0, max_epsilon=10.0, num_points=21
):
"""Get logits when the input is perturbed in an interval in adv direction.
Args:
sess: Tf session
model: Model for which we wish to get logits.
x_data: Numpy array c... | [
"def",
"get_logits_over_interval",
"(",
"sess",
",",
"model",
",",
"x_data",
",",
"fgsm_params",
",",
"min_epsilon",
"=",
"-",
"10.0",
",",
"max_epsilon",
"=",
"10.0",
",",
"num_points",
"=",
"21",
")",
":",
"# Get the height, width and number of channels",
"heigh... | [
85,
0
] | [
133,
29
] | python | en | ['en', 'en', 'en'] | True |
linear_extrapolation_plot | (
log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21
) | Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for the labels
file_name: Plot filename
min_epsilon: Minimum value of epsilon over the interval
max_epsilon: Maximum value of epsilon over the interval
... | Generate linear extrapolation plot. | def linear_extrapolation_plot(
log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21
):
"""Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for the labels
file_name: Plot filename
... | [
"def",
"linear_extrapolation_plot",
"(",
"log_prob_adv_array",
",",
"y",
",",
"file_name",
",",
"min_epsilon",
"=",
"-",
"10",
",",
"max_epsilon",
"=",
"10",
",",
"num_points",
"=",
"21",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"\"Ag... | [
136,
0
] | [
181,
17
] | python | it | ['ro', 'mg', 'it'] | False |
SessionStorage._get | (self, *args, **kwargs) |
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
|
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
| def _get(self, *args, **kwargs):
"""
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
"""
return self.deserialize_messages(self.request.session.get(self.session_key)), Tru... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"deserialize_messages",
"(",
"self",
".",
"request",
".",
"session",
".",
"get",
"(",
"self",
".",
"session_key",
")",
")",
",",
"True"
] | [
22,
4
] | [
28,
90
] | python | en | ['en', 'error', 'th'] | False |
SessionStorage._store | (self, messages, response, *args, **kwargs) |
Store a list of messages to the request's session.
|
Store a list of messages to the request's session.
| def _store(self, messages, response, *args, **kwargs):
"""
Store a list of messages to the request's session.
"""
if messages:
self.request.session[self.session_key] = self.serialize_messages(messages)
else:
self.request.session.pop(self.session_key, None)... | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"messages",
":",
"self",
".",
"request",
".",
"session",
"[",
"self",
".",
"session_key",
"]",
"=",
"self",
".",
"serialize_mes... | [
30,
4
] | [
38,
17
] | python | en | ['en', 'error', 'th'] | False |
Retry.from_int | (cls, retries, redirect=True, default=None) | Backwards-compatibility for the old retries format. | Backwards-compatibility for the old retries format. | def from_int(cls, retries, redirect=True, default=None):
""" Backwards-compatibility for the old retries format."""
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redire... | [
"def",
"from_int",
"(",
"cls",
",",
"retries",
",",
"redirect",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"retries",
"is",
"None",
":",
"retries",
"=",
"default",
"if",
"default",
"is",
"not",
"None",
"else",
"cls",
".",
"DEFAULT",
"i... | [
218,
4
] | [
229,
26
] | python | en | ['en', 'en', 'en'] | True |
Retry.get_backoff_time | (self) | Formula for computing the current backoff
:rtype: float
| Formula for computing the current backoff | def get_backoff_time(self):
""" Formula for computing the current backoff
:rtype: float
"""
# We want to consider only the last consecutive errors sequence (Ignore redirects).
consecutive_errors_len = len(
list(
takewhile(lambda x: x.redirect_location... | [
"def",
"get_backoff_time",
"(",
"self",
")",
":",
"# We want to consider only the last consecutive errors sequence (Ignore redirects).",
"consecutive_errors_len",
"=",
"len",
"(",
"list",
"(",
"takewhile",
"(",
"lambda",
"x",
":",
"x",
".",
"redirect_location",
"is",
"Non... | [
231,
4
] | [
246,
51
] | python | en | ['en', 'en', 'en'] | True |
Retry.get_retry_after | (self, response) | Get the value of Retry-After in seconds. | Get the value of Retry-After in seconds. | def get_retry_after(self, response):
""" Get the value of Retry-After in seconds. """
retry_after = response.getheader("Retry-After")
if retry_after is None:
return None
return self.parse_retry_after(retry_after) | [
"def",
"get_retry_after",
"(",
"self",
",",
"response",
")",
":",
"retry_after",
"=",
"response",
".",
"getheader",
"(",
"\"Retry-After\"",
")",
"if",
"retry_after",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"parse_retry_after",
"(",
"retry_a... | [
264,
4
] | [
272,
50
] | python | en | ['en', 'en', 'en'] | True |
Retry.sleep | (self, response=None) | Sleep between retry attempts.
This method will respect a server's ``Retry-After`` response header
and sleep the duration of the time requested. If that is not present, it
will use an exponential backoff. By default, the backoff factor is 0 and
this method will return immediately.
... | Sleep between retry attempts. | def sleep(self, response=None):
""" Sleep between retry attempts.
This method will respect a server's ``Retry-After`` response header
and sleep the duration of the time requested. If that is not present, it
will use an exponential backoff. By default, the backoff factor is 0 and
... | [
"def",
"sleep",
"(",
"self",
",",
"response",
"=",
"None",
")",
":",
"if",
"self",
".",
"respect_retry_after_header",
"and",
"response",
":",
"slept",
"=",
"self",
".",
"sleep_for_retry",
"(",
"response",
")",
"if",
"slept",
":",
"return",
"self",
".",
"... | [
288,
4
] | [
302,
29
] | python | en | ['en', 'nl', 'en'] | True |
Retry._is_connection_error | (self, err) | Errors when we're fairly sure that the server did not receive the
request, so it should be safe to retry.
| Errors when we're fairly sure that the server did not receive the
request, so it should be safe to retry.
| def _is_connection_error(self, err):
""" Errors when we're fairly sure that the server did not receive the
request, so it should be safe to retry.
"""
return isinstance(err, ConnectTimeoutError) | [
"def",
"_is_connection_error",
"(",
"self",
",",
"err",
")",
":",
"return",
"isinstance",
"(",
"err",
",",
"ConnectTimeoutError",
")"
] | [
304,
4
] | [
308,
51
] | python | en | ['en', 'en', 'en'] | True |
Retry._is_read_error | (self, err) | Errors that occur after the request has been started, so we should
assume that the server began processing it.
| Errors that occur after the request has been started, so we should
assume that the server began processing it.
| def _is_read_error(self, err):
""" Errors that occur after the request has been started, so we should
assume that the server began processing it.
"""
return isinstance(err, (ReadTimeoutError, ProtocolError)) | [
"def",
"_is_read_error",
"(",
"self",
",",
"err",
")",
":",
"return",
"isinstance",
"(",
"err",
",",
"(",
"ReadTimeoutError",
",",
"ProtocolError",
")",
")"
] | [
310,
4
] | [
314,
65
] | python | en | ['en', 'en', 'en'] | True |
Retry._is_method_retryable | (self, method) | Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist.
| Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist.
| def _is_method_retryable(self, method):
""" Checks if a given HTTP method should be retried upon, depending if
it is included on the method whitelist.
"""
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return True | [
"def",
"_is_method_retryable",
"(",
"self",
",",
"method",
")",
":",
"if",
"self",
".",
"method_whitelist",
"and",
"method",
".",
"upper",
"(",
")",
"not",
"in",
"self",
".",
"method_whitelist",
":",
"return",
"False",
"return",
"True"
] | [
316,
4
] | [
323,
19
] | python | en | ['en', 'en', 'en'] | True |
Retry.is_retry | (self, method, status_code, has_retry_after=False) | Is this method/status code retryable? (Based on whitelists and control
variables such as the number of total retries to allow, whether to
respect the Retry-After header, whether this header is present, and
whether the returned status code is on the list of status codes to
be retried upo... | Is this method/status code retryable? (Based on whitelists and control
variables such as the number of total retries to allow, whether to
respect the Retry-After header, whether this header is present, and
whether the returned status code is on the list of status codes to
be retried upo... | def is_retry(self, method, status_code, has_retry_after=False):
""" Is this method/status code retryable? (Based on whitelists and control
variables such as the number of total retries to allow, whether to
respect the Retry-After header, whether this header is present, and
whether the re... | [
"def",
"is_retry",
"(",
"self",
",",
"method",
",",
"status_code",
",",
"has_retry_after",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_is_method_retryable",
"(",
"method",
")",
":",
"return",
"False",
"if",
"self",
".",
"status_forcelist",
"and",
"... | [
325,
4
] | [
343,
9
] | python | en | ['en', 'en', 'en'] | True |
Retry.is_exhausted | (self) | Are we out of retries? | Are we out of retries? | def is_exhausted(self):
""" Are we out of retries? """
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
retry_counts = list(filter(None, retry_counts))
if not retry_counts:
return False
return min(retry_counts) < 0 | [
"def",
"is_exhausted",
"(",
"self",
")",
":",
"retry_counts",
"=",
"(",
"self",
".",
"total",
",",
"self",
".",
"connect",
",",
"self",
".",
"read",
",",
"self",
".",
"redirect",
",",
"self",
".",
"status",
")",
"retry_counts",
"=",
"list",
"(",
"fil... | [
345,
4
] | [
352,
36
] | python | en | ['en', 'en', 'en'] | True |
Retry.increment | (
self,
method=None,
url=None,
response=None,
error=None,
_pool=None,
_stacktrace=None,
) | Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
return a response.
:type response: :class:`~urllib3.response.HTTPResponse`
:param Exception error: An error encountered during the request, or
N... | Return a new Retry object with incremented retry counters. | def increment(
self,
method=None,
url=None,
response=None,
error=None,
_pool=None,
_stacktrace=None,
):
""" Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
... | [
"def",
"increment",
"(",
"self",
",",
"method",
"=",
"None",
",",
"url",
"=",
"None",
",",
"response",
"=",
"None",
",",
"error",
"=",
"None",
",",
"_pool",
"=",
"None",
",",
"_stacktrace",
"=",
"None",
",",
")",
":",
"if",
"self",
".",
"total",
... | [
354,
4
] | [
439,
24
] | python | en | ['en', 'en', 'en'] | True |
StringLookupTests.test_string_form_referencing | (self) |
Regression test for #1661 and #1662
Check that string form referencing of
models works, both as pre and post reference, on all RelatedField types.
|
Regression test for #1661 and #1662 | def test_string_form_referencing(self):
"""
Regression test for #1661 and #1662
Check that string form referencing of
models works, both as pre and post reference, on all RelatedField types.
"""
f1 = Foo(name="Foo1")
f1.save()
f2 = Foo(name="Foo2")
... | [
"def",
"test_string_form_referencing",
"(",
"self",
")",
":",
"f1",
"=",
"Foo",
"(",
"name",
"=",
"\"Foo1\"",
")",
"f1",
".",
"save",
"(",
")",
"f2",
"=",
"Foo",
"(",
"name",
"=",
"\"Foo2\"",
")",
"f2",
".",
"save",
"(",
")",
"w1",
"=",
"Whiz",
"... | [
9,
4
] | [
40,
46
] | python | en | ['en', 'error', 'th'] | False |
StringLookupTests.test_unicode_chars_in_queries | (self) |
Regression tests for #3937
make sure we can use unicode characters in queries.
If these tests fail on MySQL, it's a problem with the test setup.
A properly configured UTF-8 database can handle this.
|
Regression tests for #3937 | def test_unicode_chars_in_queries(self):
"""
Regression tests for #3937
make sure we can use unicode characters in queries.
If these tests fail on MySQL, it's a problem with the test setup.
A properly configured UTF-8 database can handle this.
"""
fx = Foo(name=... | [
"def",
"test_unicode_chars_in_queries",
"(",
"self",
")",
":",
"fx",
"=",
"Foo",
"(",
"name",
"=",
"'Bjorn'",
",",
"friend",
"=",
"'François')",
"",
"fx",
".",
"save",
"(",
")",
"self",
".",
"assertEqual",
"(",
"Foo",
".",
"objects",
".",
"get",
"(",
... | [
42,
4
] | [
56,
75
] | python | en | ['en', 'error', 'th'] | False |
StringLookupTests.test_queries_on_textfields | (self) |
Regression tests for #5087
make sure we can perform queries on TextFields.
|
Regression tests for #5087 | def test_queries_on_textfields(self):
"""
Regression tests for #5087
make sure we can perform queries on TextFields.
"""
a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.')
a.save()
self.assertEqual(Article.objects.get(text__exact='The ... | [
"def",
"test_queries_on_textfields",
"(",
"self",
")",
":",
"a",
"=",
"Article",
"(",
"name",
"=",
"'Test'",
",",
"text",
"=",
"'The quick brown fox jumps over the lazy dog.'",
")",
"a",
".",
"save",
"(",
")",
"self",
".",
"assertEqual",
"(",
"Article",
".",
... | [
58,
4
] | [
69,
82
] | python | en | ['en', 'error', 'th'] | False |
StringLookupTests.test_ipaddress_on_postgresql | (self) |
Regression test for #708
"like" queries on IP address fields require casting with HOST() (on PostgreSQL).
|
Regression test for #708 | def test_ipaddress_on_postgresql(self):
"""
Regression test for #708
"like" queries on IP address fields require casting with HOST() (on PostgreSQL).
"""
a = Article(name='IP test', text='The body', submitted_from='192.0.2.100')
a.save()
self.assertEqual(repr(Art... | [
"def",
"test_ipaddress_on_postgresql",
"(",
"self",
")",
":",
"a",
"=",
"Article",
"(",
"name",
"=",
"'IP test'",
",",
"text",
"=",
"'The body'",
",",
"submitted_from",
"=",
"'192.0.2.100'",
")",
"a",
".",
"save",
"(",
")",
"self",
".",
"assertEqual",
"(",... | [
71,
4
] | [
82,
90
] | python | en | ['en', 'error', 'th'] | False |
Deserializer | (object_list, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options) |
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
|
Deserialize simple Python objects back into Django ORM instances. | def Deserializer(object_list, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options):
"""
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
"""
handle_forward_r... | [
"def",
"Deserializer",
"(",
"object_list",
",",
"*",
",",
"using",
"=",
"DEFAULT_DB_ALIAS",
",",
"ignorenonexistent",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"handle_forward_references",
"=",
"options",
".",
"pop",
"(",
"'handle_forward_references'",
"... | [
77,
0
] | [
146,
69
] | python | en | ['en', 'error', 'th'] | False |
_get_model | (model_identifier) | Look up a model from an "app_label.model_name" string. | Look up a model from an "app_label.model_name" string. | def _get_model(model_identifier):
"""Look up a model from an "app_label.model_name" string."""
try:
return apps.get_model(model_identifier)
except (LookupError, TypeError):
raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier) | [
"def",
"_get_model",
"(",
"model_identifier",
")",
":",
"try",
":",
"return",
"apps",
".",
"get_model",
"(",
"model_identifier",
")",
"except",
"(",
"LookupError",
",",
"TypeError",
")",
":",
"raise",
"base",
".",
"DeserializationError",
"(",
"\"Invalid model id... | [
149,
0
] | [
154,
92
] | python | en | ['en', 'en', 'en'] | True |
feed | (request, url, feed_dict=None) | Provided for backwards compatibility. | Provided for backwards compatibility. | def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except KeyError:
raise Http404(_('Slug %r isn’t registered.') % slug)
... | [
"def",
"feed",
"(",
"request",
",",
"url",
",",
"feed_dict",
"=",
"None",
")",
":",
"if",
"not",
"feed_dict",
":",
"raise",
"Http404",
"(",
"_",
"(",
"\"No feeds are registered.\"",
")",
")",
"slug",
"=",
"url",
".",
"partition",
"(",
"'/'",
")",
"[",
... | [
4,
0
] | [
19,
28
] | python | en | ['en', 'en', 'en'] | True |
raise_option_error | (parser, option, msg) |
Raise an option parsing error using parser.error().
Args:
parser: an OptionParser instance.
option: an Option instance.
msg: the error text.
|
Raise an option parsing error using parser.error(). | def raise_option_error(parser, option, msg):
# type: (OptionParser, Option, str) -> None
"""
Raise an option parsing error using parser.error().
Args:
parser: an OptionParser instance.
option: an Option instance.
msg: the error text.
"""
msg = '{} error: {}'.format(option, msg... | [
"def",
"raise_option_error",
"(",
"parser",
",",
"option",
",",
"msg",
")",
":",
"# type: (OptionParser, Option, str) -> None",
"msg",
"=",
"'{} error: {}'",
".",
"format",
"(",
"option",
",",
"msg",
")",
"msg",
"=",
"textwrap",
".",
"fill",
"(",
"' '",
".",
... | [
40,
0
] | [
52,
21
] | python | en | ['en', 'error', 'th'] | False |
make_option_group | (group, parser) |
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
|
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
| def make_option_group(group, parser):
# type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup
"""
Return an OptionGroup object
group -- assumed to be dict with 'name' and 'options' keys
parser -- an optparse Parser
"""
option_group = OptionGroup(parser, group['name'])
for option in ... | [
"def",
"make_option_group",
"(",
"group",
",",
"parser",
")",
":",
"# type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup",
"option_group",
"=",
"OptionGroup",
"(",
"parser",
",",
"group",
"[",
"'name'",
"]",
")",
"for",
"option",
"in",
"group",
"[",
"'options... | [
55,
0
] | [
65,
23
] | python | en | ['en', 'error', 'th'] | False |
check_install_build_global | (options, check_options=None) | Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options.
| Disable wheels if per-setup.py call options are set. | def check_install_build_global(options, check_options=None):
# type: (Values, Optional[Values]) -> None
"""Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options.
... | [
"def",
"check_install_build_global",
"(",
"options",
",",
"check_options",
"=",
"None",
")",
":",
"# type: (Values, Optional[Values]) -> None",
"if",
"check_options",
"is",
"None",
":",
"check_options",
"=",
"options",
"def",
"getname",
"(",
"n",
")",
":",
"# type: ... | [
68,
0
] | [
89,
9
] | python | en | ['en', 'en', 'en'] | True |
check_dist_restriction | (options, check_target=False) | Function for determining if custom platform options are allowed.
:param options: The OptionParser options.
:param check_target: Whether or not to check if --target is being used.
| Function for determining if custom platform options are allowed. | def check_dist_restriction(options, check_target=False):
# type: (Values, bool) -> None
"""Function for determining if custom platform options are allowed.
:param options: The OptionParser options.
:param check_target: Whether or not to check if --target is being used.
"""
dist_restriction_set ... | [
"def",
"check_dist_restriction",
"(",
"options",
",",
"check_target",
"=",
"False",
")",
":",
"# type: (Values, bool) -> None",
"dist_restriction_set",
"=",
"any",
"(",
"[",
"options",
".",
"python_version",
",",
"options",
".",
"platform",
",",
"options",
".",
"a... | [
92,
0
] | [
129,
13
] | python | en | ['en', 'en', 'en'] | True |
_get_format_control | (values, option) | Get a format_control object. | Get a format_control object. | def _get_format_control(values, option):
# type: (Values, Option) -> Any
"""Get a format_control object."""
return getattr(values, option.dest) | [
"def",
"_get_format_control",
"(",
"values",
",",
"option",
")",
":",
"# type: (Values, Option) -> Any",
"return",
"getattr",
"(",
"values",
",",
"option",
".",
"dest",
")"
] | [
440,
0
] | [
443,
39
] | python | en | ['en', 'en', 'en'] | True |
_convert_python_version | (value) |
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error.
|
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. | def _convert_python_version(value):
# type: (str) -> Tuple[Tuple[int, ...], Optional[str]]
"""
Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is
non-None if and only if there was a parsing error.
"""
... | [
"def",
"_convert_python_version",
"(",
"value",
")",
":",
"# type: (str) -> Tuple[Tuple[int, ...], Optional[str]]",
"if",
"not",
"value",
":",
"# The empty string is the same as not providing a value.",
"return",
"(",
"None",
",",
"None",
")",
"parts",
"=",
"value",
".",
... | [
506,
0
] | [
533,
31
] | python | en | ['en', 'error', 'th'] | False |
_handle_python_version | (option, opt_str, value, parser) |
Handle a provided --python-version value.
|
Handle a provided --python-version value.
| def _handle_python_version(option, opt_str, value, parser):
# type: (Option, str, str, OptionParser) -> None
"""
Handle a provided --python-version value.
"""
version_info, error_msg = _convert_python_version(value)
if error_msg is not None:
msg = (
'invalid --python-version ... | [
"def",
"_handle_python_version",
"(",
"option",
",",
"opt_str",
",",
"value",
",",
"parser",
")",
":",
"# type: (Option, str, str, OptionParser) -> None",
"version_info",
",",
"error_msg",
"=",
"_convert_python_version",
"(",
"value",
")",
"if",
"error_msg",
"is",
"no... | [
536,
0
] | [
550,
47
] | python | en | ['en', 'error', 'th'] | False |
_handle_no_cache_dir | (option, opt, value, parser) |
Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option.
|
Process a value provided for the --no-cache-dir option. | def _handle_no_cache_dir(option, opt, value, parser):
# type: (Option, str, str, OptionParser) -> None
"""
Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option.
"""
# The value argument will be None if --no-cache-dir is passed... | [
"def",
"_handle_no_cache_dir",
"(",
"option",
",",
"opt",
",",
"value",
",",
"parser",
")",
":",
"# type: (Option, str, str, OptionParser) -> None",
"# The value argument will be None if --no-cache-dir is passed via the",
"# command-line, since the option doesn't accept arguments. Howev... | [
642,
0
] | [
667,
35
] | python | en | ['en', 'error', 'th'] | False |
_handle_no_use_pep517 | (option, opt, value, parser) |
Process a value provided for the --no-use-pep517 option.
This is an optparse.Option callback for the no_use_pep517 option.
|
Process a value provided for the --no-use-pep517 option. | def _handle_no_use_pep517(option, opt, value, parser):
# type: (Option, str, str, OptionParser) -> None
"""
Process a value provided for the --no-use-pep517 option.
This is an optparse.Option callback for the no_use_pep517 option.
"""
# Since --no-use-pep517 doesn't accept arguments, the value ... | [
"def",
"_handle_no_use_pep517",
"(",
"option",
",",
"opt",
",",
"value",
",",
"parser",
")",
":",
"# type: (Option, str, str, OptionParser) -> None",
"# Since --no-use-pep517 doesn't accept arguments, the value argument",
"# will be None if --no-use-pep517 is passed via the command-line.... | [
731,
0
] | [
752,
36
] | python | en | ['en', 'error', 'th'] | False |
_handle_merge_hash | (option, opt_str, value, parser) | Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name. | Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name. | def _handle_merge_hash(option, opt_str, value, parser):
# type: (Option, str, str, OptionParser) -> None
"""Given a value spelled "algo:digest", append the digest to a list
pointed to in a dict by the algo name."""
if not parser.values.hashes:
parser.values.hashes = {}
try:
algo, dig... | [
"def",
"_handle_merge_hash",
"(",
"option",
",",
"opt_str",
",",
"value",
",",
"parser",
")",
":",
"# type: (Option, str, str, OptionParser) -> None",
"if",
"not",
"parser",
".",
"values",
".",
"hashes",
":",
"parser",
".",
"values",
".",
"hashes",
"=",
"{",
"... | [
836,
0
] | [
851,
60
] | python | en | ['en', 'en', 'en'] | True |
Command.sync_apps | (self, connection, app_labels) | Run the old syncdb-style operation on a list of app_labels. | Run the old syncdb-style operation on a list of app_labels. | def sync_apps(self, connection, app_labels):
"""Run the old syncdb-style operation on a list of app_labels."""
with connection.cursor() as cursor:
tables = connection.introspection.table_names(cursor)
# Build the manifest of apps and models that are to be synchronized.
all_m... | [
"def",
"sync_apps",
"(",
"self",
",",
"connection",
",",
"app_labels",
")",
":",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"tables",
"=",
"connection",
".",
"introspection",
".",
"table_names",
"(",
"cursor",
")",
"# Build the manif... | [
292,
4
] | [
339,
66
] | python | en | ['en', 'en', 'en'] | True |
Command.describe_operation | (operation, backwards) | Return a string that describes a migration operation for --plan. | Return a string that describes a migration operation for --plan. | def describe_operation(operation, backwards):
"""Return a string that describes a migration operation for --plan."""
prefix = ''
is_error = False
if hasattr(operation, 'code'):
code = operation.reverse_code if backwards else operation.code
action = (code.__doc__ o... | [
"def",
"describe_operation",
"(",
"operation",
",",
"backwards",
")",
":",
"prefix",
"=",
"''",
"is_error",
"=",
"False",
"if",
"hasattr",
"(",
"operation",
",",
"'code'",
")",
":",
"code",
"=",
"operation",
".",
"reverse_code",
"if",
"backwards",
"else",
... | [
342,
4
] | [
363,
76
] | python | en | ['en', 'en', 'en'] | True |
get_modified_streams | (
user_ids: List[int], cutoff_date: datetime.datetime
) | Skipping streams where the user's subscription status has changed
when constructing digests is critical to ensure correctness for
streams without shared history, guest users, and long-term idle
users, because it means that every user has the same view of the
history of a given stream whose message histo... | Skipping streams where the user's subscription status has changed
when constructing digests is critical to ensure correctness for
streams without shared history, guest users, and long-term idle
users, because it means that every user has the same view of the
history of a given stream whose message histo... | def get_modified_streams(
user_ids: List[int], cutoff_date: datetime.datetime
) -> Dict[int, Set[int]]:
"""Skipping streams where the user's subscription status has changed
when constructing digests is critical to ensure correctness for
streams without shared history, guest users, and long-term idle
... | [
"def",
"get_modified_streams",
"(",
"user_ids",
":",
"List",
"[",
"int",
"]",
",",
"cutoff_date",
":",
"datetime",
".",
"datetime",
")",
"->",
"Dict",
"[",
"int",
",",
"Set",
"[",
"int",
"]",
"]",
":",
"events",
"=",
"[",
"RealmAuditLog",
".",
"SUBSCRI... | [
399,
0
] | [
438,
17
] | python | en | ['en', 'en', 'en'] | True |
_attr_key | (attr) | Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
| Return an appropriate key for an attribute for sorting | def _attr_key(attr):
"""Return an appropriate key for an attribute for sorting
Attributes have a namespace that can be either ``None`` or a string. We
can't compare the two because they're different types, so we convert
``None`` to an empty string first.
"""
return (attr[0][0] or ''), attr[0][... | [
"def",
"_attr_key",
"(",
"attr",
")",
":",
"return",
"(",
"attr",
"[",
"0",
"]",
"[",
"0",
"]",
"or",
"''",
")",
",",
"attr",
"[",
"0",
"]",
"[",
"1",
"]"
] | [
7,
0
] | [
15,
41
] | python | en | ['en', 'en', 'en'] | True |
BulkUsersTest.test_client_gravatar_option | (self) |
The main purpose of this test is to make sure we
return None for avatar_url when client_gravatar is
set to True. And we do a sanity check for when it's
False, but we leave it to other tests to validate
the specific URL.
|
The main purpose of this test is to make sure we
return None for avatar_url when client_gravatar is
set to True. And we do a sanity check for when it's
False, but we leave it to other tests to validate
the specific URL.
| def test_client_gravatar_option(self) -> None:
reset_emails_in_zulip_realm()
self.login("cordelia")
hamlet = self.example_user("hamlet")
def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]:
data = dict(client_gravatar=orjson.dumps(client_gravatar).decode())
... | [
"def",
"test_client_gravatar_option",
"(",
"self",
")",
"->",
"None",
":",
"reset_emails_in_zulip_realm",
"(",
")",
"self",
".",
"login",
"(",
"\"cordelia\"",
")",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"def",
"get_hamlet_avatar",
"(... | [
1740,
4
] | [
1769,
9
] | python | en | ['en', 'error', 'th'] | False |
GetProfileTest.test_cache_behavior | (self) | Tests whether fetching a user object the normal way, with
`get_user`, makes 1 cache query and 1 database query.
| Tests whether fetching a user object the normal way, with
`get_user`, makes 1 cache query and 1 database query.
| def test_cache_behavior(self) -> None:
"""Tests whether fetching a user object the normal way, with
`get_user`, makes 1 cache query and 1 database query.
"""
realm = get_realm("zulip")
email = self.example_user("hamlet").email
with queries_captured() as queries:
... | [
"def",
"test_cache_behavior",
"(",
"self",
")",
"->",
"None",
":",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"email",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
".",
"email",
"with",
"queries_captured",
"(",
")",
"as",
"queries",
":"... | [
1773,
4
] | [
1785,
51
] | python | en | ['en', 'en', 'en'] | True |
parse_cookie | (cookie) |
Return a dictionary parsed from a `Cookie:` header string.
|
Return a dictionary parsed from a `Cookie:` header string.
| def parse_cookie(cookie):
"""
Return a dictionary parsed from a `Cookie:` header string.
"""
cookiedict = {}
for chunk in cookie.split(';'):
if '=' in chunk:
key, val = chunk.split('=', 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla... | [
"def",
"parse_cookie",
"(",
"cookie",
")",
":",
"cookiedict",
"=",
"{",
"}",
"for",
"chunk",
"in",
"cookie",
".",
"split",
"(",
"';'",
")",
":",
"if",
"'='",
"in",
"chunk",
":",
"key",
",",
"val",
"=",
"chunk",
".",
"split",
"(",
"'='",
",",
"1",... | [
9,
0
] | [
25,
21
] | python | en | ['en', 'error', 'th'] | False |
test_resource_creation_sets_opening_hours | (admin_client, valid_resource_form_data) |
valid_resource_form_data sets the opening hours starting from 2018-06-06 only for Tuesdays.
Time is frozen to 2018-06-12 which is the first Tuesday after that to test opening hours.
|
valid_resource_form_data sets the opening hours starting from 2018-06-06 only for Tuesdays.
Time is frozen to 2018-06-12 which is the first Tuesday after that to test opening hours.
| def test_resource_creation_sets_opening_hours(admin_client, valid_resource_form_data):
"""
valid_resource_form_data sets the opening hours starting from 2018-06-06 only for Tuesdays.
Time is frozen to 2018-06-12 which is the first Tuesday after that to test opening hours.
"""
data = valid_resource_f... | [
"def",
"test_resource_creation_sets_opening_hours",
"(",
"admin_client",
",",
"valid_resource_form_data",
")",
":",
"data",
"=",
"valid_resource_form_data",
".",
"copy",
"(",
")",
"data",
"[",
"'days-periods-0-0-closes'",
"]",
"=",
"'14:00'",
"admin_client",
".",
"post"... | [
99,
0
] | [
114,
35
] | python | en | ['en', 'error', 'th'] | False |
CustomField.test_subfieldbase_plays_nice_with_module_inspect | (self) |
Custom fields should play nice with python standard module inspect.
http://users.rcn.com/python/download/Descriptor.htm#properties
|
Custom fields should play nice with python standard module inspect. | def test_subfieldbase_plays_nice_with_module_inspect(self):
"""
Custom fields should play nice with python standard module inspect.
http://users.rcn.com/python/download/Descriptor.htm#properties
"""
# Even when looking for totally different properties, SubfieldBase's
# n... | [
"def",
"test_subfieldbase_plays_nice_with_module_inspect",
"(",
"self",
")",
":",
"# Even when looking for totally different properties, SubfieldBase's",
"# non property like behavior made inspect crash. Refs #12568.",
"data",
"=",
"dict",
"(",
"inspect",
".",
"getmembers",
"(",
"MyM... | [
96,
4
] | [
106,
72
] | python | en | ['en', 'error', 'th'] | False |
AlertWordTests.test_default_no_words | (self) |
Users start out with no alert words.
|
Users start out with no alert words.
| def test_default_no_words(self) -> None:
"""
Users start out with no alert words.
"""
user = self.get_user()
words = user_alert_words(user)
self.assertEqual(words, []) | [
"def",
"test_default_no_words",
"(",
"self",
")",
"->",
"None",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
")",
"words",
"=",
"user_alert_words",
"(",
"user",
")",
"self",
".",
"assertEqual",
"(",
"words",
",",
"[",
"]",
")"
] | [
34,
4
] | [
40,
35
] | python | en | ['en', 'error', 'th'] | False |
AlertWordTests.test_basics | (self) |
Verifies the basic behavior of modifying alert words.
Also verifies the cache-flushing behavior.
|
Verifies the basic behavior of modifying alert words. | def test_basics(self) -> None:
"""
Verifies the basic behavior of modifying alert words.
Also verifies the cache-flushing behavior.
"""
user = self.get_user()
realm_alert_words = alert_words_in_realm(user.realm)
self.assert_length(realm_alert_words.get(user.id, [... | [
"def",
"test_basics",
"(",
"self",
")",
"->",
"None",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
")",
"realm_alert_words",
"=",
"alert_words_in_realm",
"(",
"user",
".",
"realm",
")",
"self",
".",
"assert_length",
"(",
"realm_alert_words",
".",
"get",
... | [
42,
4
] | [
72,
57
] | python | en | ['en', 'error', 'th'] | False |
AlertWordTests.test_remove_word | (self) |
Removing alert words works via do_remove_alert_words, even
for multi-word and non-ascii words.
|
Removing alert words works via do_remove_alert_words, even
for multi-word and non-ascii words.
| def test_remove_word(self) -> None:
"""
Removing alert words works via do_remove_alert_words, even
for multi-word and non-ascii words.
"""
user = self.get_user()
expected_remaining_alerts = set(self.interesting_alert_word_list)
do_add_alert_words(user, self.inter... | [
"def",
"test_remove_word",
"(",
"self",
")",
"->",
"None",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
")",
"expected_remaining_alerts",
"=",
"set",
"(",
"self",
".",
"interesting_alert_word_list",
")",
"do_add_alert_words",
"(",
"user",
",",
"self",
".",
... | [
74,
4
] | [
88,
85
] | python | en | ['en', 'error', 'th'] | False |
AlertWordTests.test_realm_words | (self) |
We can gather alert words for an entire realm via
alert_words_in_realm. Alerts added for one user do not impact other
users.
|
We can gather alert words for an entire realm via
alert_words_in_realm. Alerts added for one user do not impact other
users.
| def test_realm_words(self) -> None:
"""
We can gather alert words for an entire realm via
alert_words_in_realm. Alerts added for one user do not impact other
users.
"""
# Clear all the words that we got from populate_db.
AlertWord.objects.all().delete()
... | [
"def",
"test_realm_words",
"(",
"self",
")",
"->",
"None",
":",
"# Clear all the words that we got from populate_db.",
"AlertWord",
".",
"objects",
".",
"all",
"(",
")",
".",
"delete",
"(",
")",
"user1",
"=",
"self",
".",
"get_user",
"(",
")",
"do_add_alert_word... | [
90,
4
] | [
111,
65
] | python | en | ['en', 'error', 'th'] | False |
AlertWordTests.message_does_alert | (self, user: UserProfile, message: str) | Send a bunch of messages as othello, so our user is notified | Send a bunch of messages as othello, so our user is notified | def message_does_alert(self, user: UserProfile, message: str) -> bool:
"""Send a bunch of messages as othello, so our user is notified"""
self.send_stream_message(self.example_user("othello"), "Denmark", message)
user_message = most_recent_usermessage(user)
return "has_alert_word" in use... | [
"def",
"message_does_alert",
"(",
"self",
",",
"user",
":",
"UserProfile",
",",
"message",
":",
"str",
")",
"->",
"bool",
":",
"self",
".",
"send_stream_message",
"(",
"self",
".",
"example_user",
"(",
"\"othello\"",
")",
",",
"\"Denmark\"",
",",
"message",
... | [
158,
4
] | [
162,
60
] | python | en | ['en', 'en', 'en'] | True |
bdist_wheel.wheel_dist_name | (self) | Return distribution full name with - replaced with _ | Return distribution full name with - replaced with _ | def wheel_dist_name(self):
"""Return distribution full name with - replaced with _"""
components = (safer_name(self.distribution.get_name()),
safer_version(self.distribution.get_version()))
if self.build_number:
components += (self.build_number,)
return ... | [
"def",
"wheel_dist_name",
"(",
"self",
")",
":",
"components",
"=",
"(",
"safer_name",
"(",
"self",
".",
"distribution",
".",
"get_name",
"(",
")",
")",
",",
"safer_version",
"(",
"self",
".",
"distribution",
".",
"get_version",
"(",
")",
")",
")",
"if",... | [
160,
4
] | [
166,
35
] | python | en | ['en', 'en', 'en'] | True |
bdist_wheel.egg2dist | (self, egginfo_path, distinfo_path) | Convert an .egg-info directory into a .dist-info directory | Convert an .egg-info directory into a .dist-info directory | def egg2dist(self, egginfo_path, distinfo_path):
"""Convert an .egg-info directory into a .dist-info directory"""
def adios(p):
"""Appropriately delete directory, file or link."""
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p... | [
"def",
"egg2dist",
"(",
"self",
",",
"egginfo_path",
",",
"distinfo_path",
")",
":",
"def",
"adios",
"(",
"p",
")",
":",
"\"\"\"Appropriately delete directory, file or link.\"\"\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"p",
")",
"and",
"not",
"os",
"... | [
347,
4
] | [
402,
27
] | python | en | ['it', 'lb', 'en'] | False |
feed | (request, url, feed_dict=None) | Provided for backwards compatibility. | Provided for backwards compatibility. | def feed(request, url, feed_dict=None):
"""Provided for backwards compatibility."""
if not feed_dict:
raise Http404(_("No feeds are registered."))
slug = url.partition('/')[0]
try:
f = feed_dict[slug]
except KeyError:
raise Http404(_("Slug %r isn't registered.") % slug)
... | [
"def",
"feed",
"(",
"request",
",",
"url",
",",
"feed_dict",
"=",
"None",
")",
":",
"if",
"not",
"feed_dict",
":",
"raise",
"Http404",
"(",
"_",
"(",
"\"No feeds are registered.\"",
")",
")",
"slug",
"=",
"url",
".",
"partition",
"(",
"'/'",
")",
"[",
... | [
6,
0
] | [
21,
28
] | python | en | ['en', 'en', 'en'] | True |
_is_relevant_relation | (relation, altered_field) |
When altering the given field, must constraints on its model from the given
relation be temporarily dropped?
|
When altering the given field, must constraints on its model from the given
relation be temporarily dropped?
| def _is_relevant_relation(relation, altered_field):
"""
When altering the given field, must constraints on its model from the given
relation be temporarily dropped?
"""
field = relation.field
if field.many_to_many:
# M2M reverse field
return False
if altered_field.primary_key... | [
"def",
"_is_relevant_relation",
"(",
"relation",
",",
"altered_field",
")",
":",
"field",
"=",
"relation",
".",
"field",
"if",
"field",
".",
"many_to_many",
":",
"# M2M reverse field",
"return",
"False",
"if",
"altered_field",
".",
"primary_key",
"and",
"field",
... | [
14,
0
] | [
27,
48
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.execute | (self, sql, params=()) | Execute the given SQL statement, with optional parameters. | Execute the given SQL statement, with optional parameters. | def execute(self, sql, params=()):
"""Execute the given SQL statement, with optional parameters."""
# Don't perform the transactional DDL check if SQL is being collected
# as it's not going to be executed anyway.
if not self.collect_sql and self.connection.in_atomic_block and not self.co... | [
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"(",
")",
")",
":",
"# Don't perform the transactional DDL check if SQL is being collected",
"# as it's not going to be executed anyway.",
"if",
"not",
"self",
".",
"collect_sql",
"and",
"self",
".",
"connec... | [
120,
4
] | [
141,
43
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.table_sql | (self, model) | Take a model and return its table definition. | Take a model and return its table definition. | def table_sql(self, model):
"""Take a model and return its table definition."""
# Add any unique_togethers (always deferred, as some fields might be
# created afterwards, like geometry fields with some backends).
for fields in model._meta.unique_together:
columns = [model._me... | [
"def",
"table_sql",
"(",
"self",
",",
"model",
")",
":",
"# Add any unique_togethers (always deferred, as some fields might be",
"# created afterwards, like geometry fields with some backends).",
"for",
"fields",
"in",
"model",
".",
"_meta",
".",
"unique_together",
":",
"column... | [
146,
4
] | [
201,
26
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.column_sql | (self, model, field, include_default=False) |
Take a field and return its column definition.
The field must already have had set_attributes_from_name() called.
|
Take a field and return its column definition.
The field must already have had set_attributes_from_name() called.
| def column_sql(self, model, field, include_default=False):
"""
Take a field and return its column definition.
The field must already have had set_attributes_from_name() called.
"""
# Get the column's type and use that as the basis of the SQL
db_params = field.db_parameter... | [
"def",
"column_sql",
"(",
"self",
",",
"model",
",",
"field",
",",
"include_default",
"=",
"False",
")",
":",
"# Get the column's type and use that as the basis of the SQL",
"db_params",
"=",
"field",
".",
"db_parameters",
"(",
"connection",
"=",
"self",
".",
"conne... | [
205,
4
] | [
252,
26
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.skip_default | (self, field) |
Some backends don't accept default values for certain columns types
(i.e. MySQL longtext and longblob).
|
Some backends don't accept default values for certain columns types
(i.e. MySQL longtext and longblob).
| def skip_default(self, field):
"""
Some backends don't accept default values for certain columns types
(i.e. MySQL longtext and longblob).
"""
return False | [
"def",
"skip_default",
"(",
"self",
",",
"field",
")",
":",
"return",
"False"
] | [
254,
4
] | [
259,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.prepare_default | (self, value) |
Only used for backends which have requires_literal_defaults feature
|
Only used for backends which have requires_literal_defaults feature
| def prepare_default(self, value):
"""
Only used for backends which have requires_literal_defaults feature
"""
raise NotImplementedError(
'subclasses of BaseDatabaseSchemaEditor for backends which have '
'requires_literal_defaults must provide a prepare_default() m... | [
"def",
"prepare_default",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseSchemaEditor for backends which have '",
"'requires_literal_defaults must provide a prepare_default() method'",
")"
] | [
261,
4
] | [
268,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor._column_default_sql | (self, field) |
Return the SQL to use in a DEFAULT clause. The resulting string should
contain a '%s' placeholder for a default value.
|
Return the SQL to use in a DEFAULT clause. The resulting string should
contain a '%s' placeholder for a default value.
| def _column_default_sql(self, field):
"""
Return the SQL to use in a DEFAULT clause. The resulting string should
contain a '%s' placeholder for a default value.
"""
return '%s' | [
"def",
"_column_default_sql",
"(",
"self",
",",
"field",
")",
":",
"return",
"'%s'"
] | [
270,
4
] | [
275,
19
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.effective_default | (self, field) | Return a field's effective database default value. | Return a field's effective database default value. | def effective_default(self, field):
"""Return a field's effective database default value."""
return field.get_db_prep_save(self._effective_default(field), self.connection) | [
"def",
"effective_default",
"(",
"self",
",",
"field",
")",
":",
"return",
"field",
".",
"get_db_prep_save",
"(",
"self",
".",
"_effective_default",
"(",
"field",
")",
",",
"self",
".",
"connection",
")"
] | [
300,
4
] | [
302,
86
] | python | da | ['ro', 'da', 'en'] | False |
BaseDatabaseSchemaEditor.quote_value | (self, value) |
Return a quoted version of the value so it's safe to use in an SQL
string. This is not safe against injection from user code; it is
intended only for use in making SQL scripts or preparing default values
for particularly tricky backends (defaults are not user-defined, though,
so... |
Return a quoted version of the value so it's safe to use in an SQL
string. This is not safe against injection from user code; it is
intended only for use in making SQL scripts or preparing default values
for particularly tricky backends (defaults are not user-defined, though,
so... | def quote_value(self, value):
"""
Return a quoted version of the value so it's safe to use in an SQL
string. This is not safe against injection from user code; it is
intended only for use in making SQL scripts or preparing default values
for particularly tricky backends (defaults... | [
"def",
"quote_value",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
304,
4
] | [
312,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.create_model | (self, model) |
Create a table and any accompanying indexes or unique constraints for
the given `model`.
|
Create a table and any accompanying indexes or unique constraints for
the given `model`.
| def create_model(self, model):
"""
Create a table and any accompanying indexes or unique constraints for
the given `model`.
"""
sql, params = self.table_sql(model)
# Prevent using [] as params, in the case a literal '%' is used in the definition
self.execute(sql, ... | [
"def",
"create_model",
"(",
"self",
",",
"model",
")",
":",
"sql",
",",
"params",
"=",
"self",
".",
"table_sql",
"(",
"model",
")",
"# Prevent using [] as params, in the case a literal '%' is used in the definition",
"self",
".",
"execute",
"(",
"sql",
",",
"params"... | [
316,
4
] | [
331,
61
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.delete_model | (self, model) | Delete a model from the database. | Delete a model from the database. | def delete_model(self, model):
"""Delete a model from the database."""
# Handle auto-created intermediary models
for field in model._meta.local_many_to_many:
if field.remote_field.through._meta.auto_created:
self.delete_model(field.remote_field.through)
# Del... | [
"def",
"delete_model",
"(",
"self",
",",
"model",
")",
":",
"# Handle auto-created intermediary models",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"local_many_to_many",
":",
"if",
"field",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"auto_cre... | [
333,
4
] | [
347,
45
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.add_index | (self, model, index) | Add an index on a model. | Add an index on a model. | def add_index(self, model, index):
"""Add an index on a model."""
self.execute(index.create_sql(model, self), params=None) | [
"def",
"add_index",
"(",
"self",
",",
"model",
",",
"index",
")",
":",
"self",
".",
"execute",
"(",
"index",
".",
"create_sql",
"(",
"model",
",",
"self",
")",
",",
"params",
"=",
"None",
")"
] | [
349,
4
] | [
351,
64
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.remove_index | (self, model, index) | Remove an index from a model. | Remove an index from a model. | def remove_index(self, model, index):
"""Remove an index from a model."""
self.execute(index.remove_sql(model, self)) | [
"def",
"remove_index",
"(",
"self",
",",
"model",
",",
"index",
")",
":",
"self",
".",
"execute",
"(",
"index",
".",
"remove_sql",
"(",
"model",
",",
"self",
")",
")"
] | [
353,
4
] | [
355,
51
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.add_constraint | (self, model, constraint) | Add a constraint to a model. | Add a constraint to a model. | def add_constraint(self, model, constraint):
"""Add a constraint to a model."""
sql = constraint.create_sql(model, self)
if sql:
self.execute(sql) | [
"def",
"add_constraint",
"(",
"self",
",",
"model",
",",
"constraint",
")",
":",
"sql",
"=",
"constraint",
".",
"create_sql",
"(",
"model",
",",
"self",
")",
"if",
"sql",
":",
"self",
".",
"execute",
"(",
"sql",
")"
] | [
357,
4
] | [
361,
29
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.remove_constraint | (self, model, constraint) | Remove a constraint from a model. | Remove a constraint from a model. | def remove_constraint(self, model, constraint):
"""Remove a constraint from a model."""
sql = constraint.remove_sql(model, self)
if sql:
self.execute(sql) | [
"def",
"remove_constraint",
"(",
"self",
",",
"model",
",",
"constraint",
")",
":",
"sql",
"=",
"constraint",
".",
"remove_sql",
"(",
"model",
",",
"self",
")",
"if",
"sql",
":",
"self",
".",
"execute",
"(",
"sql",
")"
] | [
363,
4
] | [
367,
29
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.alter_unique_together | (self, model, old_unique_together, new_unique_together) |
Deal with a model changing its unique_together. The input
unique_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
|
Deal with a model changing its unique_together. The input
unique_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
| def alter_unique_together(self, model, old_unique_together, new_unique_together):
"""
Deal with a model changing its unique_together. The input
unique_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
"""
olds = {tuple(fields) for fields in old... | [
"def",
"alter_unique_together",
"(",
"self",
",",
"model",
",",
"old_unique_together",
",",
"new_unique_together",
")",
":",
"olds",
"=",
"{",
"tuple",
"(",
"fields",
")",
"for",
"fields",
"in",
"old_unique_together",
"}",
"news",
"=",
"{",
"tuple",
"(",
"fi... | [
369,
4
] | [
383,
65
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.alter_index_together | (self, model, old_index_together, new_index_together) |
Deal with a model changing its index_together. The input
index_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
|
Deal with a model changing its index_together. The input
index_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
| def alter_index_together(self, model, old_index_together, new_index_together):
"""
Deal with a model changing its index_together. The input
index_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
"""
olds = {tuple(fields) for fields in old_inde... | [
"def",
"alter_index_together",
"(",
"self",
",",
"model",
",",
"old_index_together",
",",
"new_index_together",
")",
":",
"olds",
"=",
"{",
"tuple",
"(",
"fields",
")",
"for",
"fields",
"in",
"old_index_together",
"}",
"news",
"=",
"{",
"tuple",
"(",
"fields... | [
385,
4
] | [
399,
78
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseSchemaEditor.alter_db_table | (self, model, old_db_table, new_db_table) | Rename the table a model points to. | Rename the table a model points to. | def alter_db_table(self, model, old_db_table, new_db_table):
"""Rename the table a model points to."""
if (old_db_table == new_db_table or
(self.connection.features.ignores_table_name_case and
old_db_table.lower() == new_db_table.lower())):
return
self.exe... | [
"def",
"alter_db_table",
"(",
"self",
",",
"model",
",",
"old_db_table",
",",
"new_db_table",
")",
":",
"if",
"(",
"old_db_table",
"==",
"new_db_table",
"or",
"(",
"self",
".",
"connection",
".",
"features",
".",
"ignores_table_name_case",
"and",
"old_db_table",... | [
417,
4
] | [
430,
71
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.alter_db_tablespace | (self, model, old_db_tablespace, new_db_tablespace) | Move a model's table between tablespaces. | Move a model's table between tablespaces. | def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
"""Move a model's table between tablespaces."""
self.execute(self.sql_retablespace_table % {
"table": self.quote_name(model._meta.db_table),
"old_tablespace": self.quote_name(old_db_tablespace),
... | [
"def",
"alter_db_tablespace",
"(",
"self",
",",
"model",
",",
"old_db_tablespace",
",",
"new_db_tablespace",
")",
":",
"self",
".",
"execute",
"(",
"self",
".",
"sql_retablespace_table",
"%",
"{",
"\"table\"",
":",
"self",
".",
"quote_name",
"(",
"model",
".",... | [
432,
4
] | [
438,
10
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseSchemaEditor.add_field | (self, model, field) |
Create a field on a model. Usually involves adding a column, but may
involve adding a table instead (for M2M fields).
|
Create a field on a model. Usually involves adding a column, but may
involve adding a table instead (for M2M fields).
| def add_field(self, model, field):
"""
Create a field on a model. Usually involves adding a column, but may
involve adding a table instead (for M2M fields).
"""
# Special-case implicit M2M tables
if field.many_to_many and field.remote_field.through._meta.auto_created:
... | [
"def",
"add_field",
"(",
"self",
",",
"model",
",",
"field",
")",
":",
"# Special-case implicit M2M tables",
"if",
"field",
".",
"many_to_many",
"and",
"field",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"auto_created",
":",
"return",
"self",
".",... | [
440,
4
] | [
495,
35
] | 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.