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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
catch_ldap_error | (signal: Signal, **kwargs: Any) |
Inside django_auth_ldap populate_user(), if LDAPError is raised,
e.g. due to invalid connection credentials, the function catches it
and emits a signal (ldap_error) to communicate this error to others.
We normally don't use signals, but here there's no choice, so in this function
we essentially con... |
Inside django_auth_ldap populate_user(), if LDAPError is raised,
e.g. due to invalid connection credentials, the function catches it
and emits a signal (ldap_error) to communicate this error to others.
We normally don't use signals, but here there's no choice, so in this function
we essentially con... | def catch_ldap_error(signal: Signal, **kwargs: Any) -> None:
"""
Inside django_auth_ldap populate_user(), if LDAPError is raised,
e.g. due to invalid connection credentials, the function catches it
and emits a signal (ldap_error) to communicate this error to others.
We normally don't use signals, bu... | [
"def",
"catch_ldap_error",
"(",
"signal",
":",
"Signal",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"if",
"kwargs",
"[",
"\"context\"",
"]",
"==",
"\"populate_user\"",
":",
"# The exception message can contain the password (if it was invalid),",
"#... | [
926,
0
] | [
938,
75
] | python | en | ['en', 'error', 'th'] | False |
social_associate_user_helper | (
backend: BaseAuth, return_data: Dict[str, Any], *args: Any, **kwargs: Any
) | Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in most other auth backends in this file).
Returns a UserProfile object for successful authentication, and None otherwise.
| Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in most other auth backends in this file). | def social_associate_user_helper(
backend: BaseAuth, return_data: Dict[str, Any], *args: Any, **kwargs: Any
) -> Union[HttpResponse, Optional[UserProfile]]:
"""Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in ... | [
"def",
"social_associate_user_helper",
"(",
"backend",
":",
"BaseAuth",
",",
"return_data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Union",
"[",
"HttpResponse",
",",
"Opti... | [
1233,
0
] | [
1371,
23
] | python | en | ['en', 'en', 'en'] | True |
social_auth_associate_user | (
backend: BaseAuth, *args: Any, **kwargs: Any
) | A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
later stages of settings.SOCIAL_AUTH_PIPELINE, such as
social_auth_finish, as kwargs.
| A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
later stages of settings.SOCIAL_AUTH_PIPELINE, such as
social_auth_finish, as kwargs.
| def social_auth_associate_user(
backend: BaseAuth, *args: Any, **kwargs: Any
) -> Union[HttpResponse, Dict[str, Any]]:
"""A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
l... | [
"def",
"social_auth_associate_user",
"(",
"backend",
":",
"BaseAuth",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Union",
"[",
"HttpResponse",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"partial_token",
"=",
... | [
1375,
0
] | [
1396,
9
] | python | en | ['en', 'en', 'en'] | True |
social_auth_finish | (
backend: Any, details: Dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any
) | Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropriate) and redirecting the browser
to the appropriate next page depending on the situation. Read the
comments below as well as login_or_register_... | Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropriate) and redirecting the browser
to the appropriate next page depending on the situation. Read the
comments below as well as login_or_register_... | def social_auth_finish(
backend: Any, details: Dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any
) -> Optional[HttpResponse]:
"""Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropr... | [
"def",
"social_auth_finish",
"(",
"backend",
":",
"Any",
",",
"details",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"response",
":",
"HttpResponse",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Optional",
"[",
... | [
1399,
0
] | [
1526,
50
] | python | en | ['en', 'en', 'en'] | True |
get_external_method_dicts | (realm: Optional[Realm] = None) |
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed.
|
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed.
| def get_external_method_dicts(realm: Optional[Realm] = None) -> List[ExternalAuthMethodDictT]:
"""
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed.
"""
result: List[ExternalAuthMethodDictT] = []
for backend in EXTERNAL_AUTH_MET... | [
"def",
"get_external_method_dicts",
"(",
"realm",
":",
"Optional",
"[",
"Realm",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"ExternalAuthMethodDictT",
"]",
":",
"result",
":",
"List",
"[",
"ExternalAuthMethodDictT",
"]",
"=",
"[",
"]",
"for",
"backend",
"in",... | [
2220,
0
] | [
2232,
17
] | python | en | ['en', 'error', 'th'] | False |
ZulipAuthMixin.get_user | (self, user_profile_id: int) | Override the Django method for getting a UserProfile object from
the user_profile_id,. | Override the Django method for getting a UserProfile object from
the user_profile_id,. | def get_user(self, user_profile_id: int) -> Optional[UserProfile]:
"""Override the Django method for getting a UserProfile object from
the user_profile_id,."""
try:
return get_user_profile_by_id(user_profile_id)
except UserProfile.DoesNotExist:
return None | [
"def",
"get_user",
"(",
"self",
",",
"user_profile_id",
":",
"int",
")",
"->",
"Optional",
"[",
"UserProfile",
"]",
":",
"try",
":",
"return",
"get_user_profile_by_id",
"(",
"user_profile_id",
")",
"except",
"UserProfile",
".",
"DoesNotExist",
":",
"return",
"... | [
317,
4
] | [
323,
23
] | python | en | ['en', 'en', 'en'] | True |
EmailAuthBackend.authenticate | (
self,
request: Optional[HttpRequest] = None,
*,
username: str,
password: str,
realm: Realm,
return_data: Optional[Dict[str, Any]] = None,
) | Authenticate a user based on email address as the user name. | Authenticate a user based on email address as the user name. | def authenticate(
self,
request: Optional[HttpRequest] = None,
*,
username: str,
password: str,
realm: Realm,
return_data: Optional[Dict[str, Any]] = None,
) -> Optional[UserProfile]:
""" Authenticate a user based on email address as the user name. """... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
":",
"Optional",
"[",
"HttpRequest",
"]",
"=",
"None",
",",
"*",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"realm",
":",
"Realm",
",",
"return_data",
":",
"Optional",
"[",
"Dict",... | [
378,
4
] | [
407,
19
] | python | en | ['en', 'en', 'en'] | True |
ZulipLDAPAuthBackendBase.django_to_ldap_username | (self, username: str) |
Translates django username (user_profile.delivery_email or whatever the user typed in the login
field when authenticating via the LDAP backend) into LDAP username.
Guarantees that the username it returns actually has an entry in the LDAP directory.
Raises ZulipLDAPExceptionNoMatchingLDA... |
Translates django username (user_profile.delivery_email or whatever the user typed in the login
field when authenticating via the LDAP backend) into LDAP username.
Guarantees that the username it returns actually has an entry in the LDAP directory.
Raises ZulipLDAPExceptionNoMatchingLDA... | def django_to_ldap_username(self, username: str) -> str:
"""
Translates django username (user_profile.delivery_email or whatever the user typed in the login
field when authenticating via the LDAP backend) into LDAP username.
Guarantees that the username it returns actually has an entry i... | [
"def",
"django_to_ldap_username",
"(",
"self",
",",
"username",
":",
"str",
")",
"->",
"str",
":",
"result",
"=",
"username",
"if",
"settings",
".",
"LDAP_APPEND_DOMAIN",
":",
"if",
"is_valid_email",
"(",
"username",
")",
":",
"if",
"not",
"username",
".",
... | [
515,
4
] | [
555,
21
] | python | en | ['en', 'error', 'th'] | False |
ZulipLDAPAuthBackendBase.ldap_to_django_username | (self, username: str) |
This is called inside django_auth_ldap with only one role:
to convert _LDAPUser._username to django username (so in Zulip, the email)
and pass that as "username" argument to get_or_build_user(username, ldapuser).
In many cases, the email is stored in the _LDAPUser's attributes, so it ca... |
This is called inside django_auth_ldap with only one role:
to convert _LDAPUser._username to django username (so in Zulip, the email)
and pass that as "username" argument to get_or_build_user(username, ldapuser).
In many cases, the email is stored in the _LDAPUser's attributes, so it ca... | def ldap_to_django_username(self, username: str) -> str:
"""
This is called inside django_auth_ldap with only one role:
to convert _LDAPUser._username to django username (so in Zulip, the email)
and pass that as "username" argument to get_or_build_user(username, ldapuser).
In man... | [
"def",
"ldap_to_django_username",
"(",
"self",
",",
"username",
":",
"str",
")",
"->",
"str",
":",
"return",
"username"
] | [
577,
4
] | [
587,
23
] | python | en | ['en', 'error', 'th'] | False |
ZulipLDAPAuthBackendBase.is_account_control_disabled_user | (self, ldap_user: _LDAPUser) | Implements the userAccountControl check for whether a user has been
disabled in an Active Directory server being integrated with
Zulip via LDAP. | Implements the userAccountControl check for whether a user has been
disabled in an Active Directory server being integrated with
Zulip via LDAP. | def is_account_control_disabled_user(self, ldap_user: _LDAPUser) -> bool:
"""Implements the userAccountControl check for whether a user has been
disabled in an Active Directory server being integrated with
Zulip via LDAP."""
account_control_value = ldap_user.attrs[
settings.A... | [
"def",
"is_account_control_disabled_user",
"(",
"self",
",",
"ldap_user",
":",
"_LDAPUser",
")",
"->",
"bool",
":",
"account_control_value",
"=",
"ldap_user",
".",
"attrs",
"[",
"settings",
".",
"AUTH_LDAP_USER_ATTR_MAP",
"[",
"\"userAccountControl\"",
"]",
"]",
"["... | [
623,
4
] | [
631,
28
] | python | en | ['en', 'en', 'en'] | True |
ZulipLDAPAuthBackendBase.get_mapped_name | (cls, ldap_user: _LDAPUser) | Constructs the user's Zulip full_name from the LDAP data | Constructs the user's Zulip full_name from the LDAP data | def get_mapped_name(cls, ldap_user: _LDAPUser) -> str:
"""Constructs the user's Zulip full_name from the LDAP data"""
if "full_name" in settings.AUTH_LDAP_USER_ATTR_MAP:
full_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["full_name"]
full_name = ldap_user.attrs[full_name_attr][0]
... | [
"def",
"get_mapped_name",
"(",
"cls",
",",
"ldap_user",
":",
"_LDAPUser",
")",
"->",
"str",
":",
"if",
"\"full_name\"",
"in",
"settings",
".",
"AUTH_LDAP_USER_ATTR_MAP",
":",
"full_name_attr",
"=",
"settings",
".",
"AUTH_LDAP_USER_ATTR_MAP",
"[",
"\"full_name\"",
... | [
642,
4
] | [
656,
24
] | python | en | ['en', 'en', 'en'] | True |
ZulipLDAPAuthBackend.get_or_build_user | (self, username: str, ldap_user: _LDAPUser) | The main function of our authentication backend extension of
django-auth-ldap. When this is called (from `authenticate`),
django-auth-ldap will already have verified that the provided
username and password match those in the LDAP database.
This function's responsibility is to check (1)... | The main function of our authentication backend extension of
django-auth-ldap. When this is called (from `authenticate`),
django-auth-ldap will already have verified that the provided
username and password match those in the LDAP database. | def get_or_build_user(self, username: str, ldap_user: _LDAPUser) -> Tuple[UserProfile, bool]:
"""The main function of our authentication backend extension of
django-auth-ldap. When this is called (from `authenticate`),
django-auth-ldap will already have verified that the provided
userna... | [
"def",
"get_or_build_user",
"(",
"self",
",",
"username",
":",
"str",
",",
"ldap_user",
":",
"_LDAPUser",
")",
"->",
"Tuple",
"[",
"UserProfile",
",",
"bool",
"]",
":",
"return_data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"username",... | [
758,
4
] | [
844,
33
] | python | en | ['en', 'en', 'en'] | True |
ZulipLDAPUserPopulator.get_or_build_user | (
self, username: str, ldap_user: ZulipLDAPUser
) | This is used only in non-authentication contexts such as:
./manage.py sync_ldap_user_data
| This is used only in non-authentication contexts such as:
./manage.py sync_ldap_user_data
| def get_or_build_user(
self, username: str, ldap_user: ZulipLDAPUser
) -> Tuple[UserProfile, bool]:
"""This is used only in non-authentication contexts such as:
./manage.py sync_ldap_user_data
"""
# Obtain the django username from the ldap_user object:
username = self... | [
"def",
"get_or_build_user",
"(",
"self",
",",
"username",
":",
"str",
",",
"ldap_user",
":",
"ZulipLDAPUser",
")",
"->",
"Tuple",
"[",
"UserProfile",
",",
"bool",
"]",
":",
"# Obtain the django username from the ldap_user object:",
"username",
"=",
"self",
".",
"u... | [
882,
4
] | [
918,
28
] | python | en | ['en', 'en', 'en'] | True |
ExternalAuthMethod.dict_representation | (cls, realm: Optional[Realm] = None) |
Method returning dictionaries representing the authentication methods
corresponding to the backend that subclasses this. The documentation
for the external_authentication_methods field of the /server_settings endpoint
explains the details of these dictionaries.
This returns a li... |
Method returning dictionaries representing the authentication methods
corresponding to the backend that subclasses this. The documentation
for the external_authentication_methods field of the /server_settings endpoint
explains the details of these dictionaries.
This returns a li... | def dict_representation(cls, realm: Optional[Realm] = None) -> List[ExternalAuthMethodDictT]:
"""
Method returning dictionaries representing the authentication methods
corresponding to the backend that subclasses this. The documentation
for the external_authentication_methods field of th... | [
"def",
"dict_representation",
"(",
"cls",
",",
"realm",
":",
"Optional",
"[",
"Realm",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"ExternalAuthMethodDictT",
"]",
":"
] | [
1054,
4
] | [
1062,
11
] | python | en | ['en', 'error', 'th'] | False |
SocialAuthMixin.auth_complete | (self, *args: Any, **kwargs: Any) | This is a small wrapper around the core `auth_complete` method of
python-social-auth, designed primarily to prevent 500s for
exceptions in the social auth code from situations that are
really user errors. Returning `None` from this function will
redirect the browser to the login page.
... | This is a small wrapper around the core `auth_complete` method of
python-social-auth, designed primarily to prevent 500s for
exceptions in the social auth code from situations that are
really user errors. Returning `None` from this function will
redirect the browser to the login page.
... | def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
"""This is a small wrapper around the core `auth_complete` method of
python-social-auth, designed primarily to prevent 500s for
exceptions in the social auth code from situations that are
really user errors. R... | [
"def",
"auth_complete",
"(",
"self",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Optional",
"[",
"HttpResponse",
"]",
":",
"try",
":",
"# Call the auth_complete method of social_core.backends.oauth.BaseOAuth2",
"return",
"super",... | [
1544,
4
] | [
1566,
23
] | python | en | ['en', 'en', 'en'] | True |
load_target_class | (input_dir) | Loads target classes. | Loads target classes. | def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, "target_class.csv")) as f:
return {row[0]: int(row[1]) for row in csv.reader(f) if len(row) >= 2} | [
"def",
"load_target_class",
"(",
"input_dir",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"\"target_class.csv\"",
")",
")",
"as",
"f",
":",
"return",
"{",
"row",
"[",
"0",
"]",
":",
... | [
40,
0
] | [
43,
78
] | python | en | ['en', 'bg', 'en'] | True |
load_images | (input_dir, batch_shape) | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be less than batch_size, in this case o... | Read png images from input directory in batches. | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this li... | [
"def",
"load_images",
"(",
"input_dir",
",",
"batch_shape",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"batch_shape",
")",
"filenames",
"=",
"[",
"]",
"idx",
"=",
"0",
"batch_size",
"=",
"batch_shape",
"[",
"0",
"]",
"for",
"filepath",
"in",
"tf... | [
46,
0
] | [
76,
31
] | python | en | ['en', 'en', 'en'] | True |
save_images | (images, filenames, output_dir) | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory ... | Saves images to the output directory. | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filena... | [
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"# Images for inception classifier are normalized to be in [-1, 1] interval,",
"# so rescale them back to [0, 1]."... | [
79,
0
] | [
93,
69
] | python | en | ['en', 'en', 'en'] | True |
Read_input | (data, batch_size) |
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
sample_rate: a numpy array
trans: an array includes the targeted transcriptions (batch_size,)
|
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
sample_rate: a numpy array
trans: an array includes the targeted transcriptions (batch_size,)
| def Read_input(data, batch_size):
"""
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
sample_rate: a numpy array
trans: an array includes the targeted transcriptions (batch_size,)
"""
audios = []
lengths = []
for i in range(batch_size):
... | [
"def",
"Read_input",
"(",
"data",
",",
"batch_size",
")",
":",
"audios",
"=",
"[",
"]",
"lengths",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"batch_size",
")",
":",
"name",
",",
"_",
"=",
"data",
"[",
"0",
",",
"i",
"]",
".",
"split",
"(",... | [
34,
0
] | [
86,
83
] | python | en | ['en', 'error', 'th'] | False |
Readrir | (num_room) |
Return:
rir: a numpy array of the room reverberation
(make sure the test rooms are different from training rooms)
|
Return:
rir: a numpy array of the room reverberation
(make sure the test rooms are different from training rooms) | def Readrir(num_room):
"""
Return:
rir: a numpy array of the room reverberation
(make sure the test rooms are different from training rooms)
"""
index = num_room + FLAGS.num_train_rooms + 1
_, rir = wav.read(FLAGS.root_dir + FLAGS.rir_dir + "_rir_" + str(index) + ".wav")
return ... | [
"def",
"Readrir",
"(",
"num_room",
")",
":",
"index",
"=",
"num_room",
"+",
"FLAGS",
".",
"num_train_rooms",
"+",
"1",
"_",
",",
"rir",
"=",
"wav",
".",
"read",
"(",
"FLAGS",
".",
"root_dir",
"+",
"FLAGS",
".",
"rir_dir",
"+",
"\"_rir_\"",
"+",
"str"... | [
89,
0
] | [
98,
14
] | python | en | ['en', 'error', 'th'] | False |
safe_name | (name) | Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
| Convert an arbitrary string to a standard distribution name | def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | [
"def",
"safe_name",
"(",
"name",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"name",
")"
] | [
53,
0
] | [
58,
46
] | python | en | ['en', 'en', 'en'] | True |
safe_version | (version) | Convert an arbitrary string to a standard version string
Spaces become dots, and all other non-alphanumeric characters become
dashes, with runs of multiple dashes condensed to a single dash.
| Convert an arbitrary string to a standard version string | def safe_version(version):
"""Convert an arbitrary string to a standard version string
Spaces become dots, and all other non-alphanumeric characters become
dashes, with runs of multiple dashes condensed to a single dash.
"""
version = version.replace(' ','.')
return re.sub('[^A-Za-z0-9.]+', '-'... | [
"def",
"safe_version",
"(",
"version",
")",
":",
"version",
"=",
"version",
".",
"replace",
"(",
"' '",
",",
"'.'",
")",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"version",
")"
] | [
61,
0
] | [
68,
49
] | python | en | ['en', 'en', 'en'] | True |
to_filename | (name) | Convert a project or version name to its filename-escaped form
Any '-' characters are currently replaced with '_'.
| Convert a project or version name to its filename-escaped form | def to_filename(name):
"""Convert a project or version name to its filename-escaped form
Any '-' characters are currently replaced with '_'.
"""
return name.replace('-','_') | [
"def",
"to_filename",
"(",
"name",
")",
":",
"return",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")"
] | [
71,
0
] | [
76,
32
] | python | en | ['en', 'en', 'en'] | True |
autoescape | (parser, token) |
Force autoescape behavior for this block.
|
Force autoescape behavior for this block.
| def autoescape(parser, token):
"""
Force autoescape behavior for this block.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
if len(args) != 2:
raise TemplateSyntaxError("'autoescape' tag requires exactly ... | [
"def",
"autoescape",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
"... | [
564,
0
] | [
577,
57
] | python | en | ['en', 'error', 'th'] | False |
comment | (parser, token) |
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
|
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
| def comment(parser, token):
"""
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
"""
parser.skip_past('endcomment')
return CommentNode() | [
"def",
"comment",
"(",
"parser",
",",
"token",
")",
":",
"parser",
".",
"skip_past",
"(",
"'endcomment'",
")",
"return",
"CommentNode",
"(",
")"
] | [
581,
0
] | [
586,
24
] | python | en | ['en', 'error', 'th'] | False |
cycle | (parser, token) |
Cycles among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through
the loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Outside of a loo... |
Cycles among the given strings each time this tag is encountered. | def cycle(parser, token):
"""
Cycles among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through
the loop::
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{... | [
"def",
"cycle",
"(",
"parser",
",",
"token",
")",
":",
"# Note: This returns the exact same node on each {% cycle name %} call;",
"# that is, the node object returned from {% cycle a b c as name %} and the",
"# one returned from {% cycle name %} are the exact same object. This",
"# shouldn't c... | [
590,
0
] | [
676,
15
] | python | en | ['en', 'error', 'th'] | False |
debug | (parser, token) |
Outputs a whole load of debugging information, including the current
context and imported modules.
Sample usage::
<pre>
{% debug %}
</pre>
|
Outputs a whole load of debugging information, including the current
context and imported modules. | def debug(parser, token):
"""
Outputs a whole load of debugging information, including the current
context and imported modules.
Sample usage::
<pre>
{% debug %}
</pre>
"""
return DebugNode() | [
"def",
"debug",
"(",
"parser",
",",
"token",
")",
":",
"return",
"DebugNode",
"(",
")"
] | [
685,
0
] | [
696,
22
] | python | en | ['en', 'error', 'th'] | False |
do_filter | (parser, token) |
Filters the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in lowercase.
... |
Filters the contents of the block through variable filters. | def do_filter(parser, token):
"""
Filters the contents of the block through variable filters.
Filters can also be piped through each other, and they can have
arguments -- just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escape... | [
"def",
"do_filter",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"_",
",",
"rest",
"=",
"token",
".",
"contents",
".",
"split",
"(",
"None",
",",
"1",
")",
"filter_expr",
"="... | [
700,
0
] | [
726,
44
] | python | en | ['en', 'error', 'th'] | False |
firstof | (parser, token) |
Outputs the first variable passed that is not False, without escaping.
Outputs nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 %}
This is equivalent to::
{% if var1 %}
{{ var1|safe }}
{% elif var2 %}
{{ var2|sa... |
Outputs the first variable passed that is not False, without escaping. | def firstof(parser, token):
"""
Outputs the first variable passed that is not False, without escaping.
Outputs nothing if all the passed variables are False.
Sample usage::
{% firstof var1 var2 var3 %}
This is equivalent to::
{% if var1 %}
{{ var1|safe }}
{% ... | [
"def",
"firstof",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"bits",
")",
"<",
"1",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'firstof' statement requires at least ... | [
730,
0
] | [
767,
68
] | python | en | ['en', 'error', 'th'] | False |
do_for | (parser, token) |
Loops over each item in an array.
For example, to display a list of athletes given ``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by using
``{% for obj in list re... |
Loops over each item in an array. | def do_for(parser, token):
"""
Loops over each item in an array.
For example, to display a list of athletes given ``athlete_list``::
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
You can loop over a list in reverse by... | [
"def",
"do_for",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"4",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'for' statements should have at least four\"",
"\" words: %s\"",
... | [
771,
0
] | [
859,
82
] | python | en | ['en', 'error', 'th'] | False |
ifequal | (parser, token) |
Outputs the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
{% endifnotequal %}
|
Outputs the contents of the block if the two arguments equal each other. | def ifequal(parser, token):
"""
Outputs the contents of the block if the two arguments equal each other.
Examples::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
{% ifnotequal user.id comment.user_id %}
...
{% else %}
...
... | [
"def",
"ifequal",
"(",
"parser",
",",
"token",
")",
":",
"return",
"do_ifequal",
"(",
"parser",
",",
"token",
",",
"False",
")"
] | [
880,
0
] | [
896,
43
] | python | en | ['en', 'error', 'th'] | False |
ifnotequal | (parser, token) |
Outputs the contents of the block if the two arguments are not equal.
See ifequal.
|
Outputs the contents of the block if the two arguments are not equal.
See ifequal.
| def ifnotequal(parser, token):
"""
Outputs the contents of the block if the two arguments are not equal.
See ifequal.
"""
return do_ifequal(parser, token, True) | [
"def",
"ifnotequal",
"(",
"parser",
",",
"token",
")",
":",
"return",
"do_ifequal",
"(",
"parser",
",",
"token",
",",
"True",
")"
] | [
900,
0
] | [
905,
42
] | python | en | ['en', 'error', 'th'] | False |
do_if | (parser, token) |
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
{% elif athlete_in_locker_r... |
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output: | def do_if(parser, token):
"""
The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
(i.e., exists, is not empty, and is not a false boolean value), the
contents of the block are output:
::
{% if athlete_list %}
Number of athletes: {{ athlete_list|count }}
... | [
"def",
"do_if",
"(",
"parser",
",",
"token",
")",
":",
"# {% if ... %}",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"condition",
"=",
"TemplateIfParser",
"(",
"parser",
",",
"bits",
")",
".",
"parse",
"(",
")",
"nodelist... | [
932,
0
] | [
1015,
39
] | python | en | ['en', 'error', 'th'] | False |
ifchanged | (parser, token) |
Checks if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a
... |
Checks if a value has changed from the last iteration of a loop. | def ifchanged(parser, token):
"""
Checks if a value has changed from the last iteration of a loop.
The ``{% ifchanged %}`` block tag is used within a loop. It has two
possible uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has change... | [
"def",
"ifchanged",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"nodelist_true",
"=",
"parser",
".",
"parse",
"(",
"(",
"'else'",
",",
"'endifchanged'",
")",
")",
"token",
"=",
"parser",
".",
"next_token"... | [
1019,
0
] | [
1057,
64
] | python | en | ['en', 'error', 'th'] | False |
ssi | (parser, token) |
Outputs the contents of a given file into the page.
Like a simple "include" tag, the ``ssi`` tag includes the contents
of another file -- which must be specified using an absolute path --
in the current page::
{% ssi "/home/html/ljworld.com/includes/right_generic.html" %}
If the optional... |
Outputs the contents of a given file into the page. | def ssi(parser, token):
"""
Outputs the contents of a given file into the page.
Like a simple "include" tag, the ``ssi`` tag includes the contents
of another file -- which must be specified using an absolute path --
in the current page::
{% ssi "/home/html/ljworld.com/includes/right_generi... | [
"def",
"ssi",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"parsed",
"=",
"False",
"if",
"len",
"(",
"bits",
")",
"not",
"in",
"(",
"2",
",",
"3",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'s... | [
1061,
0
] | [
1088,
36
] | python | en | ['en', 'error', 'th'] | False |
load | (parser, token) |
Loads a custom template tag set.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
|
Loads a custom template tag set. | def load(parser, token):
"""
Loads a custom template tag set.
For example, to load the template tags in
``django/templatetags/news/photos.py``::
{% load news.photos %}
Can also be used to load an individual tag/filter from
a library::
{% load byline from news %}
"""
... | [
"def",
"load",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"4",
"and",
... | [
1092,
0
] | [
1139,
21
] | python | en | ['en', 'error', 'th'] | False |
lorem | (parser, token) |
Creates random Latin text useful for providing test data in templates.
Usage format::
{% lorem [count] [method] [random] %}
``count`` is a number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` is either ``w`` for words, ``p`` for HTML p... |
Creates random Latin text useful for providing test data in templates. | def lorem(parser, token):
"""
Creates random Latin text useful for providing test data in templates.
Usage format::
{% lorem [count] [method] [random] %}
``count`` is a number (or variable) containing the number of paragraphs or
words to generate (default is 1).
``method`` is either ... | [
"def",
"lorem",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"list",
"(",
"token",
".",
"split_contents",
"(",
")",
")",
"tagname",
"=",
"bits",
"[",
"0",
"]",
"# Random bit",
"common",
"=",
"bits",
"[",
"-",
"1",
"]",
"!=",
"'random'",
"if"... | [
1143,
0
] | [
1186,
43
] | python | en | ['en', 'error', 'th'] | False |
now | (parser, token) |
Displays the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
|
Displays the date, formatted according to the given string. | def now(parser, token):
"""
Displays the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
"""
bits = token.split_contents()
if len(... | [
"def",
"now",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'now' statement takes one argument\"",
")",
"format_string",
"=... | [
1190,
0
] | [
1205,
33
] | python | en | ['en', 'error', 'th'] | False |
regroup | (parser, token) |
Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``people`` is a list of ``Person`` objects that have ``first_name``,
``last_name``, and ``gender`` attributes, and you'd like to display a list
that looks like:
* M... |
Regroups a list of alike objects by a common attribute. | def regroup(parser, token):
"""
Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that
``people`` is a list of ``Person`` objects that have ``first_name``,
``last_name``, and ``gender`` attributes, and you'd like to display a lis... | [
"def",
"regroup",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"6",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'regroup' tag takes five arguments\"",
")",
"target",
"=",
... | [
1209,
0
] | [
1274,
52
] | python | en | ['en', 'error', 'th'] | False |
spaceless | (parser, token) |
Removes whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example would return this HTML::
<p><a href="foo/">Foo</a></p>
Only sp... |
Removes whitespace between HTML tags, including tab and newline characters. | def spaceless(parser, token):
"""
Removes whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example would return this HTML::
<p><a... | [
"def",
"spaceless",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endspaceless'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"SpacelessNode",
"(",
"nodelist",
")"
] | [
1278,
0
] | [
1305,
34
] | python | en | ['en', 'error', 'th'] | False |
templatetag | (parser, token) |
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
================== =======
Ar... |
Outputs one of the bits used to compose template tags. | def templatetag(parser, token):
"""
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
... | [
"def",
"templatetag",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
... | [
1309,
0
] | [
1340,
31
] | python | en | ['en', 'error', 'th'] | False |
url | (parser, token) |
Returns an absolute URL matching given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url "path.to.some_view" arg1 arg2 %}
or
{% url "path.to.some_view" name1=value1 name2=value2 %}
The first argument is a pat... |
Returns an absolute URL matching given view with its parameters. | def url(parser, token):
"""
Returns an absolute URL matching given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url "path.to.some_view" arg1 arg2 %}
or
{% url "path.to.some_view" name1=value1 name2=value2 %}
... | [
"def",
"url",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one argument\"",
"\" (path to a view)\"",
"%",... | [
1344,
0
] | [
1431,
49
] | python | en | ['en', 'error', 'th'] | False |
verbatim | (parser, token) |
Stops the template engine from rendering the contents of this block tag.
Usage::
{% verbatim %}
{% don't process this %}
{% endverbatim %}
You can also designate a specific closing tag block (allowing the
unrendered use of ``{% endverbatim %}``)::
{% verbatim myb... |
Stops the template engine from rendering the contents of this block tag. | def verbatim(parser, token):
"""
Stops the template engine from rendering the contents of this block tag.
Usage::
{% verbatim %}
{% don't process this %}
{% endverbatim %}
You can also designate a specific closing tag block (allowing the
unrendered use of ``{% endverba... | [
"def",
"verbatim",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endverbatim'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"VerbatimNode",
"(",
"nodelist",
".",
"render",
"(",
"Co... | [
1435,
0
] | [
1454,
51
] | python | en | ['en', 'error', 'th'] | False |
widthratio | (parser, token) |
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}" />
If ``this_value`` is ... |
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant. | def widthratio(parser, token):
"""
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_w... | [
"def",
"widthratio",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"4",
":",
"tag",
",",
"this_value_expr",
",",
"max_value_expr",
",",
"max_width",
"=",
"bits",
"asva... | [
1458,
0
] | [
1492,
38
] | python | en | ['en', 'error', 'th'] | False |
do_with | (parser, token) |
Adds one or more values to the context (inside of this block) for caching
and easy access.
For example::
{% with total=person.some_sql_method %}
{{ total }} object{{ total|pluralize }}
{% endwith %}
Multiple values can be added to the context::
{% with foo=1 bar=... |
Adds one or more values to the context (inside of this block) for caching
and easy access. | def do_with(parser, token):
"""
Adds one or more values to the context (inside of this block) for caching
and easy access.
For example::
{% with total=person.some_sql_method %}
{{ total }} object{{ total|pluralize }}
{% endwith %}
Multiple values can be added to the co... | [
"def",
"do_with",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"remaining_bits",
"=",
"bits",
"[",
"1",
":",
"]",
"extra_context",
"=",
"token_kwargs",
"(",
"remaining_bits",
",",
"parser",
",",
"support_leg... | [
1496,
0
] | [
1527,
70
] | python | en | ['en', 'error', 'th'] | False |
DatabaseOperations.date_interval_sql | (self, sql, connector, timedelta) |
implements the interval functionality for expressions
format for Postgres:
(datefield + interval '3 days 200 seconds 5 microseconds')
|
implements the interval functionality for expressions
format for Postgres:
(datefield + interval '3 days 200 seconds 5 microseconds')
| def date_interval_sql(self, sql, connector, timedelta):
"""
implements the interval functionality for expressions
format for Postgres:
(datefield + interval '3 days 200 seconds 5 microseconds')
"""
modifiers = []
if timedelta.days:
modifiers.append... | [
"def",
"date_interval_sql",
"(",
"self",
",",
"sql",
",",
"connector",
",",
"timedelta",
")",
":",
"modifiers",
"=",
"[",
"]",
"if",
"timedelta",
".",
"days",
":",
"modifiers",
".",
"append",
"(",
"'%s days'",
"%",
"timedelta",
".",
"days",
")",
"if",
... | [
18,
4
] | [
33,
66
] | python | en | ['en', 'error', 'th'] | False |
DatabaseOperations.max_name_length | (self) |
Returns the maximum length of an identifier.
Note that the maximum length of an identifier is 63 by default, but can
be changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h .
This implementation simply returns 63, but can easi... |
Returns the maximum length of an identifier. | def max_name_length(self):
"""
Returns the maximum length of an identifier.
Note that the maximum length of an identifier is 63 by default, but can
be changed by recompiling PostgreSQL after editing the NAMEDATALEN
macro in src/include/pg_config_manual.h .
This implemen... | [
"def",
"max_name_length",
"(",
"self",
")",
":",
"return",
"63"
] | [
200,
4
] | [
212,
17
] | python | en | ['en', 'error', 'th'] | False |
iterate_with_exp_backoff | (
base_iter,
max_num_tries=6,
max_backoff=300.0,
start_backoff=4.0,
backoff_multiplier=2.0,
frac_random_backoff=0.25,
) | Iterate with exponential backoff on failures.
Useful to wrap results of datastore Query.fetch to avoid 429 error.
Args:
base_iter: basic iterator of generator object
max_num_tries: maximum number of tries for each request
max_backoff: maximum backoff, in seconds
start_backoff: initial ... | Iterate with exponential backoff on failures. | def iterate_with_exp_backoff(
base_iter,
max_num_tries=6,
max_backoff=300.0,
start_backoff=4.0,
backoff_multiplier=2.0,
frac_random_backoff=0.25,
):
"""Iterate with exponential backoff on failures.
Useful to wrap results of datastore Query.fetch to avoid 429 error.
Args:
base... | [
"def",
"iterate_with_exp_backoff",
"(",
"base_iter",
",",
"max_num_tries",
"=",
"6",
",",
"max_backoff",
"=",
"300.0",
",",
"start_backoff",
"=",
"4.0",
",",
"backoff_multiplier",
"=",
"2.0",
",",
"frac_random_backoff",
"=",
"0.25",
",",
")",
":",
"try_number",
... | [
167,
0
] | [
213,
27
] | python | en | ['en', 'en', 'en'] | True |
CompetitionStorageClient.__init__ | (self, project_id, bucket_name) | Initialize client with project id and name of the storage bucket. | Initialize client with project id and name of the storage bucket. | def __init__(self, project_id, bucket_name):
"""Initialize client with project id and name of the storage bucket."""
self.project_id = project_id
self.bucket_name = bucket_name
self.client = storage.Client(project=project_id)
self.bucket = self.client.get_bucket(bucket_name) | [
"def",
"__init__",
"(",
"self",
",",
"project_id",
",",
"bucket_name",
")",
":",
"self",
".",
"project_id",
"=",
"project_id",
"self",
".",
"bucket_name",
"=",
"bucket_name",
"self",
".",
"client",
"=",
"storage",
".",
"Client",
"(",
"project",
"=",
"proje... | [
36,
4
] | [
41,
57
] | python | en | ['en', 'en', 'en'] | True |
CompetitionStorageClient.list_blobs | (self, prefix="") | Lists names of all blobs by their prefix. | Lists names of all blobs by their prefix. | def list_blobs(self, prefix=""):
"""Lists names of all blobs by their prefix."""
return [b.name for b in self.bucket.list_blobs(prefix=prefix)] | [
"def",
"list_blobs",
"(",
"self",
",",
"prefix",
"=",
"\"\"",
")",
":",
"return",
"[",
"b",
".",
"name",
"for",
"b",
"in",
"self",
".",
"bucket",
".",
"list_blobs",
"(",
"prefix",
"=",
"prefix",
")",
"]"
] | [
43,
4
] | [
45,
70
] | python | en | ['en', 'en', 'en'] | True |
CompetitionStorageClient.get_blob | (self, blob_name) | Gets google.cloud.storage.blob.Blob object by blob name. | Gets google.cloud.storage.blob.Blob object by blob name. | def get_blob(self, blob_name):
"""Gets google.cloud.storage.blob.Blob object by blob name."""
return self.bucket.get_blob(blob_name) | [
"def",
"get_blob",
"(",
"self",
",",
"blob_name",
")",
":",
"return",
"self",
".",
"bucket",
".",
"get_blob",
"(",
"blob_name",
")"
] | [
47,
4
] | [
49,
46
] | python | en | ['en', 'en', 'en'] | True |
CompetitionStorageClient.new_blob | (self, blob_name) | Creates new storage blob with provided name. | Creates new storage blob with provided name. | def new_blob(self, blob_name):
"""Creates new storage blob with provided name."""
return storage.Blob(blob_name, self.bucket) | [
"def",
"new_blob",
"(",
"self",
",",
"blob_name",
")",
":",
"return",
"storage",
".",
"Blob",
"(",
"blob_name",
",",
"self",
".",
"bucket",
")"
] | [
51,
4
] | [
53,
51
] | python | en | ['en', 'en', 'en'] | True |
NoTransactionBatch.__init__ | (self, client) | Init NoTransactionBatch with provided CompetitionDatastoreClient. | Init NoTransactionBatch with provided CompetitionDatastoreClient. | def __init__(self, client):
"""Init NoTransactionBatch with provided CompetitionDatastoreClient."""
self._client = client
self._cur_batch = None
self._num_mutations = 0 | [
"def",
"__init__",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_cur_batch",
"=",
"None",
"self",
".",
"_num_mutations",
"=",
"0"
] | [
87,
4
] | [
91,
31
] | python | en | ['en', 'en', 'en'] | True |
NoTransactionBatch.begin | (self) | Begins a batch. | Begins a batch. | def begin(self):
"""Begins a batch."""
if self._cur_batch:
raise ValueError("Previous batch is not committed.")
self._cur_batch = self._client.batch()
self._cur_batch.begin()
self._num_mutations = 0 | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_batch",
":",
"raise",
"ValueError",
"(",
"\"Previous batch is not committed.\"",
")",
"self",
".",
"_cur_batch",
"=",
"self",
".",
"_client",
".",
"batch",
"(",
")",
"self",
".",
"_cur_batch",
... | [
93,
4
] | [
99,
31
] | python | en | ['en', 'lb', 'en'] | True |
NoTransactionBatch.commit | (self) | Commits all pending mutations. | Commits all pending mutations. | def commit(self):
"""Commits all pending mutations."""
self._cur_batch.commit()
self._cur_batch = None
self._num_mutations = 0 | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"_cur_batch",
".",
"commit",
"(",
")",
"self",
".",
"_cur_batch",
"=",
"None",
"self",
".",
"_num_mutations",
"=",
"0"
] | [
101,
4
] | [
105,
31
] | python | en | ['en', 'bg', 'en'] | True |
NoTransactionBatch.rollback | (self) | Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able to rollback... | Rolls back pending mutations. | def rollback(self):
"""Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer... | [
"def",
"rollback",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_cur_batch",
":",
"self",
".",
"_cur_batch",
".",
"rollback",
"(",
")",
"except",
"ValueError",
":",
"# ignore \"Batch must be in progress to rollback\" error",
"pass",
"self",
".",
"_cur_... | [
107,
4
] | [
122,
31
] | python | en | ['en', 'bg', 'en'] | True |
NoTransactionBatch.put | (self, entity) | Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore
| Adds mutation of the entity to the mutation buffer. | def put(self, entity):
"""Adds mutation of the entity to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
entity: entity which should be put into the datastore
"""
s... | [
"def",
"put",
"(",
"self",
",",
"entity",
")",
":",
"self",
".",
"_cur_batch",
".",
"put",
"(",
"entity",
")",
"self",
".",
"_num_mutations",
"+=",
"1",
"if",
"self",
".",
"_num_mutations",
">=",
"MAX_MUTATIONS_IN_BATCH",
":",
"self",
".",
"commit",
"(",... | [
124,
4
] | [
137,
24
] | python | en | ['en', 'en', 'en'] | True |
NoTransactionBatch.delete | (self, key) | Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
| Adds deletion of the entity with given key to the mutation buffer. | def delete(self, key):
"""Adds deletion of the entity with given key to the mutation buffer.
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it.
Args:
key: key of the entity which should be deleted
"""
... | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_cur_batch",
".",
"delete",
"(",
"key",
")",
"self",
".",
"_num_mutations",
"+=",
"1",
"if",
"self",
".",
"_num_mutations",
">=",
"MAX_MUTATIONS_IN_BATCH",
":",
"self",
".",
"commit",
"(",... | [
139,
4
] | [
152,
24
] | python | en | ['en', 'en', 'en'] | True |
CompetitionDatastoreClient.__init__ | (self, project_id, namespace=None) | Init this method with given project id and optional namespace. | Init this method with given project id and optional namespace. | def __init__(self, project_id, namespace=None):
"""Init this method with given project id and optional namespace."""
self._client = datastore.Client(project=project_id, namespace=namespace) | [
"def",
"__init__",
"(",
"self",
",",
"project_id",
",",
"namespace",
"=",
"None",
")",
":",
"self",
".",
"_client",
"=",
"datastore",
".",
"Client",
"(",
"project",
"=",
"project_id",
",",
"namespace",
"=",
"namespace",
")"
] | [
219,
4
] | [
221,
80
] | python | en | ['en', 'en', 'en'] | True |
CompetitionDatastoreClient.key | (self, *args, **kwargs) | Creates datastore key. | Creates datastore key. | def key(self, *args, **kwargs):
"""Creates datastore key."""
return self._client.key(*args, **kwargs) | [
"def",
"key",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_client",
".",
"key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
223,
4
] | [
225,
48
] | python | en | ['fr', 'et', 'en'] | False |
CompetitionDatastoreClient.entity | (self, key) | Creates datastore entity. | Creates datastore entity. | def entity(self, key):
"""Creates datastore entity."""
return datastore.Entity(key) | [
"def",
"entity",
"(",
"self",
",",
"key",
")",
":",
"return",
"datastore",
".",
"Entity",
"(",
"key",
")"
] | [
227,
4
] | [
229,
36
] | python | en | ['fr', 'la', 'en'] | False |
CompetitionDatastoreClient.no_transact_batch | (self) | Starts batch of mutation which is committed without transaction. | Starts batch of mutation which is committed without transaction. | def no_transact_batch(self):
"""Starts batch of mutation which is committed without transaction."""
return NoTransactionBatch(self._client) | [
"def",
"no_transact_batch",
"(",
"self",
")",
":",
"return",
"NoTransactionBatch",
"(",
"self",
".",
"_client",
")"
] | [
231,
4
] | [
233,
47
] | python | en | ['en', 'en', 'en'] | True |
CompetitionDatastoreClient.batch | (self) | Starts batch of mutations. | Starts batch of mutations. | def batch(self):
"""Starts batch of mutations."""
return self._client.batch() | [
"def",
"batch",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"batch",
"(",
")"
] | [
235,
4
] | [
237,
35
] | python | en | ['en', 'bg', 'en'] | True |
CompetitionDatastoreClient.transaction | (self) | Starts transaction. | Starts transaction. | def transaction(self):
"""Starts transaction."""
return self._client.transaction() | [
"def",
"transaction",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"transaction",
"(",
")"
] | [
239,
4
] | [
241,
41
] | python | en | ['en', 'jv', 'en'] | False |
CompetitionDatastoreClient.get | (self, key, transaction=None) | Retrieves an entity given its key. | Retrieves an entity given its key. | def get(self, key, transaction=None):
"""Retrieves an entity given its key."""
return self._client.get(key, transaction=transaction) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"transaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"key",
",",
"transaction",
"=",
"transaction",
")"
] | [
243,
4
] | [
245,
61
] | python | en | ['en', 'en', 'en'] | True |
CompetitionDatastoreClient.query_fetch | (self, **kwargs) | Queries datastore (using exponential backoff). | Queries datastore (using exponential backoff). | def query_fetch(self, **kwargs):
"""Queries datastore (using exponential backoff)."""
return iterate_with_exp_backoff(self._client.query(**kwargs).fetch()) | [
"def",
"query_fetch",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"iterate_with_exp_backoff",
"(",
"self",
".",
"_client",
".",
"query",
"(",
"*",
"*",
"kwargs",
")",
".",
"fetch",
"(",
")",
")"
] | [
247,
4
] | [
249,
77
] | python | en | ['en', 'en', 'en'] | True |
RequestException.__init__ | (self, *args, **kwargs) | Initialize RequestException with `request` and `response` objects. | Initialize RequestException with `request` and `response` objects. | def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"kwargs",
".",
"pop",
"(",
"'response'",
",",
"None",
")",
"self",
".",
"response",
"=",
"response",
"self",
".",
"request",
"=",
"kwargs",
".",
"... | [
16,
4
] | [
24,
63
] | python | en | ['en', 'en', 'en'] | True |
csrf | (request) |
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
|
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
| def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debu... | [
"def",
"csrf",
"(",
"request",
")",
":",
"def",
"_get_val",
"(",
")",
":",
"token",
"=",
"get_token",
"(",
"request",
")",
"if",
"token",
"is",
"None",
":",
"# In order to be able to provide debugging info in the",
"# case of misconfiguration, we use a sentinel value",
... | [
16,
0
] | [
31,
53
] | python | en | ['en', 'error', 'th'] | False |
debug | (request) |
Return context variables helpful for debugging.
|
Return context variables helpful for debugging.
| def debug(request):
"""
Return context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connections
# Return a lazy reference that comp... | [
"def",
"debug",
"(",
"request",
")",
":",
"context_extras",
"=",
"{",
"}",
"if",
"settings",
".",
"DEBUG",
"and",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
")",
"in",
"settings",
".",
"INTERNAL_IPS",
":",
"context_extras",
"[",
"'debug'",
... | [
34,
0
] | [
48,
25
] | python | en | ['en', 'error', 'th'] | False |
static | (request) |
Add static-related context variables to the context.
|
Add static-related context variables to the context.
| def static(request):
"""
Add static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL} | [
"def",
"static",
"(",
"request",
")",
":",
"return",
"{",
"'STATIC_URL'",
":",
"settings",
".",
"STATIC_URL",
"}"
] | [
65,
0
] | [
69,
46
] | python | en | ['en', 'error', 'th'] | False |
media | (request) |
Add media-related context variables to the context.
|
Add media-related context variables to the context.
| def media(request):
"""
Add media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL} | [
"def",
"media",
"(",
"request",
")",
":",
"return",
"{",
"'MEDIA_URL'",
":",
"settings",
".",
"MEDIA_URL",
"}"
] | [
72,
0
] | [
76,
44
] | python | en | ['en', 'error', 'th'] | False |
save | (filepath, obj) | Saves an object to the specified filepath using joblib.
joblib is like pickle but will save NumPy arrays as separate files for
greater efficiency.
:param filepath: str, path to save to
:obj filepath: object to save
| Saves an object to the specified filepath using joblib. | def save(filepath, obj):
"""Saves an object to the specified filepath using joblib.
joblib is like pickle but will save NumPy arrays as separate files for
greater efficiency.
:param filepath: str, path to save to
:obj filepath: object to save
"""
joblib.dump(obj, filepath) | [
"def",
"save",
"(",
"filepath",
",",
"obj",
")",
":",
"joblib",
".",
"dump",
"(",
"obj",
",",
"filepath",
")"
] | [
201,
0
] | [
211,
30
] | python | en | ['en', 'en', 'en'] | True |
load | (filepath) | Returns an object stored via `save` | Returns an object stored via `save` | def load(filepath):
"""Returns an object stored via `save`"""
obj = joblib.load(filepath)
return obj | [
"def",
"load",
"(",
"filepath",
")",
":",
"obj",
"=",
"joblib",
".",
"load",
"(",
"filepath",
")",
"return",
"obj"
] | [
214,
0
] | [
219,
14
] | python | en | ['en', 'en', 'en'] | True |
NoRefModel.get_vars | (self) |
Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model.
|
Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model.
| def get_vars(self):
"""
Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model.
"""
# Catch eager execution and assert function overload... | [
"def",
"get_vars",
"(",
"self",
")",
":",
"# Catch eager execution and assert function overload.",
"try",
":",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"For Eager execution - get_vars \"",
"\"must be overridden.\"",
")",
... | [
152,
4
] | [
198,
25
] | python | en | ['en', 'error', 'th'] | False |
Subversion.get_revision | (cls, location) |
Return the maximum revision for all files under a given location
|
Return the maximum revision for all files under a given location
| def get_revision(cls, location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if cls.dirname not in dirs:
dirs[... | [
"def",
"get_revision",
"(",
"cls",
",",
"location",
")",
":",
"# Note: taken from setuptools.command.egg_info",
"revision",
"=",
"0",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"location",
")",
":",
"if",
"cls",
".",
"dirname",
... | [
51,
4
] | [
76,
23
] | python | en | ['en', 'error', 'th'] | False |
Subversion.get_netloc_and_auth | (cls, netloc, scheme) |
This override allows the auth information to be passed to svn via the
--username and --password options instead of via the URL.
|
This override allows the auth information to be passed to svn via the
--username and --password options instead of via the URL.
| def get_netloc_and_auth(cls, netloc, scheme):
"""
This override allows the auth information to be passed to svn via the
--username and --password options instead of via the URL.
"""
if scheme == 'ssh':
# The --username and --password options can't be used for
... | [
"def",
"get_netloc_and_auth",
"(",
"cls",
",",
"netloc",
",",
"scheme",
")",
":",
"if",
"scheme",
"==",
"'ssh'",
":",
"# The --username and --password options can't be used for",
"# svn+ssh URLs, so keep the auth information in the URL.",
"return",
"super",
"(",
"Subversion",... | [
79,
4
] | [
89,
45
] | python | en | ['en', 'error', 'th'] | False |
Subversion.is_commit_id_equal | (cls, dest, name) | Always assume the versions don't match | Always assume the versions don't match | def is_commit_id_equal(cls, dest, name):
"""Always assume the versions don't match"""
return False | [
"def",
"is_commit_id_equal",
"(",
"cls",
",",
"dest",
",",
"name",
")",
":",
"return",
"False"
] | [
184,
4
] | [
186,
20
] | python | en | ['en', 'en', 'en'] | True |
Subversion.call_vcs_version | (self) | Query the version of the currently installed Subversion client.
:return: A tuple containing the parts of the version information or
``()`` if the version returned from ``svn`` could not be parsed.
:raises: BadCommand: If ``svn`` is not installed.
| Query the version of the currently installed Subversion client. | def call_vcs_version(self):
# type: () -> Tuple[int, ...]
"""Query the version of the currently installed Subversion client.
:return: A tuple containing the parts of the version information or
``()`` if the version returned from ``svn`` could not be parsed.
:raises: BadComma... | [
"def",
"call_vcs_version",
"(",
"self",
")",
":",
"# type: () -> Tuple[int, ...]",
"# Example versions:",
"# svn, version 1.10.3 (r1842928)",
"# compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0",
"# svn, version 1.7.14 (r1542130)",
"# compiled Mar 28 2018, 08:49:13 on ... | [
203,
4
] | [
228,
29
] | python | en | ['en', 'en', 'en'] | True |
Subversion.get_vcs_version | (self) | Return the version of the currently installed Subversion client.
If the version of the Subversion client has already been queried,
a cached value will be used.
:return: A tuple containing the parts of the version information or
``()`` if the version returned from ``svn`` could not ... | Return the version of the currently installed Subversion client. | def get_vcs_version(self):
# type: () -> Tuple[int, ...]
"""Return the version of the currently installed Subversion client.
If the version of the Subversion client has already been queried,
a cached value will be used.
:return: A tuple containing the parts of the version infor... | [
"def",
"get_vcs_version",
"(",
"self",
")",
":",
"# type: () -> Tuple[int, ...]",
"if",
"self",
".",
"_vcs_version",
"is",
"not",
"None",
":",
"# Use cached version, if available.",
"# If parsing the version failed previously (empty tuple),",
"# do not attempt to parse it again.",
... | [
230,
4
] | [
249,
26
] | python | en | ['en', 'en', 'en'] | True |
Subversion.get_remote_call_options | (self) | Return options to be used on calls to Subversion that contact the server.
These options are applicable for the following ``svn`` subcommands used
in this class.
- checkout
- export
- switch
- update
:return: A list of command line arguments to p... | Return options to be used on calls to Subversion that contact the server. | def get_remote_call_options(self):
# type: () -> CommandArgs
"""Return options to be used on calls to Subversion that contact the server.
These options are applicable for the following ``svn`` subcommands used
in this class.
- checkout
- export
- swi... | [
"def",
"get_remote_call_options",
"(",
"self",
")",
":",
"# type: () -> CommandArgs",
"if",
"not",
"self",
".",
"use_interactive",
":",
"# --non-interactive switch is available since Subversion 0.14.4.",
"# Subversion < 1.8 runs in interactive mode by default.",
"return",
"[",
"'--... | [
251,
4
] | [
282,
17
] | python | en | ['en', 'en', 'en'] | True |
Subversion.export | (self, location, url) | Export the svn repository at the url to the destination location | Export the svn repository at the url to the destination location | def export(self, location, url):
# type: (str, HiddenText) -> None
"""Export the svn repository at the url to the destination location"""
url, rev_options = self.get_url_rev_options(url)
logger.info('Exporting svn repository %s to %s', url, location)
with indent_log():
... | [
"def",
"export",
"(",
"self",
",",
"location",
",",
"url",
")",
":",
"# type: (str, HiddenText) -> None",
"url",
",",
"rev_options",
"=",
"self",
".",
"get_url_rev_options",
"(",
"url",
")",
"logger",
".",
"info",
"(",
"'Exporting svn repository %s to %s'",
",",
... | [
284,
4
] | [
299,
57
] | python | en | ['en', 'en', 'en'] | True |
detect | (byte_str) |
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
|
Detect the encoding of the given byte string. | def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expecte... | [
"def",
"detect",
"(",
"byte_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytearray",
")",
":",
"if",
"not",
"isinstance",
"(",
"byte_str",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'Expected object of type bytes or bytearray, got: ... | [
23,
0
] | [
38,
27
] | python | en | ['en', 'error', 'th'] | False |
register.check_metadata | (self) | Deprecated API. | Deprecated API. | def check_metadata(self):
"""Deprecated API."""
warn("distutils.command.register.check_metadata is deprecated, \
use the check command instead", PendingDeprecationWarning)
check = self.distribution.get_command_obj('check')
check.ensure_finalized()
check.strict = sel... | [
"def",
"check_metadata",
"(",
"self",
")",
":",
"warn",
"(",
"\"distutils.command.register.check_metadata is deprecated, \\\n use the check command instead\"",
",",
"PendingDeprecationWarning",
")",
"check",
"=",
"self",
".",
"distribution",
".",
"get_command_obj",
... | [
57,
4
] | [
65,
19
] | python | en | ['en', 'pt', 'en'] | False |
register._set_config | (self) | Reads the configuration file and set attributes.
| Reads the configuration file and set attributes.
| def _set_config(self):
''' Reads the configuration file and set attributes.
'''
config = self._read_pypirc()
if config != {}:
self.username = config['username']
self.password = config['password']
self.repository = config['repository']
self.... | [
"def",
"_set_config",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_read_pypirc",
"(",
")",
"if",
"config",
"!=",
"{",
"}",
":",
"self",
".",
"username",
"=",
"config",
"[",
"'username'",
"]",
"self",
".",
"password",
"=",
"config",
"[",
"'pas... | [
67,
4
] | [
82,
35
] | python | en | ['en', 'en', 'en'] | True |
register.classifiers | (self) | Fetch the list of classifiers from the server.
| Fetch the list of classifiers from the server.
| def classifiers(self):
''' Fetch the list of classifiers from the server.
'''
url = self.repository+'?:action=list_classifiers'
response = urllib.request.urlopen(url)
log.info(self._read_pypi_response(response)) | [
"def",
"classifiers",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"repository",
"+",
"'?:action=list_classifiers'",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"log",
".",
"info",
"(",
"self",
".",
"_read_pypi_response",
... | [
84,
4
] | [
89,
52
] | python | en | ['en', 'en', 'en'] | True |
register.verify_metadata | (self) | Send the metadata to the package index server to be checked.
| Send the metadata to the package index server to be checked.
| def verify_metadata(self):
''' Send the metadata to the package index server to be checked.
'''
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
log.info('Server response (%s): %s', code, result) | [
"def",
"verify_metadata",
"(",
"self",
")",
":",
"# send the info to the server and report the result",
"(",
"code",
",",
"result",
")",
"=",
"self",
".",
"post_to_server",
"(",
"self",
".",
"build_post_data",
"(",
"'verify'",
")",
")",
"log",
".",
"info",
"(",
... | [
91,
4
] | [
96,
58
] | python | en | ['en', 'en', 'en'] | True |
register.send_metadata | (self) | Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is a ConfigParser-formatted file with a... | Send the metadata to the package index server. | def send_metadata(self):
''' Send the metadata to the package index server.
Well, do the following:
1. figure who the user is, and then
2. send the data as a Basic auth'ed POST.
First we try to read the username/password from $HOME/.pypirc,
which is ... | [
"def",
"send_metadata",
"(",
"self",
")",
":",
"# see if we can short-cut and get the username/password from the",
"# config",
"if",
"self",
".",
"has_config",
":",
"choice",
"=",
"'1'",
"username",
"=",
"self",
".",
"username",
"password",
"=",
"self",
".",
"passwo... | [
98,
4
] | [
218,
62
] | python | en | ['en', 'en', 'en'] | True |
register.post_to_server | (self, data, auth=None) | Post a query to the server, and return a string response.
| Post a query to the server, and return a string response.
| def post_to_server(self, data, auth=None):
''' Post a query to the server, and return a string response.
'''
if 'name' in data:
self.announce('Registering %s to %s' % (data['name'],
self.repository),
... | [
"def",
"post_to_server",
"(",
"self",
",",
"data",
",",
"auth",
"=",
"None",
")",
":",
"if",
"'name'",
"in",
"data",
":",
"self",
".",
"announce",
"(",
"'Registering %s to %s'",
"%",
"(",
"data",
"[",
"'name'",
"]",
",",
"self",
".",
"repository",
")",... | [
248,
4
] | [
303,
21
] | python | en | ['en', 'en', 'en'] | True |
set_cookie_data | (storage, messages, invalid=False, encode_empty=False) |
Sets ``request.COOKIES`` with the encoded data and removes the storage
backend's loaded data cache.
|
Sets ``request.COOKIES`` with the encoded data and removes the storage
backend's loaded data cache.
| def set_cookie_data(storage, messages, invalid=False, encode_empty=False):
"""
Sets ``request.COOKIES`` with the encoded data and removes the storage
backend's loaded data cache.
"""
encoded_data = storage._encode(messages, encode_empty=encode_empty)
if invalid:
# Truncate the first char... | [
"def",
"set_cookie_data",
"(",
"storage",
",",
"messages",
",",
"invalid",
"=",
"False",
",",
"encode_empty",
"=",
"False",
")",
":",
"encoded_data",
"=",
"storage",
".",
"_encode",
"(",
"messages",
",",
"encode_empty",
"=",
"encode_empty",
")",
"if",
"inval... | [
11,
0
] | [
22,
32
] | python | en | ['en', 'error', 'th'] | False |
stored_cookie_messages_count | (storage, response) |
Returns an integer containing the number of messages stored.
|
Returns an integer containing the number of messages stored.
| def stored_cookie_messages_count(storage, response):
"""
Returns an integer containing the number of messages stored.
"""
# Get a list of cookies, excluding ones with a max-age of 0 (because
# they have been marked for deletion).
cookie = response.cookies.get(storage.cookie_name)
if not cook... | [
"def",
"stored_cookie_messages_count",
"(",
"storage",
",",
"response",
")",
":",
"# Get a list of cookies, excluding ones with a max-age of 0 (because",
"# they have been marked for deletion).",
"cookie",
"=",
"response",
".",
"cookies",
".",
"get",
"(",
"storage",
".",
"coo... | [
25,
0
] | [
39,
20
] | python | en | ['en', 'error', 'th'] | False |
load_images | (input_dir, batch_shape) | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case o... | Read png images from input directory in batches. | def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this li... | [
"def",
"load_images",
"(",
"input_dir",
",",
"batch_shape",
")",
":",
"images",
"=",
"np",
".",
"zeros",
"(",
"batch_shape",
")",
"filenames",
"=",
"[",
"]",
"idx",
"=",
"0",
"batch_size",
"=",
"batch_shape",
"[",
"0",
"]",
"for",
"filepath",
"in",
"tf... | [
32,
0
] | [
60,
31
] | python | en | ['en', 'en', 'en'] | True |
save_images | (images, filenames, output_dir) | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory ... | Saves images to the output directory. | def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filena... | [
"def",
"save_images",
"(",
"images",
",",
"filenames",
",",
"output_dir",
")",
":",
"for",
"i",
",",
"filename",
"in",
"enumerate",
"(",
"filenames",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output... | [
63,
0
] | [
75,
55
] | python | en | ['en', 'en', 'en'] | True |
main | (_) | Run the sample attack | Run the sample attack | def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir) | [
"def",
"main",
"(",
"_",
")",
":",
"batch_shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
",",
"FLAGS",
".",
"image_height",
",",
"FLAGS",
".",
"image_width",
",",
"3",
"]",
"for",
"filenames",
",",
"images",
"in",
"load_images",
"(",
"FLAGS",
".",
"inpu... | [
78,
0
] | [
82,
56
] | python | en | ['en', 'it', 'en'] | True |
with_cleanup | (func) | Decorator for common logic related to managing temporary
directories.
| Decorator for common logic related to managing temporary
directories.
| def with_cleanup(func):
# type: (Any) -> Any
"""Decorator for common logic related to managing temporary
directories.
"""
def configure_tempdir_registry(registry):
# type: (TempDirectoryTypeRegistry) -> None
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)
... | [
"def",
"with_cleanup",
"(",
"func",
")",
":",
"# type: (Any) -> Any",
"def",
"configure_tempdir_registry",
"(",
"registry",
")",
":",
"# type: (TempDirectoryTypeRegistry) -> None",
"for",
"t",
"in",
"KEEPABLE_TEMPDIR_TYPES",
":",
"registry",
".",
"set_delete",
"(",
"t",... | [
167,
0
] | [
192,
18
] | python | en | ['en', 'en', 'en'] | True |
SessionCommandMixin._get_index_urls | (cls, options) | Return a list of index urls from user-provided options. | Return a list of index urls from user-provided options. | def _get_index_urls(cls, options):
# type: (Values) -> Optional[List[str]]
"""Return a list of index urls from user-provided options."""
index_urls = []
if not getattr(options, "no_index", False):
url = getattr(options, "index_url", None)
if url:
i... | [
"def",
"_get_index_urls",
"(",
"cls",
",",
"options",
")",
":",
"# type: (Values) -> Optional[List[str]]",
"index_urls",
"=",
"[",
"]",
"if",
"not",
"getattr",
"(",
"options",
",",
"\"no_index\"",
",",
"False",
")",
":",
"url",
"=",
"getattr",
"(",
"options",
... | [
64,
4
] | [
76,
33
] | python | en | ['en', 'en', 'en'] | True |
SessionCommandMixin.get_default_session | (self, options) | Get a default-managed session. | Get a default-managed session. | def get_default_session(self, options):
# type: (Values) -> PipSession
"""Get a default-managed session."""
if self._session is None:
self._session = self.enter_context(self._build_session(options))
# there's no type annotation on requests.Session, so it's
# a... | [
"def",
"get_default_session",
"(",
"self",
",",
"options",
")",
":",
"# type: (Values) -> PipSession",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"self",
".",
"enter_context",
"(",
"self",
".",
"_build_session",
"(",
"optio... | [
78,
4
] | [
87,
28
] | python | en | ['en', 'da', 'en'] | True |
IndexGroupCommand.handle_pip_version_check | (self, options) |
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
|
Do the pip version check if not disabled. | def handle_pip_version_check(self, options):
# type: (Values) -> None
"""
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
"""
# Make sure the index_group options are present.
assert hasattr(options, 'no_index'... | [
"def",
"handle_pip_version_check",
"(",
"self",
",",
"options",
")",
":",
"# type: (Values) -> None",
"# Make sure the index_group options are present.",
"assert",
"hasattr",
"(",
"options",
",",
"'no_index'",
")",
"if",
"options",
".",
"disable_pip_version_check",
"or",
... | [
137,
4
] | [
157,
52
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.make_requirement_preparer | (
temp_build_dir, # type: TempDirectory
options, # type: Values
req_tracker, # type: RequirementTracker
session, # type: PipSession
finder, # type: PackageFinder
use_user_site, # type: b... |
Create a RequirementPreparer instance for the given parameters.
|
Create a RequirementPreparer instance for the given parameters.
| def make_requirement_preparer(
temp_build_dir, # type: TempDirectory
options, # type: Values
req_tracker, # type: RequirementTracker
session, # type: PipSession
finder, # type: PackageFinder
use_us... | [
"def",
"make_requirement_preparer",
"(",
"temp_build_dir",
",",
"# type: TempDirectory",
"options",
",",
"# type: Values",
"req_tracker",
",",
"# type: RequirementTracker",
"session",
",",
"# type: PipSession",
"finder",
",",
"# type: PackageFinder",
"use_user_site",
",",
"# ... | [
204,
4
] | [
234,
9
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.make_resolver | (
preparer, # type: RequirementPreparer
finder, # type: PackageFinder
options, # type: Values
wheel_cache=None, # type: Optional[WheelCache]
use_user_site=False, ... |
Create a Resolver instance for the given parameters.
|
Create a Resolver instance for the given parameters.
| def make_resolver(
preparer, # type: RequirementPreparer
finder, # type: PackageFinder
options, # type: Values
wheel_cache=None, # type: Optional[WheelCache]
use_user_site=False... | [
"def",
"make_resolver",
"(",
"preparer",
",",
"# type: RequirementPreparer",
"finder",
",",
"# type: PackageFinder",
"options",
",",
"# type: Values",
"wheel_cache",
"=",
"None",
",",
"# type: Optional[WheelCache]",
"use_user_site",
"=",
"False",
",",
"# type: bool",
"ign... | [
237,
4
] | [
290,
9
] | python | en | ['en', 'error', 'th'] | False |
RequirementCommand.get_requirements | (
self,
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, # type: PipSession
check_supported_wheels=True, # type: bool
) |
Parse command-line arguments into the corresponding requirements.
|
Parse command-line arguments into the corresponding requirements.
| def get_requirements(
self,
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, # type: PipSession
check_supported_wheels=True, # type: bool
):
# type: (...) -> List[InstallRequirement... | [
"def",
"get_requirements",
"(",
"self",
",",
"args",
",",
"# type: List[str]",
"options",
",",
"# type: Values",
"finder",
",",
"# type: PackageFinder",
"session",
",",
"# type: PipSession",
"check_supported_wheels",
"=",
"True",
",",
"# type: bool",
")",
":",
"# type... | [
292,
4
] | [
366,
27
] | 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.