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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
format_html | (format_string, *args, **kwargs) |
Similar to str.format, but pass all arguments through conditional_escape(),
and call mark_safe() on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
|
Similar to str.format, but pass all arguments through conditional_escape(),
and call mark_safe() on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
| def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but pass all arguments through conditional_escape(),
and call mark_safe() on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditi... | [
"def",
"format_html",
"(",
"format_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args_safe",
"=",
"map",
"(",
"conditional_escape",
",",
"args",
")",
"kwargs_safe",
"=",
"{",
"k",
":",
"conditional_escape",
"(",
"v",
")",
"for",
"(",
"... | [
103,
0
] | [
111,
69
] | python | en | ['en', 'error', 'th'] | False |
format_html_join | (sep, format_string, args_generator) |
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape.
'args_generator' should be an iterator that returns the sequence of 'args'
that will be passed... |
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape. | def format_html_join(sep, format_string, args_generator):
"""
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape.
'args_generator' should be an ite... | [
"def",
"format_html_join",
"(",
"sep",
",",
"format_string",
",",
"args_generator",
")",
":",
"return",
"mark_safe",
"(",
"conditional_escape",
"(",
"sep",
")",
".",
"join",
"(",
"format_html",
"(",
"format_string",
",",
"*",
"args",
")",
"for",
"args",
"in"... | [
114,
0
] | [
131,
6
] | python | en | ['en', 'error', 'th'] | False |
linebreaks | (value, autoescape=False) | Convert newlines into <p> and <br>s. | Convert newlines into <p> and <br>s. | def linebreaks(value, autoescape=False):
"""Convert newlines into <p> and <br>s."""
value = normalize_newlines(value)
paras = re.split('\n{2,}', str(value))
if autoescape:
paras = ['<p>%s</p>' % escape(p).replace('\n', '<br>') for p in paras]
else:
paras = ['<p>%s</p>' % p.replace('\... | [
"def",
"linebreaks",
"(",
"value",
",",
"autoescape",
"=",
"False",
")",
":",
"value",
"=",
"normalize_newlines",
"(",
"value",
")",
"paras",
"=",
"re",
".",
"split",
"(",
"'\\n{2,}'",
",",
"str",
"(",
"value",
")",
")",
"if",
"autoescape",
":",
"paras... | [
135,
0
] | [
143,
29
] | python | en | ['en', 'en', 'en'] | True |
_strip_once | (value) |
Internal tag stripping utility used by strip_tags.
|
Internal tag stripping utility used by strip_tags.
| def _strip_once(value):
"""
Internal tag stripping utility used by strip_tags.
"""
s = MLStripper()
s.feed(value)
s.close()
return s.get_data() | [
"def",
"_strip_once",
"(",
"value",
")",
":",
"s",
"=",
"MLStripper",
"(",
")",
"s",
".",
"feed",
"(",
"value",
")",
"s",
".",
"close",
"(",
")",
"return",
"s",
".",
"get_data",
"(",
")"
] | [
165,
0
] | [
172,
23
] | python | en | ['en', 'error', 'th'] | False |
strip_tags | (value) | Return the given HTML with all tags stripped. | Return the given HTML with all tags stripped. | def strip_tags(value):
"""Return the given HTML with all tags stripped."""
# Note: in typical case this loop executes _strip_once once. Loop condition
# is redundant, but helps to reduce number of executions of _strip_once.
value = str(value)
while '<' in value and '>' in value:
new_value = ... | [
"def",
"strip_tags",
"(",
"value",
")",
":",
"# Note: in typical case this loop executes _strip_once once. Loop condition",
"# is redundant, but helps to reduce number of executions of _strip_once.",
"value",
"=",
"str",
"(",
"value",
")",
"while",
"'<'",
"in",
"value",
"and",
... | [
176,
0
] | [
187,
16
] | python | en | ['en', 'en', 'en'] | True |
strip_spaces_between_tags | (value) | Return the given HTML with spaces between tags removed. | Return the given HTML with spaces between tags removed. | def strip_spaces_between_tags(value):
"""Return the given HTML with spaces between tags removed."""
return re.sub(r'>\s+<', '><', str(value)) | [
"def",
"strip_spaces_between_tags",
"(",
"value",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'>\\s+<'",
",",
"'><'",
",",
"str",
"(",
"value",
")",
")"
] | [
191,
0
] | [
193,
45
] | python | en | ['en', 'en', 'en'] | True |
smart_urlquote | (url) | Quote a URL if it isn't already quoted. | Quote a URL if it isn't already quoted. | def smart_urlquote(url):
"""Quote a URL if it isn't already quoted."""
def unquote_quote(segment):
segment = unquote(segment)
# Tilde is part of RFC3986 Unreserved Characters
# https://tools.ietf.org/html/rfc3986#section-2.3
# See also https://bugs.python.org/issue16285
r... | [
"def",
"smart_urlquote",
"(",
"url",
")",
":",
"def",
"unquote_quote",
"(",
"segment",
")",
":",
"segment",
"=",
"unquote",
"(",
"segment",
")",
"# Tilde is part of RFC3986 Unreserved Characters",
"# https://tools.ietf.org/html/rfc3986#section-2.3",
"# See also https://bugs.p... | [
196,
0
] | [
228,
62
] | python | en | ['en', 'en', 'en'] | True |
urlize | (text, trim_url_limit=None, nofollow=False, autoescape=False) |
Convert any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing punctuation (periods, commas, close-parens) and
leading punctuation (opening pa... |
Convert any URLs in text into clickable links. | def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
"""
Convert any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing pun... | [
"def",
"urlize",
"(",
"text",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"autoescape",
"=",
"False",
")",
":",
"safe_input",
"=",
"isinstance",
"(",
"text",
",",
"SafeData",
")",
"def",
"trim_url",
"(",
"x",
",",
"limit",
"... | [
232,
0
] | [
345,
25
] | python | en | ['en', 'error', 'th'] | False |
avoid_wrapping | (value) |
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
|
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
| def avoid_wrapping(value):
"""
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
"""
return value.replace(" ", "\xa0") | [
"def",
"avoid_wrapping",
"(",
"value",
")",
":",
"return",
"value",
".",
"replace",
"(",
"\" \"",
",",
"\"\\xa0\"",
")"
] | [
348,
0
] | [
353,
37
] | python | en | ['en', 'error', 'th'] | False |
html_safe | (klass) |
A decorator that defines the __html__ method. This helps non-Django
templates to detect classes whose __str__ methods return SafeString.
|
A decorator that defines the __html__ method. This helps non-Django
templates to detect classes whose __str__ methods return SafeString.
| def html_safe(klass):
"""
A decorator that defines the __html__ method. This helps non-Django
templates to detect classes whose __str__ methods return SafeString.
"""
if '__html__' in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it defines "
... | [
"def",
"html_safe",
"(",
"klass",
")",
":",
"if",
"'__html__'",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"can't apply @html_safe to %s because it defines \"",
"\"__html__().\"",
"%",
"klass",
".",
"__name__",
")",
"if",
"'__str__'",
"not",
... | [
356,
0
] | [
374,
16
] | python | en | ['en', 'error', 'th'] | False |
eval_in_new_process | (
neuropod_path,
input_data,
binary_path=sys.executable,
extra_args=[],
neuropod_load_args={},
**kwargs
) |
Loads and runs a neuropod model in a separate process with specified input data.
Raises a CalledProcessError if there was an error evaluating the neuropod
:param neuropod_path The path to the neuropod to load
:param input_data A pickleable dict containing sample input to the model
... |
Loads and runs a neuropod model in a separate process with specified input data. | def eval_in_new_process(
neuropod_path,
input_data,
binary_path=sys.executable,
extra_args=[],
neuropod_load_args={},
**kwargs
):
"""
Loads and runs a neuropod model in a separate process with specified input data.
Raises a CalledProcessError if there was an error evaluating the neu... | [
"def",
"eval_in_new_process",
"(",
"neuropod_path",
",",
"input_data",
",",
"binary_path",
"=",
"sys",
".",
"executable",
",",
"extra_args",
"=",
"[",
"]",
",",
"neuropod_load_args",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"TemporaryDirecto... | [
22,
0
] | [
71,
42
] | python | en | ['en', 'error', 'th'] | False |
create_features | (input_tf, sample_rate_tf, mask_freq) |
Return:
A tensor of features with size (batch_size, max_time_steps, 80)
|
Return:
A tensor of features with size (batch_size, max_time_steps, 80)
| def create_features(input_tf, sample_rate_tf, mask_freq):
"""
Return:
A tensor of features with size (batch_size, max_time_steps, 80)
"""
features_list = []
# unstact the features with placeholder
input_unpack = tf.unstack(input_tf, axis=0)
for i in range(len(input_unpack)):
... | [
"def",
"create_features",
"(",
"input_tf",
",",
"sample_rate_tf",
",",
"mask_freq",
")",
":",
"features_list",
"=",
"[",
"]",
"# unstact the features with placeholder",
"input_unpack",
"=",
"tf",
".",
"unstack",
"(",
"input_tf",
",",
"axis",
"=",
"0",
")",
"for"... | [
33,
0
] | [
49,
22
] | python | en | ['en', 'error', 'th'] | False |
create_speech_rir | (audios, rir, lengths_audios, max_len, batch_size) |
Returns:
A tensor of speech with reverberations (Convolve the audio with the rir)
|
Returns:
A tensor of speech with reverberations (Convolve the audio with the rir)
| def create_speech_rir(audios, rir, lengths_audios, max_len, batch_size):
"""
Returns:
A tensor of speech with reverberations (Convolve the audio with the rir)
"""
speech_rir = []
for i in range(batch_size):
s1 = lengths_audios[i]
s2 = tf.convert_to_tensor(tf.shape(rir))
... | [
"def",
"create_speech_rir",
"(",
"audios",
",",
"rir",
",",
"lengths_audios",
",",
"max_len",
",",
"batch_size",
")",
":",
"speech_rir",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"batch_size",
")",
":",
"s1",
"=",
"lengths_audios",
"[",
"i",
"]",
... | [
76,
0
] | [
114,
22
] | python | en | ['en', 'error', 'th'] | False |
load_and_test_neuropod | (
neuropod_path,
test_input_data,
test_expected_out=None,
neuropod_load_args={},
**kwargs
) |
Loads a neuropod in a new process and verifies that inference runs.
If expected output is specified, the output of the model is checked against
the expected values.
Raises a ValueError if the outputs don't match the expected values
|
Loads a neuropod in a new process and verifies that inference runs.
If expected output is specified, the output of the model is checked against
the expected values. | def load_and_test_neuropod(
neuropod_path,
test_input_data,
test_expected_out=None,
neuropod_load_args={},
**kwargs
):
"""
Loads a neuropod in a new process and verifies that inference runs.
If expected output is specified, the output of the model is checked against
the expected valu... | [
"def",
"load_and_test_neuropod",
"(",
"neuropod_path",
",",
"test_input_data",
",",
"test_expected_out",
"=",
"None",
",",
"neuropod_load_args",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"RUN_NATIVE_TESTS",
":",
"# Load the model using native out-of-proc... | [
64,
0
] | [
97,
61
] | python | en | ['en', 'error', 'th'] | False |
save_test_data | (neuropod_path, test_input_data, test_expected_out) |
Saves the model's test data to a pickle file in the neuropod's data directory
:param neuropod_path: the path of the neuropod model
:param test_input_data: a dictionary of expected input feature values
:param test_expected_out: a dictionary of expected output feature values
:return: None
|
Saves the model's test data to a pickle file in the neuropod's data directory | def save_test_data(neuropod_path, test_input_data, test_expected_out):
"""
Saves the model's test data to a pickle file in the neuropod's data directory
:param neuropod_path: the path of the neuropod model
:param test_input_data: a dictionary of expected input feature values
:param test_expected_ou... | [
"def",
"save_test_data",
"(",
"neuropod_path",
",",
"test_input_data",
",",
"test_expected_out",
")",
":",
"test_data",
"=",
"{",
"\"test_input\"",
":",
"test_input_data",
",",
"\"test_output\"",
":",
"test_expected_out",
"}",
"with",
"open",
"(",
"os",
".",
"path... | [
100,
0
] | [
111,
46
] | python | en | ['en', 'error', 'th'] | False |
load_test_data | (neuropod_path) |
Loads test data from the data directory
:param neuropod_path: the path of the neuropod model
:return: dict or None
|
Loads test data from the data directory | def load_test_data(neuropod_path):
"""
Loads test data from the data directory
:param neuropod_path: the path of the neuropod model
:return: dict or None
"""
try:
with open(
os.path.join(neuropod_path, TEST_DATA_FILENAME), "rb"
) as test_data_file:
return... | [
"def",
"load_test_data",
"(",
"neuropod_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"neuropod_path",
",",
"TEST_DATA_FILENAME",
")",
",",
"\"rb\"",
")",
"as",
"test_data_file",
":",
"return",
"pickle",
".",
"load"... | [
114,
0
] | [
128,
19
] | python | en | ['en', 'error', 'th'] | False |
get_keyring_auth | (url, username) | Return the tuple auth for a given url from keyring. | Return the tuple auth for a given url from keyring. | def get_keyring_auth(url, username):
"""Return the tuple auth for a given url from keyring."""
if not url or not keyring:
return None
try:
try:
get_credential = keyring.get_credential
except AttributeError:
pass
else:
logger.debug("Getting... | [
"def",
"get_keyring_auth",
"(",
"url",
",",
"username",
")",
":",
"if",
"not",
"url",
"or",
"not",
"keyring",
":",
"return",
"None",
"try",
":",
"try",
":",
"get_credential",
"=",
"keyring",
".",
"get_credential",
"except",
"AttributeError",
":",
"pass",
"... | [
45,
0
] | [
71,
9
] | python | en | ['en', 'en', 'en'] | True |
MultiDomainBasicAuth._get_index_url | (self, url) | Return the original index URL matching the requested URL.
Cached or dynamically generated credentials may work against
the original index URL rather than just the netloc.
The provided url should have had its username and password
removed already. If the original index url had credentia... | Return the original index URL matching the requested URL. | def _get_index_url(self, url):
"""Return the original index URL matching the requested URL.
Cached or dynamically generated credentials may work against
the original index URL rather than just the netloc.
The provided url should have had its username and password
removed alread... | [
"def",
"_get_index_url",
"(",
"self",
",",
"url",
")",
":",
"if",
"not",
"url",
"or",
"not",
"self",
".",
"index_urls",
":",
"return",
"None",
"for",
"u",
"in",
"self",
".",
"index_urls",
":",
"prefix",
"=",
"remove_auth_from_url",
"(",
"u",
")",
".",
... | [
88,
4
] | [
107,
24
] | python | en | ['en', 'en', 'en'] | True |
MultiDomainBasicAuth._get_new_credentials | (self, original_url, allow_netrc=True,
allow_keyring=True) | Find and return credentials for the specified URL. | Find and return credentials for the specified URL. | def _get_new_credentials(self, original_url, allow_netrc=True,
allow_keyring=True):
"""Find and return credentials for the specified URL."""
# Split the credentials and netloc from the url.
url, netloc, url_user_password = split_auth_netloc_from_url(
orig... | [
"def",
"_get_new_credentials",
"(",
"self",
",",
"original_url",
",",
"allow_netrc",
"=",
"True",
",",
"allow_keyring",
"=",
"True",
")",
":",
"# Split the credentials and netloc from the url.",
"url",
",",
"netloc",
",",
"url_user_password",
"=",
"split_auth_netloc_fro... | [
109,
4
] | [
157,
33
] | python | en | ['en', 'en', 'en'] | True |
MultiDomainBasicAuth._get_url_and_credentials | (self, original_url) | Return the credentials to use for the provided URL.
If allowed, netrc and keyring may be used to obtain the
correct credentials.
Returns (url_without_credentials, username, password). Note
that even if the original URL contains credentials, this
function may return a different ... | Return the credentials to use for the provided URL. | def _get_url_and_credentials(self, original_url):
"""Return the credentials to use for the provided URL.
If allowed, netrc and keyring may be used to obtain the
correct credentials.
Returns (url_without_credentials, username, password). Note
that even if the original URL contai... | [
"def",
"_get_url_and_credentials",
"(",
"self",
",",
"original_url",
")",
":",
"url",
",",
"netloc",
",",
"_",
"=",
"split_auth_netloc_from_url",
"(",
"original_url",
")",
"# Use any stored credentials that we have for this netloc",
"username",
",",
"password",
"=",
"se... | [
159,
4
] | [
197,
38
] | python | en | ['en', 'en', 'en'] | True |
MultiDomainBasicAuth.warn_on_401 | (self, resp, **kwargs) | Response callback to warn about incorrect credentials. | Response callback to warn about incorrect credentials. | def warn_on_401(self, resp, **kwargs):
"""Response callback to warn about incorrect credentials."""
if resp.status_code == 401:
logger.warning(
'401 Error, Credentials not correct for %s', resp.request.url,
) | [
"def",
"warn_on_401",
"(",
"self",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"resp",
".",
"status_code",
"==",
"401",
":",
"logger",
".",
"warning",
"(",
"'401 Error, Credentials not correct for %s'",
",",
"resp",
".",
"request",
".",
"url",
",... | [
277,
4
] | [
282,
13
] | python | en | ['en', 'en', 'en'] | True |
MultiDomainBasicAuth.save_credentials | (self, resp, **kwargs) | Response callback to save credentials on success. | Response callback to save credentials on success. | def save_credentials(self, resp, **kwargs):
"""Response callback to save credentials on success."""
assert keyring is not None, "should never reach here without keyring"
if not keyring:
return
creds = self._credentials_to_save
self._credentials_to_save = None
... | [
"def",
"save_credentials",
"(",
"self",
",",
"resp",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"keyring",
"is",
"not",
"None",
",",
"\"should never reach here without keyring\"",
"if",
"not",
"keyring",
":",
"return",
"creds",
"=",
"self",
".",
"_credential... | [
284,
4
] | [
297,
62
] | python | en | ['en', 'en', 'en'] | True |
FormsFormsetTestCase.make_choiceformset | (self, formset_data=None, formset_class=ChoiceFormSet,
total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs) |
Make a ChoiceFormset from the given formset_data.
The data should be given as a list of (choice, votes) tuples.
|
Make a ChoiceFormset from the given formset_data.
The data should be given as a list of (choice, votes) tuples.
| def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet,
total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
"""
Make a ChoiceFormset from the given formset_data.
The data should be given as a list of (choice, votes) tuples.
"""... | [
"def",
"make_choiceformset",
"(",
"self",
",",
"formset_data",
"=",
"None",
",",
"formset_class",
"=",
"ChoiceFormSet",
",",
"total_forms",
"=",
"None",
",",
"initial_forms",
"=",
"0",
",",
"max_num_forms",
"=",
"0",
",",
"min_num_forms",
"=",
"0",
",",
"*",... | [
58,
4
] | [
87,
44
] | python | en | ['en', 'error', 'th'] | False |
FormsFormsetTestCase.test_formset_nonzero | (self) |
Formsets with no forms should still evaluate as true.
Regression test for #15722
|
Formsets with no forms should still evaluate as true.
Regression test for #15722
| def test_formset_nonzero(self):
"""
Formsets with no forms should still evaluate as true.
Regression test for #15722
"""
ChoiceFormset = formset_factory(Choice, extra=0)
formset = ChoiceFormset()
self.assertEqual(len(formset.forms), 0)
self.assertTrue(form... | [
"def",
"test_formset_nonzero",
"(",
"self",
")",
":",
"ChoiceFormset",
"=",
"formset_factory",
"(",
"Choice",
",",
"extra",
"=",
"0",
")",
"formset",
"=",
"ChoiceFormset",
"(",
")",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"formset",
".",
"forms",
")",... | [
912,
4
] | [
920,
32
] | python | en | ['en', 'error', 'th'] | False |
FormsFormsetTestCase.test_formset_splitdatetimefield | (self) |
Formset should also work with SplitDateTimeField(initial=datetime.datetime.now).
Regression test for #18709.
|
Formset should also work with SplitDateTimeField(initial=datetime.datetime.now).
Regression test for #18709.
| def test_formset_splitdatetimefield(self):
"""
Formset should also work with SplitDateTimeField(initial=datetime.datetime.now).
Regression test for #18709.
"""
data = {
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '0',
'form-0-when_0': '1904-... | [
"def",
"test_formset_splitdatetimefield",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'form-TOTAL_FORMS'",
":",
"'1'",
",",
"'form-INITIAL_FORMS'",
":",
"'0'",
",",
"'form-0-when_0'",
":",
"'1904-06-16'",
",",
"'form-0-when_1'",
":",
"'15:51:33'",
",",
"}",
"formset... | [
922,
4
] | [
934,
43
] | python | en | ['en', 'error', 'th'] | False |
FormsFormsetTestCase.test_hard_limit_on_instantiated_forms | (self) | A formset has a hard limit on the number of forms instantiated. | A formset has a hard limit on the number of forms instantiated. | def test_hard_limit_on_instantiated_forms(self):
"""A formset has a hard limit on the number of forms instantiated."""
# reduce the default limit of 1000 temporarily for testing
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
try:
formsets.DEFAULT_MAX_NUM = 2
Choi... | [
"def",
"test_hard_limit_on_instantiated_forms",
"(",
"self",
")",
":",
"# reduce the default limit of 1000 temporarily for testing",
"_old_DEFAULT_MAX_NUM",
"=",
"formsets",
".",
"DEFAULT_MAX_NUM",
"try",
":",
"formsets",
".",
"DEFAULT_MAX_NUM",
"=",
"2",
"ChoiceFormSet",
"="... | [
966,
4
] | [
996,
59
] | python | en | ['en', 'en', 'en'] | True |
FormsFormsetTestCase.test_increase_hard_limit | (self) | Can increase the built-in forms limit via a higher max_num. | Can increase the built-in forms limit via a higher max_num. | def test_increase_hard_limit(self):
"""Can increase the built-in forms limit via a higher max_num."""
# reduce the default limit of 1000 temporarily for testing
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
try:
formsets.DEFAULT_MAX_NUM = 3
# for this form, we w... | [
"def",
"test_increase_hard_limit",
"(",
"self",
")",
":",
"# reduce the default limit of 1000 temporarily for testing",
"_old_DEFAULT_MAX_NUM",
"=",
"formsets",
".",
"DEFAULT_MAX_NUM",
"try",
":",
"formsets",
".",
"DEFAULT_MAX_NUM",
"=",
"3",
"# for this form, we want a limit o... | [
998,
4
] | [
1026,
59
] | python | en | ['en', 'en', 'en'] | True |
FormsFormsetTestCase.test_formset_total_error_count | (self) | A valid formset should have 0 total errors. | A valid formset should have 0 total errors. | def test_formset_total_error_count(self):
"""A valid formset should have 0 total errors."""
data = [ # formset_data, expected error count
([('Calexico', '100')], 0),
([('Calexico', '')], 1),
([('', 'invalid')], 2),
([('Calexico', '100'), ('Calexico', '')]... | [
"def",
"test_formset_total_error_count",
"(",
"self",
")",
":",
"data",
"=",
"[",
"# formset_data, expected error count",
"(",
"[",
"(",
"'Calexico'",
",",
"'100'",
")",
"]",
",",
"0",
")",
",",
"(",
"[",
"(",
"'Calexico'",
",",
"''",
")",
"]",
",",
"1",... | [
1060,
4
] | [
1072,
79
] | python | en | ['en', 'en', 'en'] | True |
TestEmptyFormSet.test_empty_formset_is_valid | (self) | Test that an empty formset still calls clean() | Test that an empty formset still calls clean() | def test_empty_formset_is_valid(self):
"""Test that an empty formset still calls clean()"""
EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, ... | [
"def",
"test_empty_formset_is_valid",
"(",
"self",
")",
":",
"EmptyFsetWontValidateFormset",
"=",
"formset_factory",
"(",
"FavoriteDrinkForm",
",",
"extra",
"=",
"0",
",",
"formset",
"=",
"EmptyFsetWontValidate",
")",
"formset",
"=",
"EmptyFsetWontValidateFormset",
"(",... | [
1195,
4
] | [
1201,
45
] | python | en | ['en', 'en', 'en'] | True |
TestEmptyFormSet.test_empty_formset_media | (self) | Make sure media is available on empty formset, refs #19545 | Make sure media is available on empty formset, refs #19545 | def test_empty_formset_media(self):
"""Make sure media is available on empty formset, refs #19545"""
class MediaForm(Form):
class Media:
js = ('some-file.js',)
self.assertIn('some-file.js', str(formset_factory(MediaForm, extra=0)().media)) | [
"def",
"test_empty_formset_media",
"(",
"self",
")",
":",
"class",
"MediaForm",
"(",
"Form",
")",
":",
"class",
"Media",
":",
"js",
"=",
"(",
"'some-file.js'",
",",
")",
"self",
".",
"assertIn",
"(",
"'some-file.js'",
",",
"str",
"(",
"formset_factory",
"(... | [
1203,
4
] | [
1208,
87
] | python | en | ['en', 'en', 'en'] | True |
TestEmptyFormSet.test_empty_formset_is_multipart | (self) | Make sure `is_multipart()` works with empty formset, refs #19545 | Make sure `is_multipart()` works with empty formset, refs #19545 | def test_empty_formset_is_multipart(self):
"""Make sure `is_multipart()` works with empty formset, refs #19545"""
class FileForm(Form):
file = FileField()
self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart()) | [
"def",
"test_empty_formset_is_multipart",
"(",
"self",
")",
":",
"class",
"FileForm",
"(",
"Form",
")",
":",
"file",
"=",
"FileField",
"(",
")",
"self",
".",
"assertTrue",
"(",
"formset_factory",
"(",
"FileForm",
",",
"extra",
"=",
"0",
")",
"(",
")",
".... | [
1210,
4
] | [
1214,
76
] | python | en | ['en', 'en', 'en'] | True |
FileBasedCache._cull | (self) |
Removes random cache entries if max_entries is reached at a ratio
of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means
that the entire cache will be purged.
|
Removes random cache entries if max_entries is reached at a ratio
of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means
that the entire cache will be purged.
| def _cull(self):
"""
Removes random cache entries if max_entries is reached at a ratio
of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means
that the entire cache will be purged.
"""
filelist = self._list_cache_files()
num_entries = len(filelist)
... | [
"def",
"_cull",
"(",
"self",
")",
":",
"filelist",
"=",
"self",
".",
"_list_cache_files",
"(",
")",
"num_entries",
"=",
"len",
"(",
"filelist",
")",
"if",
"num_entries",
"<",
"self",
".",
"_max_entries",
":",
"return",
"# return early if no culling is required",... | [
83,
4
] | [
99,
31
] | python | en | ['en', 'error', 'th'] | False |
FileBasedCache._key_to_file | (self, key, version=None) |
Convert a key into a cache file path. Basically this is the
root cache path joined with the md5sum of the key and a suffix.
|
Convert a key into a cache file path. Basically this is the
root cache path joined with the md5sum of the key and a suffix.
| def _key_to_file(self, key, version=None):
"""
Convert a key into a cache file path. Basically this is the
root cache path joined with the md5sum of the key and a suffix.
"""
key = self.make_key(key, version=version)
self.validate_key(key)
return os.path.join(self... | [
"def",
"_key_to_file",
"(",
"self",
",",
"key",
",",
"version",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"make_key",
"(",
"key",
",",
"version",
"=",
"version",
")",
"self",
".",
"validate_key",
"(",
"key",
")",
"return",
"os",
".",
"path",
... | [
111,
4
] | [
119,
76
] | python | en | ['en', 'error', 'th'] | False |
FileBasedCache.clear | (self) |
Remove all the cache files.
|
Remove all the cache files.
| def clear(self):
"""
Remove all the cache files.
"""
if not os.path.exists(self._dir):
return
for fname in self._list_cache_files():
self._delete(fname) | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_dir",
")",
":",
"return",
"for",
"fname",
"in",
"self",
".",
"_list_cache_files",
"(",
")",
":",
"self",
".",
"_delete",
"(",
"fname",
")"
] | [
121,
4
] | [
128,
31
] | python | en | ['en', 'error', 'th'] | False |
FileBasedCache._is_expired | (self, f) |
Takes an open cache file and determines if it has expired,
deletes the file if it is has passed its expiry time.
|
Takes an open cache file and determines if it has expired,
deletes the file if it is has passed its expiry time.
| def _is_expired(self, f):
"""
Takes an open cache file and determines if it has expired,
deletes the file if it is has passed its expiry time.
"""
exp = pickle.load(f)
if exp is not None and exp < time.time():
f.close() # On Windows a file has to be closed be... | [
"def",
"_is_expired",
"(",
"self",
",",
"f",
")",
":",
"exp",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"if",
"exp",
"is",
"not",
"None",
"and",
"exp",
"<",
"time",
".",
"time",
"(",
")",
":",
"f",
".",
"close",
"(",
")",
"# On Windows a file ha... | [
130,
4
] | [
140,
20
] | python | en | ['en', 'error', 'th'] | False |
FileBasedCache._list_cache_files | (self) |
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
|
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
| def _list_cache_files(self):
"""
Get a list of paths to all the cache files. These are all the files
in the root cache dir that end on the cache_suffix.
"""
if not os.path.exists(self._dir):
return []
filelist = [os.path.join(self._dir, fname) for fname
... | [
"def",
"_list_cache_files",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_dir",
")",
":",
"return",
"[",
"]",
"filelist",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"fname"... | [
142,
4
] | [
151,
23
] | python | en | ['en', 'error', 'th'] | False |
current | (report) |
The current implementation of report printing.
:param report: ConfidenceReport
|
The current implementation of report printing.
:param report: ConfidenceReport
| def current(report):
"""
The current implementation of report printing.
:param report: ConfidenceReport
"""
if hasattr(report, "completed"):
if report.completed:
print("Report completed")
else:
print("REPORT NOT COMPLETED")
else:
warnings.warn(
... | [
"def",
"current",
"(",
"report",
")",
":",
"if",
"hasattr",
"(",
"report",
",",
"\"completed\"",
")",
":",
"if",
"report",
".",
"completed",
":",
"print",
"(",
"\"Report completed\"",
")",
"else",
":",
"print",
"(",
"\"REPORT NOT COMPLETED\"",
")",
"else",
... | [
23,
0
] | [
43,
69
] | python | en | ['en', 'error', 'th'] | False |
deprecated | (report) |
The deprecated implementation of report printing.
:param report: dict
|
The deprecated implementation of report printing.
:param report: dict
| def deprecated(report):
"""
The deprecated implementation of report printing.
:param report: dict
"""
warnings.warn(
"Printing dict-based reports is deprecated. This function "
"is included only to support a private development branch "
"and may be removed without warning."
... | [
"def",
"deprecated",
"(",
"report",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Printing dict-based reports is deprecated. This function \"",
"\"is included only to support a private development branch \"",
"\"and may be removed without warning.\"",
")",
"for",
"key",
"in",
"report"... | [
46,
0
] | [
72,
75
] | python | en | ['en', 'error', 'th'] | False |
geos_version | () | Return the string version of the GEOS library. | Return the string version of the GEOS library. | def geos_version():
"""Return the string version of the GEOS library."""
return lgeos.GEOSversion() | [
"def",
"geos_version",
"(",
")",
":",
"return",
"lgeos",
".",
"GEOSversion",
"(",
")"
] | [
166,
0
] | [
168,
30
] | python | en | ['en', 'en', 'en'] | True |
geos_version_tuple | () | Return the GEOS version as a tuple (major, minor, subminor). | Return the GEOS version as a tuple (major, minor, subminor). | def geos_version_tuple():
"""Return the GEOS version as a tuple (major, minor, subminor)."""
return get_version_tuple(geos_version().decode()) | [
"def",
"geos_version_tuple",
"(",
")",
":",
"return",
"get_version_tuple",
"(",
"geos_version",
"(",
")",
".",
"decode",
"(",
")",
")"
] | [
171,
0
] | [
173,
53
] | python | en | ['en', 'lt', 'en'] | True |
parse | (version) |
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
|
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
| def parse(version):
"""
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
"""
try:
return Version(version)
except InvalidVersion:
retu... | [
"def",
"parse",
"(",
"version",
")",
":",
"try",
":",
"return",
"Version",
"(",
"version",
")",
"except",
"InvalidVersion",
":",
"return",
"LegacyVersion",
"(",
"version",
")"
] | [
20,
0
] | [
29,
37
] | python | en | ['en', 'error', 'th'] | False |
_parse_local_version | (local) |
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
|
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
| def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_separators.split(local)
) | [
"def",
"_parse_local_version",
"(",
"local",
")",
":",
"if",
"local",
"is",
"not",
"None",
":",
"return",
"tuple",
"(",
"part",
".",
"lower",
"(",
")",
"if",
"not",
"part",
".",
"isdigit",
"(",
")",
"else",
"int",
"(",
"part",
")",
"for",
"part",
"... | [
366,
0
] | [
374,
9
] | python | en | ['en', 'error', 'th'] | False |
cleanse_setting | (key, value) | Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary.
| Cleanse an individual setting key/value of sensitive content. | def cleanse_setting(key, value):
"""Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary.
"""
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
else:
if i... | [
"def",
"cleanse_setting",
"(",
"key",
",",
"value",
")",
":",
"try",
":",
"if",
"HIDDEN_SETTINGS",
".",
"search",
"(",
"key",
")",
":",
"cleansed",
"=",
"CLEANSED_SUBSTITUTE",
"else",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"cleanse... | [
48,
0
] | [
70,
19
] | python | en | ['en', 'en', 'en'] | True |
get_safe_settings | () | Returns a dictionary of the settings module, with sensitive settings blurred out. | Returns a dictionary of the settings module, with sensitive settings blurred out. | def get_safe_settings():
"Returns a dictionary of the settings module, with sensitive settings blurred out."
settings_dict = {}
for k in dir(settings):
if k.isupper():
settings_dict[k] = cleanse_setting(k, getattr(settings, k))
return settings_dict | [
"def",
"get_safe_settings",
"(",
")",
":",
"settings_dict",
"=",
"{",
"}",
"for",
"k",
"in",
"dir",
"(",
"settings",
")",
":",
"if",
"k",
".",
"isupper",
"(",
")",
":",
"settings_dict",
"[",
"k",
"]",
"=",
"cleanse_setting",
"(",
"k",
",",
"getattr",... | [
73,
0
] | [
79,
24
] | python | en | ['en', 'en', 'en'] | True |
technical_500_response | (request, exc_type, exc_value, tb, status_code=500) |
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
|
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
| def technical_500_response(request, exc_type, exc_value, tb, status_code=500):
"""
Create a technical server error response. The last three arguments are
the values returned from sys.exc_info() and friends.
"""
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
if request.is_ajax():
... | [
"def",
"technical_500_response",
"(",
"request",
",",
"exc_type",
",",
"exc_value",
",",
"tb",
",",
"status_code",
"=",
"500",
")",
":",
"reporter",
"=",
"ExceptionReporter",
"(",
"request",
",",
"exc_type",
",",
"exc_value",
",",
"tb",
")",
"if",
"request",... | [
82,
0
] | [
93,
79
] | python | en | ['en', 'error', 'th'] | False |
technical_404_response | (request, exception) | Create a technical 404 error response. The exception should be the Http404. | Create a technical 404 error response. The exception should be the Http404. | def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried =... | [
"def",
"technical_404_response",
"(",
"request",
",",
"exception",
")",
":",
"try",
":",
"error_url",
"=",
"exception",
".",
"args",
"[",
"0",
"]",
"[",
"'path'",
"]",
"except",
"(",
"IndexError",
",",
"TypeError",
",",
"KeyError",
")",
":",
"error_url",
... | [
505,
0
] | [
556,
70
] | python | en | ['en', 'en', 'en'] | True |
default_urlconf | (request) | Create an empty URLconf 404 error response. | Create an empty URLconf 404 error response. | def default_urlconf(request):
"Create an empty URLconf 404 error response."
t = Template(DEFAULT_URLCONF_TEMPLATE, name='Default URLconf template')
c = Context({
"title": _("Welcome to Django"),
"heading": _("It worked!"),
"subheading": _("Congratulations on your first Django-powere... | [
"def",
"default_urlconf",
"(",
"request",
")",
":",
"t",
"=",
"Template",
"(",
"DEFAULT_URLCONF_TEMPLATE",
",",
"name",
"=",
"'Default URLconf template'",
")",
"c",
"=",
"Context",
"(",
"{",
"\"title\"",
":",
"_",
"(",
"\"Welcome to Django\"",
")",
",",
"\"hea... | [
559,
0
] | [
573,
62
] | python | en | ['en', 'de', 'en'] | True |
SafeExceptionReporterFilter.is_active | (self, request) |
This filter is to add safety in production environments (i.e. DEBUG
is False). If DEBUG is True then your site is not safe anyway.
This hook is provided as a convenience to easily activate or
deactivate the filter on a per request basis.
|
This filter is to add safety in production environments (i.e. DEBUG
is False). If DEBUG is True then your site is not safe anyway.
This hook is provided as a convenience to easily activate or
deactivate the filter on a per request basis.
| def is_active(self, request):
"""
This filter is to add safety in production environments (i.e. DEBUG
is False). If DEBUG is True then your site is not safe anyway.
This hook is provided as a convenience to easily activate or
deactivate the filter on a per request basis.
... | [
"def",
"is_active",
"(",
"self",
",",
"request",
")",
":",
"return",
"settings",
".",
"DEBUG",
"is",
"False"
] | [
139,
4
] | [
146,
38
] | python | en | ['en', 'error', 'th'] | False |
SafeExceptionReporterFilter.get_cleansed_multivaluedict | (self, request, multivaluedict) |
Replaces the keys in a MultiValueDict marked as sensitive with stars.
This mitigates leaking sensitive POST parameters if something like
request.POST['nonexistent_key'] throws an exception (#21098).
|
Replaces the keys in a MultiValueDict marked as sensitive with stars.
This mitigates leaking sensitive POST parameters if something like
request.POST['nonexistent_key'] throws an exception (#21098).
| def get_cleansed_multivaluedict(self, request, multivaluedict):
"""
Replaces the keys in a MultiValueDict marked as sensitive with stars.
This mitigates leaking sensitive POST parameters if something like
request.POST['nonexistent_key'] throws an exception (#21098).
"""
s... | [
"def",
"get_cleansed_multivaluedict",
"(",
"self",
",",
"request",
",",
"multivaluedict",
")",
":",
"sensitive_post_parameters",
"=",
"getattr",
"(",
"request",
",",
"'sensitive_post_parameters'",
",",
"[",
"]",
")",
"if",
"self",
".",
"is_active",
"(",
"request",... | [
148,
4
] | [
160,
29
] | python | en | ['en', 'error', 'th'] | False |
SafeExceptionReporterFilter.get_post_parameters | (self, request) |
Replaces the values of POST parameters marked as sensitive with
stars (*********).
|
Replaces the values of POST parameters marked as sensitive with
stars (*********).
| def get_post_parameters(self, request):
"""
Replaces the values of POST parameters marked as sensitive with
stars (*********).
"""
if request is None:
return {}
else:
sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', [])
... | [
"def",
"get_post_parameters",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
"is",
"None",
":",
"return",
"{",
"}",
"else",
":",
"sensitive_post_parameters",
"=",
"getattr",
"(",
"request",
",",
"'sensitive_post_parameters'",
",",
"[",
"]",
")",
"if... | [
162,
4
] | [
185,
35
] | python | en | ['en', 'error', 'th'] | False |
SafeExceptionReporterFilter.get_traceback_frame_variables | (self, request, tb_frame) |
Replaces the values of variables marked as sensitive with
stars (*********).
|
Replaces the values of variables marked as sensitive with
stars (*********).
| def get_traceback_frame_variables(self, request, tb_frame):
"""
Replaces the values of variables marked as sensitive with
stars (*********).
"""
# Loop through the frame's callers to see if the sensitive_variables
# decorator was used.
current_frame = tb_frame.f_b... | [
"def",
"get_traceback_frame_variables",
"(",
"self",
",",
"request",
",",
"tb_frame",
")",
":",
"# Loop through the frame's callers to see if the sensitive_variables",
"# decorator was used.",
"current_frame",
"=",
"tb_frame",
".",
"f_back",
"sensitive_variables",
"=",
"None",
... | [
196,
4
] | [
244,
31
] | python | en | ['en', 'error', 'th'] | False |
ExceptionReporter.get_traceback_data | (self) | Return a dictionary containing traceback information. | Return a dictionary containing traceback information. | def get_traceback_data(self):
"""Return a dictionary containing traceback information."""
if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
from django.template.loader import template_source_loaders
self.template_does_not_exist = True
self.loader_... | [
"def",
"get_traceback_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"exc_type",
"and",
"issubclass",
"(",
"self",
".",
"exc_type",
",",
"TemplateDoesNotExist",
")",
":",
"from",
"django",
".",
"template",
".",
"loader",
"import",
"template_source_loaders",
... | [
277,
4
] | [
358,
16
] | python | en | ['en', 'en', 'en'] | True |
ExceptionReporter.get_traceback_html | (self) | Return HTML version of debug 500 HTTP error page. | Return HTML version of debug 500 HTTP error page. | def get_traceback_html(self):
"Return HTML version of debug 500 HTTP error page."
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
c = Context(self.get_traceback_data(), use_l10n=False)
return t.render(c) | [
"def",
"get_traceback_html",
"(",
"self",
")",
":",
"t",
"=",
"Template",
"(",
"TECHNICAL_500_TEMPLATE",
",",
"name",
"=",
"'Technical 500 template'",
")",
"c",
"=",
"Context",
"(",
"self",
".",
"get_traceback_data",
"(",
")",
",",
"use_l10n",
"=",
"False",
... | [
360,
4
] | [
364,
26
] | python | en | ['en', 'da', 'en'] | True |
ExceptionReporter.get_traceback_text | (self) | Return plain text version of debug 500 HTTP error page. | Return plain text version of debug 500 HTTP error page. | def get_traceback_text(self):
"Return plain text version of debug 500 HTTP error page."
t = Template(TECHNICAL_500_TEXT_TEMPLATE, name='Technical 500 template')
c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False)
return t.render(c) | [
"def",
"get_traceback_text",
"(",
"self",
")",
":",
"t",
"=",
"Template",
"(",
"TECHNICAL_500_TEXT_TEMPLATE",
",",
"name",
"=",
"'Technical 500 template'",
")",
"c",
"=",
"Context",
"(",
"self",
".",
"get_traceback_data",
"(",
")",
",",
"autoescape",
"=",
"Fal... | [
366,
4
] | [
370,
26
] | python | en | ['en', 'en', 'en'] | True |
ExceptionReporter._get_lines_from_file | (self, filename, lineno, context_lines, loader=None, module_name=None) |
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
|
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
| def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
source = None
if loader is not None and ... | [
"def",
"_get_lines_from_file",
"(",
"self",
",",
"filename",
",",
"lineno",
",",
"context_lines",
",",
"loader",
"=",
"None",
",",
"module_name",
"=",
"None",
")",
":",
"source",
"=",
"None",
"if",
"loader",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"l... | [
412,
4
] | [
455,
67
] | python | en | ['en', 'error', 'th'] | False |
ExceptionReporter.format_exception | (self) |
Return the same data as from traceback.format_exception.
|
Return the same data as from traceback.format_exception.
| def format_exception(self):
"""
Return the same data as from traceback.format_exception.
"""
import traceback
frames = self.get_traceback_frames()
tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
list = ['Traceback (most recent... | [
"def",
"format_exception",
"(",
"self",
")",
":",
"import",
"traceback",
"frames",
"=",
"self",
".",
"get_traceback_frames",
"(",
")",
"tb",
"=",
"[",
"(",
"f",
"[",
"'filename'",
"]",
",",
"f",
"[",
"'lineno'",
"]",
",",
"f",
"[",
"'function'",
"]",
... | [
492,
4
] | [
502,
19
] | python | en | ['en', 'error', 'th'] | False |
su_to_zulip | (save_suid: bool = False) | Warning: su_to_zulip assumes that the zulip checkout is owned by
the zulip user (or whatever normal user is running the Zulip
installation). It should never be run from the installer or other
production contexts before /home/zulip/deployments/current is
created. | Warning: su_to_zulip assumes that the zulip checkout is owned by
the zulip user (or whatever normal user is running the Zulip
installation). It should never be run from the installer or other
production contexts before /home/zulip/deployments/current is
created. | def su_to_zulip(save_suid: bool = False) -> None:
"""Warning: su_to_zulip assumes that the zulip checkout is owned by
the zulip user (or whatever normal user is running the Zulip
installation). It should never be run from the installer or other
production contexts before /home/zulip/deployments/current... | [
"def",
"su_to_zulip",
"(",
"save_suid",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"pwent",
"=",
"get_zulip_pwent",
"(",
")",
"os",
".",
"setgid",
"(",
"pwent",
".",
"pw_gid",
")",
"if",
"save_suid",
":",
"os",
".",
"setresuid",
"(",
"pwent",
... | [
144,
0
] | [
156,
37
] | python | en | ['en', 'en', 'en'] | True |
parse_os_release | () |
Example of the useful subset of the data:
{
'ID': 'ubuntu',
'VERSION_ID': '18.04',
'NAME': 'Ubuntu',
'VERSION': '18.04.3 LTS (Bionic Beaver)',
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
}
VERSION_CODENAME (e.g. 'bionic') is nice and human-readable, but
we avoid using it, as it i... |
Example of the useful subset of the data:
{
'ID': 'ubuntu',
'VERSION_ID': '18.04',
'NAME': 'Ubuntu',
'VERSION': '18.04.3 LTS (Bionic Beaver)',
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
} | def parse_os_release() -> Dict[str, str]:
"""
Example of the useful subset of the data:
{
'ID': 'ubuntu',
'VERSION_ID': '18.04',
'NAME': 'Ubuntu',
'VERSION': '18.04.3 LTS (Bionic Beaver)',
'PRETTY_NAME': 'Ubuntu 18.04.3 LTS',
}
VERSION_CODENAME (e.g. 'bionic') is nice and h... | [
"def",
"parse_os_release",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"distro_info",
"=",
"{",
"}",
"# type: Dict[str, str]",
"with",
"open",
"(",
"\"/etc/os-release\"",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"line",
"=",
... | [
403,
0
] | [
427,
22
] | python | en | ['en', 'error', 'th'] | False |
os_families | () |
Known families:
debian (includes: debian, ubuntu)
ubuntu (includes: ubuntu)
fedora (includes: fedora, rhel, centos)
rhel (includes: rhel, centos)
centos (includes: centos)
|
Known families:
debian (includes: debian, ubuntu)
ubuntu (includes: ubuntu)
fedora (includes: fedora, rhel, centos)
rhel (includes: rhel, centos)
centos (includes: centos)
| def os_families() -> Set[str]:
"""
Known families:
debian (includes: debian, ubuntu)
ubuntu (includes: ubuntu)
fedora (includes: fedora, rhel, centos)
rhel (includes: rhel, centos)
centos (includes: centos)
"""
distro_info = parse_os_release()
return {distro_info["ID"], *distro_i... | [
"def",
"os_families",
"(",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"distro_info",
"=",
"parse_os_release",
"(",
")",
"return",
"{",
"distro_info",
"[",
"\"ID\"",
"]",
",",
"*",
"distro_info",
".",
"get",
"(",
"\"ID_LIKE\"",
",",
"\"\"",
")",
".",
"spli... | [
431,
0
] | [
441,
71
] | python | en | ['en', 'error', 'th'] | False |
is_digest_obsolete | (
hash_name: str, filenames: Sequence[str], extra_strings: Sequence[str] = []
) |
In order to determine if we need to run some
process, we calculate a digest of the important
files and strings whose respective contents
or values may indicate such a need.
filenames = files we should hash the contents of
extra_strings = strings we should hash directly
Grep for ca... |
In order to determine if we need to run some
process, we calculate a digest of the important
files and strings whose respective contents
or values may indicate such a need. | def is_digest_obsolete(
hash_name: str, filenames: Sequence[str], extra_strings: Sequence[str] = []
) -> bool:
"""
In order to determine if we need to run some
process, we calculate a digest of the important
files and strings whose respective contents
or values may indicate such a need.
... | [
"def",
"is_digest_obsolete",
"(",
"hash_name",
":",
"str",
",",
"filenames",
":",
"Sequence",
"[",
"str",
"]",
",",
"extra_strings",
":",
"Sequence",
"[",
"str",
"]",
"=",
"[",
"]",
")",
"->",
"bool",
":",
"last_hash_path",
"=",
"os",
".",
"path",
".",... | [
457,
0
] | [
489,
31
] | python | en | ['en', 'error', 'th'] | False |
deport | (netloc: str) | Remove the port from a hostname:port string. Brackets on a literal
IPv6 address are included. | Remove the port from a hostname:port string. Brackets on a literal
IPv6 address are included. | def deport(netloc: str) -> str:
"""Remove the port from a hostname:port string. Brackets on a literal
IPv6 address are included."""
r = SplitResult("", netloc, "", "", "")
assert r.hostname is not None
return "[" + r.hostname + "]" if ":" in r.hostname else r.hostname | [
"def",
"deport",
"(",
"netloc",
":",
"str",
")",
"->",
"str",
":",
"r",
"=",
"SplitResult",
"(",
"\"\"",
",",
"netloc",
",",
"\"\"",
",",
"\"\"",
",",
"\"\"",
")",
"assert",
"r",
".",
"hostname",
"is",
"not",
"None",
"return",
"\"[\"",
"+",
"r",
... | [
596,
0
] | [
601,
70
] | python | en | ['en', 'en', 'en'] | True |
SimpleTest.test_nonempty_update | (self) |
Test that update changes the right number of rows for a nonempty queryset
|
Test that update changes the right number of rows for a nonempty queryset
| def test_nonempty_update(self):
"""
Test that update changes the right number of rows for a nonempty queryset
"""
num_updated = self.a1.b_set.update(y=100)
self.assertEqual(num_updated, 20)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 20) | [
"def",
"test_nonempty_update",
"(",
"self",
")",
":",
"num_updated",
"=",
"self",
".",
"a1",
".",
"b_set",
".",
"update",
"(",
"y",
"=",
"100",
")",
"self",
".",
"assertEqual",
"(",
"num_updated",
",",
"20",
")",
"cnt",
"=",
"B",
".",
"objects",
".",... | [
15,
4
] | [
22,
33
] | python | en | ['en', 'error', 'th'] | False |
SimpleTest.test_empty_update | (self) |
Test that update changes the right number of rows for an empty queryset
|
Test that update changes the right number of rows for an empty queryset
| def test_empty_update(self):
"""
Test that update changes the right number of rows for an empty queryset
"""
num_updated = self.a2.b_set.update(y=100)
self.assertEqual(num_updated, 0)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 0) | [
"def",
"test_empty_update",
"(",
"self",
")",
":",
"num_updated",
"=",
"self",
".",
"a2",
".",
"b_set",
".",
"update",
"(",
"y",
"=",
"100",
")",
"self",
".",
"assertEqual",
"(",
"num_updated",
",",
"0",
")",
"cnt",
"=",
"B",
".",
"objects",
".",
"... | [
24,
4
] | [
31,
32
] | python | en | ['en', 'error', 'th'] | False |
SimpleTest.test_nonempty_update_with_inheritance | (self) |
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
|
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
| def test_nonempty_update_with_inheritance(self):
"""
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
"""
num_updated = self.a1.d_set.update(y=100)
self.assertEqual(num_updated, 20)
cnt = D.objects.f... | [
"def",
"test_nonempty_update_with_inheritance",
"(",
"self",
")",
":",
"num_updated",
"=",
"self",
".",
"a1",
".",
"d_set",
".",
"update",
"(",
"y",
"=",
"100",
")",
"self",
".",
"assertEqual",
"(",
"num_updated",
",",
"20",
")",
"cnt",
"=",
"D",
".",
... | [
33,
4
] | [
41,
33
] | python | en | ['en', 'error', 'th'] | False |
SimpleTest.test_empty_update_with_inheritance | (self) |
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
|
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
| def test_empty_update_with_inheritance(self):
"""
Test that update changes the right number of rows for an empty queryset
when the update affects only a base table
"""
num_updated = self.a2.d_set.update(y=100)
self.assertEqual(num_updated, 0)
cnt = D.objects.filte... | [
"def",
"test_empty_update_with_inheritance",
"(",
"self",
")",
":",
"num_updated",
"=",
"self",
".",
"a2",
".",
"d_set",
".",
"update",
"(",
"y",
"=",
"100",
")",
"self",
".",
"assertEqual",
"(",
"num_updated",
",",
"0",
")",
"cnt",
"=",
"D",
".",
"obj... | [
43,
4
] | [
51,
32
] | python | en | ['en', 'error', 'th'] | False |
SimpleTest.test_foreign_key_update_with_id | (self) |
Test that update works using <field>_id for foreign keys
|
Test that update works using <field>_id for foreign keys
| def test_foreign_key_update_with_id(self):
"""
Test that update works using <field>_id for foreign keys
"""
num_updated = self.a1.d_set.update(a_id=self.a2)
self.assertEqual(num_updated, 20)
self.assertEqual(self.a2.d_set.count(), 20) | [
"def",
"test_foreign_key_update_with_id",
"(",
"self",
")",
":",
"num_updated",
"=",
"self",
".",
"a1",
".",
"d_set",
".",
"update",
"(",
"a_id",
"=",
"self",
".",
"a2",
")",
"self",
".",
"assertEqual",
"(",
"num_updated",
",",
"20",
")",
"self",
".",
... | [
53,
4
] | [
59,
51
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update | (self) |
Objects are updated by first filtering the candidates into a queryset
and then calling the update() method. It executes immediately and
returns nothing.
|
Objects are updated by first filtering the candidates into a queryset
and then calling the update() method. It executes immediately and
returns nothing.
| def test_update(self):
"""
Objects are updated by first filtering the candidates into a queryset
and then calling the update() method. It executes immediately and
returns nothing.
"""
resp = DataPoint.objects.filter(value="apple").update(name="d1")
self.assertEqua... | [
"def",
"test_update",
"(",
"self",
")",
":",
"resp",
"=",
"DataPoint",
".",
"objects",
".",
"filter",
"(",
"value",
"=",
"\"apple\"",
")",
".",
"update",
"(",
"name",
"=",
"\"d1\"",
")",
"self",
".",
"assertEqual",
"(",
"resp",
",",
"1",
")",
"resp",... | [
70,
4
] | [
79,
47
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update_multiple_objects | (self) |
We can update multiple objects at once.
|
We can update multiple objects at once.
| def test_update_multiple_objects(self):
"""
We can update multiple objects at once.
"""
resp = DataPoint.objects.filter(value="banana").update(
value="pineapple")
self.assertEqual(resp, 2)
self.assertEqual(DataPoint.objects.get(name="d2").value, 'pineapple') | [
"def",
"test_update_multiple_objects",
"(",
"self",
")",
":",
"resp",
"=",
"DataPoint",
".",
"objects",
".",
"filter",
"(",
"value",
"=",
"\"banana\"",
")",
".",
"update",
"(",
"value",
"=",
"\"pineapple\"",
")",
"self",
".",
"assertEqual",
"(",
"resp",
",... | [
81,
4
] | [
88,
77
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update_fk | (self) |
Foreign key fields can also be updated, although you can only update
the object referred to, not anything inside the related object.
|
Foreign key fields can also be updated, although you can only update
the object referred to, not anything inside the related object.
| def test_update_fk(self):
"""
Foreign key fields can also be updated, although you can only update
the object referred to, not anything inside the related object.
"""
resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0)
self.assertEqual(resp, 1)
resp... | [
"def",
"test_update_fk",
"(",
"self",
")",
":",
"resp",
"=",
"RelatedPoint",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"\"r1\"",
")",
".",
"update",
"(",
"data",
"=",
"self",
".",
"d0",
")",
"self",
".",
"assertEqual",
"(",
"resp",
",",
"1",
... | [
90,
4
] | [
98,
47
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update_multiple_fields | (self) |
Multiple fields can be updated at once
|
Multiple fields can be updated at once
| def test_update_multiple_fields(self):
"""
Multiple fields can be updated at once
"""
resp = DataPoint.objects.filter(value="apple").update(
value="fruit", another_value="peach")
self.assertEqual(resp, 1)
d = DataPoint.objects.get(name="d0")
self.asser... | [
"def",
"test_update_multiple_fields",
"(",
"self",
")",
":",
"resp",
"=",
"DataPoint",
".",
"objects",
".",
"filter",
"(",
"value",
"=",
"\"apple\"",
")",
".",
"update",
"(",
"value",
"=",
"\"fruit\"",
",",
"another_value",
"=",
"\"peach\"",
")",
"self",
"... | [
100,
4
] | [
109,
50
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update_all | (self) |
In the rare case you want to update every instance of a model, update()
is also a manager method.
|
In the rare case you want to update every instance of a model, update()
is also a manager method.
| def test_update_all(self):
"""
In the rare case you want to update every instance of a model, update()
is also a manager method.
"""
self.assertEqual(DataPoint.objects.update(value='thing'), 3)
resp = DataPoint.objects.values('value').distinct()
self.assertEqual(l... | [
"def",
"test_update_all",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"DataPoint",
".",
"objects",
".",
"update",
"(",
"value",
"=",
"'thing'",
")",
",",
"3",
")",
"resp",
"=",
"DataPoint",
".",
"objects",
".",
"values",
"(",
"'value'",
")"... | [
111,
4
] | [
118,
58
] | python | en | ['en', 'error', 'th'] | False |
AdvancedTests.test_update_slice_fail | (self) |
We do not support update on already sliced query sets.
|
We do not support update on already sliced query sets.
| def test_update_slice_fail(self):
"""
We do not support update on already sliced query sets.
"""
method = DataPoint.objects.all()[:2].update
self.assertRaises(AssertionError, method,
another_value='another thing') | [
"def",
"test_update_slice_fail",
"(",
"self",
")",
":",
"method",
"=",
"DataPoint",
".",
"objects",
".",
"all",
"(",
")",
"[",
":",
"2",
"]",
".",
"update",
"self",
".",
"assertRaises",
"(",
"AssertionError",
",",
"method",
",",
"another_value",
"=",
"'a... | [
120,
4
] | [
126,
56
] | python | en | ['en', 'error', 'th'] | False |
generate_saml_response | (
self, email: str, name: str, extra_attributes: Mapping[str, List[str]] = {}
) |
The samlresponse.txt fixture has a pre-generated SAMLResponse,
with {email}, {first_name}, {last_name} placeholders, that can
be filled out with the data we want.
|
The samlresponse.txt fixture has a pre-generated SAMLResponse,
with {email}, {first_name}, {last_name} placeholders, that can
be filled out with the data we want.
| def generate_saml_response(
self, email: str, name: str, extra_attributes: Mapping[str, List[str]] = {}
) -> str:
"""
The samlresponse.txt fixture has a pre-generated SAMLResponse,
with {email}, {first_name}, {last_name} placeholders, that can
be filled out with the data we w... | [
"def",
"generate_saml_response",
"(",
"self",
",",
"email",
":",
"str",
",",
"name",
":",
"str",
",",
"extra_attributes",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"{",
"}",
")",
"->",
"str",
":",
"name_parts",
"=",
"name",
... | [
1811,
4
] | [
1846,
28
] | python | en | ['en', 'error', 'th'] | False |
test_social_auth_no_key | (self) |
Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING,
we override this test, to test for the case where the obligatory
SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured.
|
Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING,
we override this test, to test for the case where the obligatory
SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured.
| def test_social_auth_no_key(self) -> None:
"""
Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING,
we override this test, to test for the case where the obligatory
SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured.
"""
account_data_dict = self.ge... | [
"def",
"test_social_auth_no_key",
"(",
"self",
")",
"->",
"None",
":",
"account_data_dict",
"=",
"self",
".",
"get_account_data_dict",
"(",
"email",
"=",
"self",
".",
"email",
",",
"name",
"=",
"self",
".",
"name",
")",
"with",
"self",
".",
"settings",
"("... | [
1851,
4
] | [
1868,
99
] | python | en | ['en', 'error', 'th'] | False |
test_social_auth_complete_valid_get_idp_bad_samlresponse | (self) |
This tests for a hypothetical scenario where our basic parsing of the SAMLResponse
successfully returns the issuing IdP, but it fails further down the line, during proper
validation in the underlying libraries.
|
This tests for a hypothetical scenario where our basic parsing of the SAMLResponse
successfully returns the issuing IdP, but it fails further down the line, during proper
validation in the underlying libraries.
| def test_social_auth_complete_valid_get_idp_bad_samlresponse(self) -> None:
"""
This tests for a hypothetical scenario where our basic parsing of the SAMLResponse
successfully returns the issuing IdP, but it fails further down the line, during proper
validation in the underlying librarie... | [
"def",
"test_social_auth_complete_valid_get_idp_bad_samlresponse",
"(",
"self",
")",
"->",
"None",
":",
"with",
"self",
".",
"assertLogs",
"(",
"self",
".",
"logger_string",
",",
"level",
"=",
"\"INFO\"",
")",
"as",
"m",
",",
"mock",
".",
"patch",
".",
"object... | [
2058,
4
] | [
2081,
39
] | python | en | ['en', 'error', 'th'] | False |
test_social_auth_invalid_email | (self) |
This test needs an override from the original class. For security reasons,
the 'next' and 'mobile_flow_otp' params don't get passed on in the session
if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details.
|
This test needs an override from the original class. For security reasons,
the 'next' and 'mobile_flow_otp' params don't get passed on in the session
if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details.
| def test_social_auth_invalid_email(self) -> None:
"""
This test needs an override from the original class. For security reasons,
the 'next' and 'mobile_flow_otp' params don't get passed on in the session
if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details.... | [
"def",
"test_social_auth_invalid_email",
"(",
"self",
")",
"->",
"None",
":",
"account_data_dict",
"=",
"self",
".",
"get_account_data_dict",
"(",
"email",
"=",
"\"invalid\"",
",",
"name",
"=",
"self",
".",
"name",
")",
"with",
"self",
".",
"assertLogs",
"(",
... | [
2110,
4
] | [
2128,
47
] | python | en | ['en', 'error', 'th'] | False |
SocialAuthBase.social_auth_test | (
self,
account_data_dict: Dict[str, str],
*,
subdomain: str,
mobile_flow_otp: Optional[str] = None,
desktop_flow_otp: Optional[str] = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
expect_choose_email_screen:... | Main entrypoint for all social authentication tests.
* account_data_dict: Dictionary containing the name/email data
that should be returned by the social auth backend.
* subdomain: Which organization's login page is being accessed.
* desktop_flow_otp / mobile_flow_otp: Token to be use... | Main entrypoint for all social authentication tests. | def social_auth_test(
self,
account_data_dict: Dict[str, str],
*,
subdomain: str,
mobile_flow_otp: Optional[str] = None,
desktop_flow_otp: Optional[str] = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
expect_... | [
"def",
"social_auth_test",
"(",
"self",
",",
"account_data_dict",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"*",
",",
"subdomain",
":",
"str",
",",
"mobile_flow_otp",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"desktop_flow_otp",
":",
"Opti... | [
901,
4
] | [
994,
21
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_registration_existing_account | (self) | If the user already exists, signup flow just logs them in | If the user already exists, signup flow just logs them in | def test_social_auth_registration_existing_account(self) -> None:
"""If the user already exists, signup flow just logs them in"""
email = "hamlet@zulip.com"
name = "Full Name"
account_data_dict = self.get_account_data_dict(email=email, name=name)
result = self.social_auth_test(
... | [
"def",
"test_social_auth_registration_existing_account",
"(",
"self",
")",
"->",
"None",
":",
"email",
"=",
"\"hamlet@zulip.com\"",
"name",
"=",
"\"Full Name\"",
"account_data_dict",
"=",
"self",
".",
"get_account_data_dict",
"(",
"email",
"=",
"email",
",",
"name",
... | [
1255,
4
] | [
1274,
57
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_registration | (self) | If the user doesn't exist yet, social auth can be used to register an account | If the user doesn't exist yet, social auth can be used to register an account | def test_social_auth_registration(self) -> None:
"""If the user doesn't exist yet, social auth can be used to register an account"""
email = "newuser@zulip.com"
name = "Full Name"
subdomain = "zulip"
realm = get_realm("zulip")
account_data_dict = self.get_account_data_dic... | [
"def",
"test_social_auth_registration",
"(",
"self",
")",
"->",
"None",
":",
"email",
"=",
"\"newuser@zulip.com\"",
"name",
"=",
"\"Full Name\"",
"subdomain",
"=",
"\"zulip\"",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"account_data_dict",
"=",
"self",
"."... | [
1359,
4
] | [
1371,
9
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_registration_invitation_exists | (self) |
This tests the registration flow in the case where an invitation for the user
was generated.
|
This tests the registration flow in the case where an invitation for the user
was generated.
| def test_social_auth_registration_invitation_exists(self) -> None:
"""
This tests the registration flow in the case where an invitation for the user
was generated.
"""
email = "newuser@zulip.com"
name = "Full Name"
subdomain = "zulip"
realm = get_realm("zu... | [
"def",
"test_social_auth_registration_invitation_exists",
"(",
"self",
")",
"->",
"None",
":",
"email",
"=",
"\"newuser@zulip.com\"",
"name",
"=",
"\"Full Name\"",
"subdomain",
"=",
"\"zulip\"",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"iago",
"=",
"self",
... | [
1428,
4
] | [
1447,
9
] | python | en | ['en', 'error', 'th'] | False |
SocialAuthBase.test_social_auth_registration_using_multiuse_invite | (self) | If the user doesn't exist yet, social auth can be used to register an account | If the user doesn't exist yet, social auth can be used to register an account | def test_social_auth_registration_using_multiuse_invite(self) -> None:
"""If the user doesn't exist yet, social auth can be used to register an account"""
email = "newuser@zulip.com"
name = "Full Name"
subdomain = "zulip"
realm = get_realm("zulip")
realm.invite_required =... | [
"def",
"test_social_auth_registration_using_multiuse_invite",
"(",
"self",
")",
"->",
"None",
":",
"email",
"=",
"\"newuser@zulip.com\"",
"name",
"=",
"\"Full Name\"",
"subdomain",
"=",
"\"zulip\"",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"realm",
".",
"in... | [
1450,
4
] | [
1491,
9
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_registration_without_is_signup | (self) | If `is_signup` is not set then a new account isn't created | If `is_signup` is not set then a new account isn't created | def test_social_auth_registration_without_is_signup(self) -> None:
"""If `is_signup` is not set then a new account isn't created"""
email = "newuser@zulip.com"
name = "Full Name"
account_data_dict = self.get_account_data_dict(email=email, name=name)
result = self.social_auth_test... | [
"def",
"test_social_auth_registration_without_is_signup",
"(",
"self",
")",
"->",
"None",
":",
"email",
"=",
"\"newuser@zulip.com\"",
"name",
"=",
"\"Full Name\"",
"account_data_dict",
"=",
"self",
".",
"get_account_data_dict",
"(",
"email",
"=",
"email",
",",
"name",... | [
1493,
4
] | [
1513,
82
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_registration_without_is_signup_closed_realm | (self) | If the user doesn't exist yet in closed realm, give an error | If the user doesn't exist yet in closed realm, give an error | def test_social_auth_registration_without_is_signup_closed_realm(self) -> None:
"""If the user doesn't exist yet in closed realm, give an error"""
realm = get_realm("zulip")
do_set_realm_property(realm, "emails_restricted_to_domains", True, acting_user=None)
email = "nonexisting@phantom.... | [
"def",
"test_social_auth_registration_without_is_signup_closed_realm",
"(",
"self",
")",
"->",
"None",
":",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"do_set_realm_property",
"(",
"realm",
",",
"\"emails_restricted_to_domains\"",
",",
"True",
",",
"acting_user",
... | [
1515,
4
] | [
1543,
9
] | python | en | ['en', 'en', 'en'] | True |
SocialAuthBase.test_social_auth_with_ldap_auth_registration_from_confirmation | (self) |
This test checks that in configurations that use the LDAP authentication backend
and a social backend, it is possible to create non-LDAP users via the social backend.
|
This test checks that in configurations that use the LDAP authentication backend
and a social backend, it is possible to create non-LDAP users via the social backend.
| def test_social_auth_with_ldap_auth_registration_from_confirmation(self) -> None:
"""
This test checks that in configurations that use the LDAP authentication backend
and a social backend, it is possible to create non-LDAP users via the social backend.
"""
self.init_default_ldap_... | [
"def",
"test_social_auth_with_ldap_auth_registration_from_confirmation",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"init_default_ldap_database",
"(",
")",
"email",
"=",
"self",
".",
"nonreg_email",
"(",
"\"alice\"",
")",
"name",
"=",
"\"Alice Social\"",
"realm... | [
1609,
4
] | [
1661,
9
] | python | en | ['en', 'error', 'th'] | False |
format | (number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
force_grouping=False, use_l10n=None) |
Get a number (as a number or string), and return it as a string,
using formats defined as arguments:
* decimal_sep: Decimal separator symbol (for example ".")
* decimal_pos: Number of decimal positions
* grouping: Number of digits in every group limited by thousand separator.
For non-unifo... |
Get a number (as a number or string), and return it as a string,
using formats defined as arguments: | def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
force_grouping=False, use_l10n=None):
"""
Get a number (as a number or string), and return it as a string,
using formats defined as arguments:
* decimal_sep: Decimal separator symbol (for example ".")
* decima... | [
"def",
"format",
"(",
"number",
",",
"decimal_sep",
",",
"decimal_pos",
"=",
"None",
",",
"grouping",
"=",
"0",
",",
"thousand_sep",
"=",
"''",
",",
"force_grouping",
"=",
"False",
",",
"use_l10n",
"=",
"None",
")",
":",
"use_grouping",
"=",
"(",
"use_l1... | [
6,
0
] | [
86,
37
] | python | en | ['en', 'error', 'th'] | False |
get_preprocessed_data_set | (data_path) | Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing.
Args:
data_path: path to folder where data is stored.
Returns:
data... | Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing. | def get_preprocessed_data_set(data_path):
"""Preprocess the data set and return it. Because a list of targets and the paths
to the images are needed later, the class ImageFolderWithTargetListAndPaths
is used. Preprocessing follows standard ResNet-preprocessing.
Args:
data_path: path to folder... | [
"def",
"get_preprocessed_data_set",
"(",
"data_path",
")",
":",
"# standard ResNet-preprocessing",
"data_set",
"=",
"ImageFolderWithTargetListAndPaths",
"(",
"data_path",
",",
"transforms",
".",
"Compose",
"(",
"[",
"transforms",
".",
"Resize",
"(",
"256",
")",
",",
... | [
75,
0
] | [
102,
19
] | python | en | ['en', 'en', 'en'] | True |
get_data_loader | (Ullman_or_ImageNet) | The goal of this function is to return the data loader. Therefore, the path to the images is obtained, the data set is preprocessed and the the loader is created.
Note that the returned targets for the images from Ullman et al. are a subjective selection and is determined in imagenet_classes_for_images_from_Ullman_... | The goal of this function is to return the data loader. Therefore, the path to the images is obtained, the data set is preprocessed and the the loader is created.
Note that the returned targets for the images from Ullman et al. are a subjective selection and is determined in imagenet_classes_for_images_from_Ullman_... | def get_data_loader(Ullman_or_ImageNet):
"""The goal of this function is to return the data loader. Therefore, the path to the images is obtained, the data set is preprocessed and the the loader is created.
Note that the returned targets for the images from Ullman et al. are a subjective selection and is determ... | [
"def",
"get_data_loader",
"(",
"Ullman_or_ImageNet",
")",
":",
"data_set",
"=",
"get_preprocessed_data_set",
"(",
"config",
".",
"data_path",
")",
"# make data_loader deterministic despite shuffling",
"torch",
".",
"manual_seed",
"(",
"2809",
")",
"data_loader",
"=",
"t... | [
105,
0
] | [
129,
22
] | python | en | ['en', 'en', 'en'] | True |
generate_build_file_contents | (
name: str, dependencies: List[str], whl_file_deps: List[str], pip_data_exclude: List[str],
) | Generate a BUILD file for an unzipped Wheel
Args:
name: the target name of the py_library
dependencies: a list of Bazel labels pointing to dependencies of the library
whl_file_deps: a list of Bazel labels pointing to wheel file dependencies of this wheel.
Returns:
A complete BU... | Generate a BUILD file for an unzipped Wheel | def generate_build_file_contents(
name: str, dependencies: List[str], whl_file_deps: List[str], pip_data_exclude: List[str],
) -> str:
"""Generate a BUILD file for an unzipped Wheel
Args:
name: the target name of the py_library
dependencies: a list of Bazel labels pointing to dependencies o... | [
"def",
"generate_build_file_contents",
"(",
"name",
":",
"str",
",",
"dependencies",
":",
"List",
"[",
"str",
"]",
",",
"whl_file_deps",
":",
"List",
"[",
"str",
"]",
",",
"pip_data_exclude",
":",
"List",
"[",
"str",
"]",
",",
")",
"->",
"str",
":",
"d... | [
12,
0
] | [
59,
5
] | python | en | ['en', 'en', 'en'] | True |
generate_requirements_file_contents | (repo_name: str, targets: Iterable[str]) | Generate a requirements.bzl file for a given pip repository
The file allows converting the PyPI name to a bazel label. Additionally, it adds a function which can glob all the
installed dependencies.
Args:
repo_name: the name of the pip repository
targets: a list of Bazel labels pointing to... | Generate a requirements.bzl file for a given pip repository | def generate_requirements_file_contents(repo_name: str, targets: Iterable[str]) -> str:
"""Generate a requirements.bzl file for a given pip repository
The file allows converting the PyPI name to a bazel label. Additionally, it adds a function which can glob all the
installed dependencies.
Args:
... | [
"def",
"generate_requirements_file_contents",
"(",
"repo_name",
":",
"str",
",",
"targets",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"str",
":",
"return",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\\\n all_requirements = [{requirement_labels}]\n\n def requi... | [
62,
0
] | [
89,
5
] | python | en | ['en', 'en', 'en'] | True |
sanitise_name | (name: str) | Sanitises the name to be compatible with Bazel labels.
There are certain requirements around Bazel labels that we need to consider. From the Bazel docs:
Package names must be composed entirely of characters drawn from the set A-Z, a–z, 0–9, '/', '-', '.', and '_',
and cannot start with a slash.
... | Sanitises the name to be compatible with Bazel labels. | def sanitise_name(name: str) -> str:
"""Sanitises the name to be compatible with Bazel labels.
There are certain requirements around Bazel labels that we need to consider. From the Bazel docs:
Package names must be composed entirely of characters drawn from the set A-Z, a–z, 0–9, '/', '-', '.', and '_... | [
"def",
"sanitise_name",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"return",
"\"pypi__\"",
"+",
"name",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
".",
"replace",
"(",
"\".\"",
",",
"\"_\"",
")",
".",
"lower",
"(",
")"
] | [
92,
0
] | [
109,
70
] | python | en | ['en', 'en', 'en'] | True |
setup_namespace_pkg_compatibility | (wheel_dir: str) | Converts native namespace packages to pkgutil-style packages
Namespace packages can be created in one of three ways. They are detailed here:
https://packaging.python.org/guides/packaging-namespace-packages/#creating-a-namespace-package
'pkgutil-style namespace packages' (2) and 'pkg_resources-style namesp... | Converts native namespace packages to pkgutil-style packages | def setup_namespace_pkg_compatibility(wheel_dir: str) -> None:
"""Converts native namespace packages to pkgutil-style packages
Namespace packages can be created in one of three ways. They are detailed here:
https://packaging.python.org/guides/packaging-namespace-packages/#creating-a-namespace-package
... | [
"def",
"setup_namespace_pkg_compatibility",
"(",
"wheel_dir",
":",
"str",
")",
"->",
"None",
":",
"namespace_pkg_dirs",
"=",
"namespace_pkgs",
".",
"implicit_namespace_packages",
"(",
"wheel_dir",
",",
"ignored_dirnames",
"=",
"[",
"\"%s/bin\"",
"%",
"wheel_dir",
",",... | [
112,
0
] | [
132,
71
] | python | en | ['en', 'en', 'en'] | True |
extract_wheel | (
wheel_file: str,
extras: Dict[str, Set[str]],
pip_data_exclude: List[str],
enable_implicit_namespace_pkgs: bool,
) | Extracts wheel into given directory and creates py_library and filegroup targets.
Args:
wheel_file: the filepath of the .whl
extras: a list of extras to add as dependencies for the installed wheel
pip_data_exclude: list of file patterns to exclude from the generated data section of the py_l... | Extracts wheel into given directory and creates py_library and filegroup targets. | def extract_wheel(
wheel_file: str,
extras: Dict[str, Set[str]],
pip_data_exclude: List[str],
enable_implicit_namespace_pkgs: bool,
) -> str:
"""Extracts wheel into given directory and creates py_library and filegroup targets.
Args:
wheel_file: the filepath of the .whl
extras: a... | [
"def",
"extract_wheel",
"(",
"wheel_file",
":",
"str",
",",
"extras",
":",
"Dict",
"[",
"str",
",",
"Set",
"[",
"str",
"]",
"]",
",",
"pip_data_exclude",
":",
"List",
"[",
"str",
"]",
",",
"enable_implicit_namespace_pkgs",
":",
"bool",
",",
")",
"->",
... | [
135,
0
] | [
185,
29
] | python | en | ['en', 'en', 'en'] | True |
do_get_available_languages | (parser, token) |
This will store a list of available languages
in the context.
Usage::
{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}
This will just pull the LANGUAGES setting from
your setting file (or the default settings) and
put... |
This will store a list of available languages
in the context. | def do_get_available_languages(parser, token):
"""
This will store a list of available languages
in the context.
Usage::
{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}
This will just pull the LANGUAGES setting from
y... | [
"def",
"do_get_available_languages",
"(",
"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",
")",
... | [
186,
0
] | [
206,
45
] | python | en | ['en', 'error', 'th'] | False |
do_get_language_info | (parser, token) |
This will store the language information dictionary for the given language
code in a context variable.
Usage::
{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
|
This will store the language information dictionary for the given language
code in a context variable. | def do_get_language_info(parser, token):
"""
This will store the language information dictionary for the given language
code in a context variable.
Usage::
{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_local }}
{{ l.bidi|yesn... | [
"def",
"do_get_language_info",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"5",
"or",
"args",
"[",
"1",
"]",
"!=",
"'for'",
"or",
"args",
"[",
"3",
"]",
"!=",
... | [
210,
0
] | [
226,
71
] | python | en | ['en', 'error', 'th'] | False |
do_get_language_info_list | (parser, token) |
This will store a list of language information dictionaries for the given
language codes in a context variable. The language codes can be specified
either as a list of strings or a settings.LANGUAGES style tuple (or any
sequence of sequences whose first items are language codes).
Usage::
... |
This will store a list of language information dictionaries for the given
language codes in a context variable. The language codes can be specified
either as a list of strings or a settings.LANGUAGES style tuple (or any
sequence of sequences whose first items are language codes). | def do_get_language_info_list(parser, token):
"""
This will store a list of language information dictionaries for the given
language codes in a context variable. The language codes can be specified
either as a list of strings or a settings.LANGUAGES style tuple (or any
sequence of sequences whose fi... | [
"def",
"do_get_language_info_list",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"5",
"or",
"args",
"[",
"1",
"]",
"!=",
"'for'",
"or",
"args",
"[",
"3",
"]",
"!=... | [
230,
0
] | [
250,
75
] | python | en | ['en', 'error', 'th'] | False |
do_get_current_language | (parser, token) |
This will store the current language in the context.
Usage::
{% get_current_language as language %}
This will fetch the currently active language and
put it's value into the ``language`` context
variable.
|
This will store the current language in the context. | def do_get_current_language(parser, token):
"""
This will store the current language in the context.
Usage::
{% get_current_language as language %}
This will fetch the currently active language and
put it's value into the ``language`` context
variable.
"""
# token.split_conten... | [
"def",
"do_get_current_language",
"(",
"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",
")",
"!=... | [
269,
0
] | [
285,
42
] | python | en | ['en', 'error', 'th'] | False |
do_get_current_language_bidi | (parser, token) |
This will store the current language layout in the context.
Usage::
{% get_current_language_bidi as bidi %}
This will fetch the currently active language's layout and
put it's value into the ``bidi`` context variable.
True indicates right-to-left layout, otherwise left-to-right
|
This will store the current language layout in the context. | def do_get_current_language_bidi(parser, token):
"""
This will store the current language layout in the context.
Usage::
{% get_current_language_bidi as bidi %}
This will fetch the currently active language's layout and
put it's value into the ``bidi`` context variable.
True indicates... | [
"def",
"do_get_current_language_bidi",
"(",
"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",
")",
... | [
289,
0
] | [
305,
46
] | python | en | ['en', 'error', 'th'] | False |
do_translate | (parser, token) |
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and will run the string through the translati... |
This will mark a string for translation and will
translate the string for the current language. | def do_translate(parser, token):
"""
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and w... | [
"def",
"do_translate",
"(",
"parser",
",",
"token",
")",
":",
"class",
"TranslateParser",
"(",
"TokenParser",
")",
":",
"def",
"top",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"value",
"(",
")",
"# Backwards Compatibility fix:",
"# FilterExpression doe... | [
309,
0
] | [
385,
41
] | python | en | ['en', 'error', 'th'] | False |
do_block_translate | (parser, token) |
This will translate a block of text with parameters.
Usage::
{% blocktrans with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
Additionally, this supports pluralization::
{% blocktrans count count=var|length %}
There is {{ c... |
This will translate a block of text with parameters. | def do_block_translate(parser, token):
"""
This will translate a block of text with parameters.
Usage::
{% blocktrans with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
Additionally, this supports pluralization::
{% blocktrans c... | [
"def",
"do_block_translate",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"options",
"=",
"{",
"}",
"remaining_bits",
"=",
"bits",
"[",
"1",
":",
"]",
"while",
"remaining_bits",
":",
"option",
"=",
"remain... | [
389,
0
] | [
491,
72
] | python | en | ['en', 'error', 'th'] | False |
language | (parser, token) |
This will enable the given language just for this block.
Usage::
{% language "de" %}
This is {{ bar }} and {{ boo }}.
{% endlanguage %}
|
This will enable the given language just for this block. | def language(parser, token):
"""
This will enable the given language just for this block.
Usage::
{% language "de" %}
This is {{ bar }} and {{ boo }}.
{% endlanguage %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' tak... | [
"def",
"language",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes one argument (language)\"",
"%",
"bits",
"[",
... | [
495,
0
] | [
512,
43
] | 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.