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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
EncodingBytes.matchBytes | (self, bytes) | Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone | Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone | def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
... | [
"def",
"matchBytes",
"(",
"self",
",",
"bytes",
")",
":",
"p",
"=",
"self",
".",
"position",
"data",
"=",
"self",
"[",
"p",
":",
"p",
"+",
"len",
"(",
"bytes",
")",
"]",
"rv",
"=",
"data",
".",
"startswith",
"(",
"bytes",
")",
"if",
"rv",
":",
... | [
662,
4
] | [
671,
17
] | python | en | ['en', 'en', 'en'] | True |
EncodingBytes.jumpTo | (self, bytes) | Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match | Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match | def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nice... | [
"def",
"jumpTo",
"(",
"self",
",",
"bytes",
")",
":",
"newPosition",
"=",
"self",
"[",
"self",
".",
"position",
":",
"]",
".",
"find",
"(",
"bytes",
")",
"if",
"newPosition",
">",
"-",
"1",
":",
"# XXX: This is ugly, but I can't see a nicer way to fix this.",
... | [
673,
4
] | [
684,
31
] | python | en | ['en', 'en', 'en'] | True |
EncodingParser.__init__ | (self, data) | string - the data to work on for encoding detection | string - the data to work on for encoding detection | def __init__(self, data):
"""string - the data to work on for encoding detection"""
self.data = EncodingBytes(data)
self.encoding = None | [
"def",
"__init__",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"data",
"=",
"EncodingBytes",
"(",
"data",
")",
"self",
".",
"encoding",
"=",
"None"
] | [
690,
4
] | [
693,
28
] | python | en | ['en', 'en', 'en'] | True |
EncodingParser.handleComment | (self) | Skip over comments | Skip over comments | def handleComment(self):
"""Skip over comments"""
return self.data.jumpTo(b"-->") | [
"def",
"handleComment",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"jumpTo",
"(",
"b\"-->\"",
")"
] | [
718,
4
] | [
720,
39
] | python | en | ['en', 'en', 'en'] | True |
EncodingParser.getAttribute | (self) | Return a name,value pair for the next attribute in the stream,
if one is found, or None | Return a name,value pair for the next attribute in the stream,
if one is found, or None | def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if... | [
"def",
"getAttribute",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"# Step 1 (skip chars)",
"c",
"=",
"data",
".",
"skip",
"(",
"spaceCharactersBytes",
"|",
"frozenset",
"(",
"[",
"b\"/\"",
"]",
")",
")",
"assert",
"c",
"is",
"None",
"or",
... | [
791,
4
] | [
865,
35
] | python | en | ['en', 'en', 'en'] | True |
install_editable | (
install_options, # type: List[str]
global_options, # type: Sequence[str]
prefix, # type: Optional[str]
home, # type: Optional[str]
use_user_site, # type: bool
name, # type: str
setup_py_path, # type: str
isolated, # type: bool
build_env, # type: BuildEnvironment
unpack... | Install a package in editable mode. Most arguments are pass-through
to setuptools.
| Install a package in editable mode. Most arguments are pass-through
to setuptools.
| def install_editable(
install_options, # type: List[str]
global_options, # type: Sequence[str]
prefix, # type: Optional[str]
home, # type: Optional[str]
use_user_site, # type: bool
name, # type: str
setup_py_path, # type: str
isolated, # type: bool
build_env, # type: BuildEn... | [
"def",
"install_editable",
"(",
"install_options",
",",
"# type: List[str]",
"global_options",
",",
"# type: Sequence[str]",
"prefix",
",",
"# type: Optional[str]",
"home",
",",
"# type: Optional[str]",
"use_user_site",
",",
"# type: bool",
"name",
",",
"# type: str",
"setu... | [
18,
0
] | [
51,
13
] | python | en | ['en', 'en', 'en'] | True |
inject_into_urllib3 | () |
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
|
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
| def inject_into_urllib3():
"""
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
"""
util.SSLContext = SecureTransportContext
util.ssl_.SSLContext = SecureTransportContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_SECURETRANSPORT = True
util.ssl_.IS_SECUR... | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"SecureTransportContext",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",
"HAS... | [
179,
0
] | [
188,
39
] | python | en | ['en', 'error', 'th'] | False |
extract_from_urllib3 | () |
Undo monkey-patching by :func:`inject_into_urllib3`.
|
Undo monkey-patching by :func:`inject_into_urllib3`.
| def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.SSLContext = orig_util_SSLContext
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_... | [
"def",
"extract_from_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"HAS_SNI",
"=",
"orig_util_HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",... | [
191,
0
] | [
200,
40
] | python | en | ['en', 'error', 'th'] | False |
_read_callback | (connection_id, data_buffer, data_length_pointer) |
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
|
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
| def _read_callback(connection_id, data_buffer, data_length_pointer):
"""
SecureTransport read callback. This is called by ST to request that data
be returned from the socket.
"""
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_socket is ... | [
"def",
"_read_callback",
"(",
"connection_id",
",",
"data_buffer",
",",
"data_length_pointer",
")",
":",
"wrapped_socket",
"=",
"None",
"try",
":",
"wrapped_socket",
"=",
"_connection_refs",
".",
"get",
"(",
"connection_id",
")",
"if",
"wrapped_socket",
"is",
"Non... | [
203,
0
] | [
255,
43
] | python | en | ['en', 'error', 'th'] | False |
_write_callback | (connection_id, data_buffer, data_length_pointer) |
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
|
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
| def _write_callback(connection_id, data_buffer, data_length_pointer):
"""
SecureTransport write callback. This is called by ST to request that data
actually be sent on the network.
"""
wrapped_socket = None
try:
wrapped_socket = _connection_refs.get(connection_id)
if wrapped_sock... | [
"def",
"_write_callback",
"(",
"connection_id",
",",
"data_buffer",
",",
"data_length_pointer",
")",
":",
"wrapped_socket",
"=",
"None",
"try",
":",
"wrapped_socket",
"=",
"_connection_refs",
".",
"get",
"(",
"connection_id",
")",
"if",
"wrapped_socket",
"is",
"No... | [
258,
0
] | [
306,
43
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._raise_on_error | (self) |
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those exceptions.
It also correctly force... |
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those exceptions. | def _raise_on_error(self):
"""
A context manager that can be used to wrap calls that do I/O from
SecureTransport. If any of the I/O callbacks hit an exception, this
context manager will correctly propagate the exception after the fact.
This avoids silently swallowing those except... | [
"def",
"_raise_on_error",
"(",
"self",
")",
":",
"self",
".",
"_exception",
"=",
"None",
"# We explicitly don't catch around this yield because in the unlikely",
"# event that an exception was hit in the block we don't want to swallow",
"# it.",
"yield",
"if",
"self",
".",
"_exce... | [
343,
4
] | [
361,
27
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._set_ciphers | (self) |
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freaking nightmare.
|
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freaking nightmare.
| def _set_ciphers(self):
"""
Sets up the allowed ciphers. By default this matches the set in
util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
custom and doesn't allow changing at this time, mostly because parsing
OpenSSL cipher strings is going to be a freak... | [
"def",
"_set_ciphers",
"(",
"self",
")",
":",
"ciphers",
"=",
"(",
"Security",
".",
"SSLCipherSuite",
"*",
"len",
"(",
"CIPHER_SUITES",
")",
")",
"(",
"*",
"CIPHER_SUITES",
")",
"result",
"=",
"Security",
".",
"SSLSetEnabledCiphers",
"(",
"self",
".",
"con... | [
363,
4
] | [
374,
32
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket._custom_validate | (self, verify, trust_bundle) |
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
|
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
| def _custom_validate(self, verify, trust_bundle):
"""
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
"""
# If we disabled cert validation, just say: cool.
... | [
"def",
"_custom_validate",
"(",
"self",
",",
"verify",
",",
"trust_bundle",
")",
":",
"# If we disabled cert validation, just say: cool.",
"if",
"not",
"verify",
":",
"return",
"# We want data in memory, so load it up.",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"t... | [
376,
4
] | [
431,
13
] | python | en | ['en', 'error', 'th'] | False |
WrappedSocket.handshake | (
self,
server_hostname,
verify,
trust_bundle,
min_version,
max_version,
client_cert,
client_key,
client_key_passphrase,
) |
Actually performs the TLS handshake. This is run automatically by
wrapped socket, and shouldn't be needed in user code.
|
Actually performs the TLS handshake. This is run automatically by
wrapped socket, and shouldn't be needed in user code.
| def handshake(
self,
server_hostname,
verify,
trust_bundle,
min_version,
max_version,
client_cert,
client_key,
client_key_passphrase,
):
"""
Actually performs the TLS handshake. This is run automatically by
wrapped socke... | [
"def",
"handshake",
"(",
"self",
",",
"server_hostname",
",",
"verify",
",",
"trust_bundle",
",",
"min_version",
",",
"max_version",
",",
"client_cert",
",",
"client_key",
",",
"client_key_passphrase",
",",
")",
":",
"# First, we do the initial bits of connection setup.... | [
433,
4
] | [
520,
25
] | python | en | ['en', 'error', 'th'] | False |
SecureTransportContext.check_hostname | (self) |
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
|
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
| def check_hostname(self):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
return True | [
"def",
"check_hostname",
"(",
"self",
")",
":",
"return",
"True"
] | [
758,
4
] | [
763,
19
] | python | en | ['en', 'error', 'th'] | False |
SecureTransportContext.check_hostname | (self, value) |
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
|
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
| def check_hostname(self, value):
"""
SecureTransport cannot have its hostname checking disabled. For more,
see the comment on getpeercert() in this file.
"""
pass | [
"def",
"check_hostname",
"(",
"self",
",",
"value",
")",
":",
"pass"
] | [
766,
4
] | [
771,
12
] | python | en | ['en', 'error', 'th'] | False |
flock | (lockfile: Union[int, IO[Any]], shared: bool = False) | Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX. | Lock a file object using flock(2) for the duration of a 'with' statement. | def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]:
"""Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX."""
fcntl.flock(lockfile, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
try:
yie... | [
"def",
"flock",
"(",
"lockfile",
":",
"Union",
"[",
"int",
",",
"IO",
"[",
"Any",
"]",
"]",
",",
"shared",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"fcntl",
".",
"flock",
"(",
"lockfile",
",",
"fcntl",
".",
"LOCK_S... | [
9,
0
] | [
18,
44
] | python | en | ['en', 'en', 'en'] | True |
lockfile | (filename: str, shared: bool = False) | Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist. | Lock a file using flock(2) for the duration of a 'with' statement. | def lockfile(filename: str, shared: bool = False) -> Iterator[None]:
"""Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist."""
with open(filename, "w") as lock:
... | [
"def",
"lockfile",
"(",
"filename",
":",
"str",
",",
"shared",
":",
"bool",
"=",
"False",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"lock",
":",
"with",
"flock",
"(",
"lock",
",",
"share... | [
22,
0
] | [
30,
17
] | python | en | ['en', 'en', 'en'] | True |
TranslationTests.test_override_exit | (self) |
Test that the language restored is the one used when the function was
called, not the one used when the decorator was initialized. refs #23381
|
Test that the language restored is the one used when the function was
called, not the one used when the decorator was initialized. refs #23381
| def test_override_exit(self):
"""
Test that the language restored is the one used when the function was
called, not the one used when the decorator was initialized. refs #23381
"""
activate('fr')
@translation.override('pl')
def func_pl():
pass
... | [
"def",
"test_override_exit",
"(",
"self",
")",
":",
"activate",
"(",
"'fr'",
")",
"@",
"translation",
".",
"override",
"(",
"'pl'",
")",
"def",
"func_pl",
"(",
")",
":",
"pass",
"deactivate",
"(",
")",
"try",
":",
"activate",
"(",
"'en'",
")",
"func_pl... | [
94,
4
] | [
111,
24
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_lazy_objects | (self) |
Format string interpolation should work with *_lazy objects.
|
Format string interpolation should work with *_lazy objects.
| def test_lazy_objects(self):
"""
Format string interpolation should work with *_lazy objects.
"""
s = ugettext_lazy('Add %(name)s')
d = {'name': 'Ringo'}
self.assertEqual('Add Ringo', s % d)
with translation.override('de', deactivate=True):
self.assert... | [
"def",
"test_lazy_objects",
"(",
"self",
")",
":",
"s",
"=",
"ugettext_lazy",
"(",
"'Add %(name)s'",
")",
"d",
"=",
"{",
"'name'",
":",
"'Ringo'",
"}",
"self",
".",
"assertEqual",
"(",
"'Add Ringo'",
",",
"s",
"%",
"d",
")",
"with",
"translation",
".",
... | [
113,
4
] | [
133,
40
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_ungettext_lazy_long | (self) |
Regression test for #22820: int and long should be treated alike in ungettext_lazy.
|
Regression test for #22820: int and long should be treated alike in ungettext_lazy.
| def test_ungettext_lazy_long(self):
"""
Regression test for #22820: int and long should be treated alike in ungettext_lazy.
"""
result = ungettext_lazy('%(name)s has %(num)d good result', '%(name)s has %(num)d good results', 4)
self.assertEqual(result % {'name': 'Joe', 'num': 4},... | [
"def",
"test_ungettext_lazy_long",
"(",
"self",
")",
":",
"result",
"=",
"ungettext_lazy",
"(",
"'%(name)s has %(num)d good result'",
",",
"'%(name)s has %(num)d good results'",
",",
"4",
")",
"self",
".",
"assertEqual",
"(",
"result",
"%",
"{",
"'name'",
":",
"'Joe... | [
196,
4
] | [
204,
86
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_template_tags_pgettext | (self) |
Ensure that message contexts are taken into account the {% trans %} and
{% blocktrans %} template tags.
Refs #14806.
|
Ensure that message contexts are taken into account the {% trans %} and
{% blocktrans %} template tags.
Refs #14806.
| def test_template_tags_pgettext(self):
"""
Ensure that message contexts are taken into account the {% trans %} and
{% blocktrans %} template tags.
Refs #14806.
"""
trans_real._active = local()
trans_real._translations = {}
with translation.override('de'):
... | [
"def",
"test_template_tags_pgettext",
"(",
"self",
")",
":",
"trans_real",
".",
"_active",
"=",
"local",
"(",
")",
"trans_real",
".",
"_translations",
"=",
"{",
"}",
"with",
"translation",
".",
"override",
"(",
"'de'",
")",
":",
"# {% trans %} ------------------... | [
217,
4
] | [
339,
200
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_string_concat | (self) |
six.text_type(string_concat(...)) should not raise a TypeError - #4796
|
six.text_type(string_concat(...)) should not raise a TypeError - #4796
| def test_string_concat(self):
"""
six.text_type(string_concat(...)) should not raise a TypeError - #4796
"""
self.assertEqual('django', six.text_type(string_concat("dja", "ngo"))) | [
"def",
"test_string_concat",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"'django'",
",",
"six",
".",
"text_type",
"(",
"string_concat",
"(",
"\"dja\"",
",",
"\"ngo\"",
")",
")",
")"
] | [
341,
4
] | [
345,
78
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_empty_value | (self) |
Empty value must stay empty after being translated (#23196).
|
Empty value must stay empty after being translated (#23196).
| def test_empty_value(self):
"""
Empty value must stay empty after being translated (#23196).
"""
with translation.override('de'):
self.assertEqual("", ugettext(""))
self.assertEqual(str(""), gettext(str("")))
s = mark_safe("")
self.assertEq... | [
"def",
"test_empty_value",
"(",
"self",
")",
":",
"with",
"translation",
".",
"override",
"(",
"'de'",
")",
":",
"self",
".",
"assertEqual",
"(",
"\"\"",
",",
"ugettext",
"(",
"\"\"",
")",
")",
"self",
".",
"assertEqual",
"(",
"str",
"(",
"\"\"",
")",
... | [
347,
4
] | [
355,
44
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_safe_status | (self) |
Translating a string requiring no auto-escaping shouldn't change the "safe" status.
|
Translating a string requiring no auto-escaping shouldn't change the "safe" status.
| def test_safe_status(self):
"""
Translating a string requiring no auto-escaping shouldn't change the "safe" status.
"""
s = mark_safe(str('Password'))
self.assertEqual(SafeString, type(s))
with translation.override('de', deactivate=True):
self.assertEqual(Safe... | [
"def",
"test_safe_status",
"(",
"self",
")",
":",
"s",
"=",
"mark_safe",
"(",
"str",
"(",
"'Password'",
")",
")",
"self",
".",
"assertEqual",
"(",
"SafeString",
",",
"type",
"(",
"s",
")",
")",
"with",
"translation",
".",
"override",
"(",
"'de'",
",",
... | [
357,
4
] | [
369,
63
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_maclines | (self) |
Translations on files with mac or dos end of lines will be converted
to unix eof in .po catalogs, and they have to match when retrieved
|
Translations on files with mac or dos end of lines will be converted
to unix eof in .po catalogs, and they have to match when retrieved
| def test_maclines(self):
"""
Translations on files with mac or dos end of lines will be converted
to unix eof in .po catalogs, and they have to match when retrieved
"""
ca_translation = trans_real.translation('ca')
ca_translation._catalog['Mac\nEOF\n'] = 'Catalan Mac\nEOF... | [
"def",
"test_maclines",
"(",
"self",
")",
":",
"ca_translation",
"=",
"trans_real",
".",
"translation",
"(",
"'ca'",
")",
"ca_translation",
".",
"_catalog",
"[",
"'Mac\\nEOF\\n'",
"]",
"=",
"'Catalan Mac\\nEOF\\n'",
"ca_translation",
".",
"_catalog",
"[",
"'Win\\n... | [
371,
4
] | [
381,
78
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_to_locale | (self) |
Tests the to_locale function and the special case of Serbian Latin
(refs #12230 and r11299)
|
Tests the to_locale function and the special case of Serbian Latin
(refs #12230 and r11299)
| def test_to_locale(self):
"""
Tests the to_locale function and the special case of Serbian Latin
(refs #12230 and r11299)
"""
self.assertEqual(to_locale('en-us'), 'en_US')
self.assertEqual(to_locale('sr-lat'), 'sr_Lat') | [
"def",
"test_to_locale",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"to_locale",
"(",
"'en-us'",
")",
",",
"'en_US'",
")",
"self",
".",
"assertEqual",
"(",
"to_locale",
"(",
"'sr-lat'",
")",
",",
"'sr_Lat'",
")"
] | [
383,
4
] | [
389,
55
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_to_language | (self) |
Test the to_language function
|
Test the to_language function
| def test_to_language(self):
"""
Test the to_language function
"""
self.assertEqual(trans_real.to_language('en_US'), 'en-us')
self.assertEqual(trans_real.to_language('sr_Lat'), 'sr-lat') | [
"def",
"test_to_language",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"trans_real",
".",
"to_language",
"(",
"'en_US'",
")",
",",
"'en-us'",
")",
"self",
".",
"assertEqual",
"(",
"trans_real",
".",
"to_language",
"(",
"'sr_Lat'",
")",
",",
"'s... | [
391,
4
] | [
396,
68
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_bad_placeholder_1 | (self) |
Error in translation file should not crash template rendering
(%(person)s is translated as %(personne)s in fr.po)
Refs #16516.
|
Error in translation file should not crash template rendering
(%(person)s is translated as %(personne)s in fr.po)
Refs #16516.
| def test_bad_placeholder_1(self):
"""
Error in translation file should not crash template rendering
(%(person)s is translated as %(personne)s in fr.po)
Refs #16516.
"""
with translation.override('fr'):
t = Template('{% load i18n %}{% blocktrans %}My name is {{... | [
"def",
"test_bad_placeholder_1",
"(",
"self",
")",
":",
"with",
"translation",
".",
"override",
"(",
"'fr'",
")",
":",
"t",
"=",
"Template",
"(",
"'{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}'",
")",
"rendered",
"=",
"t",
".",
"render",
... | [
399,
4
] | [
408,
59
] | python | en | ['en', 'error', 'th'] | False |
TranslationTests.test_bad_placeholder_2 | (self) |
Error in translation file should not crash template rendering
(%(person) misses a 's' in fr.po, causing the string formatting to fail)
Refs #18393.
|
Error in translation file should not crash template rendering
(%(person) misses a 's' in fr.po, causing the string formatting to fail)
Refs #18393.
| def test_bad_placeholder_2(self):
"""
Error in translation file should not crash template rendering
(%(person) misses a 's' in fr.po, causing the string formatting to fail)
Refs #18393.
"""
with translation.override('fr'):
t = Template('{% load i18n %}{% block... | [
"def",
"test_bad_placeholder_2",
"(",
"self",
")",
":",
"with",
"translation",
".",
"override",
"(",
"'fr'",
")",
":",
"t",
"=",
"Template",
"(",
"'{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}'",
")",
"rendered",
"=",
"t",
".",
"ren... | [
411,
4
] | [
420,
65
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_parse_spec_http_header | (self) |
Testing HTTP header parsing. First, we test that we can parse the
values according to the spec (and that we extract all the pieces in
the right order).
|
Testing HTTP header parsing. First, we test that we can parse the
values according to the spec (and that we extract all the pieces in
the right order).
| def test_parse_spec_http_header(self):
"""
Testing HTTP header parsing. First, we test that we can parse the
values according to the spec (and that we extract all the pieces in
the right order).
"""
p = trans_real.parse_accept_lang_header
# Good headers.
s... | [
"def",
"test_parse_spec_http_header",
"(",
"self",
")",
":",
"p",
"=",
"trans_real",
".",
"parse_accept_lang_header",
"# Good headers.",
"self",
".",
"assertEqual",
"(",
"[",
"(",
"'de'",
",",
"1.0",
")",
"]",
",",
"p",
"(",
"'de'",
")",
")",
"self",
".",
... | [
908,
4
] | [
945,
43
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_parse_literal_http_header | (self) |
Now test that we parse a literal HTTP header correctly.
|
Now test that we parse a literal HTTP header correctly.
| def test_parse_literal_http_header(self):
"""
Now test that we parse a literal HTTP header correctly.
"""
g = get_language_from_request
r = self.rf.get('/')
r.COOKIES = {}
r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'}
self.assertEqual('pt-br', g(r))
... | [
"def",
"test_parse_literal_http_header",
"(",
"self",
")",
":",
"g",
"=",
"get_language_from_request",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"}",
"r",
".",
"META",
"=",
"{",
"'HTTP_ACCEPT_LANGUAGE'",
":"... | [
947,
4
] | [
996,
41
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_support_for_deprecated_chinese_language_codes | (self) |
Some browsers (Firefox, IE etc) use deprecated language codes. As these
language codes will be removed in Django 1.9, these will be incorrectly
matched. For example zh-tw (traditional) will be interpreted as zh-hans
(simplified), which is wrong. So we should also accept these deprecated... |
Some browsers (Firefox, IE etc) use deprecated language codes. As these
language codes will be removed in Django 1.9, these will be incorrectly
matched. For example zh-tw (traditional) will be interpreted as zh-hans
(simplified), which is wrong. So we should also accept these deprecated... | def test_support_for_deprecated_chinese_language_codes(self):
"""
Some browsers (Firefox, IE etc) use deprecated language codes. As these
language codes will be removed in Django 1.9, these will be incorrectly
matched. For example zh-tw (traditional) will be interpreted as zh-hans
... | [
"def",
"test_support_for_deprecated_chinese_language_codes",
"(",
"self",
")",
":",
"g",
"=",
"get_language_from_request",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"}",
"r",
".",
"META",
"=",
"{",
"'HTTP_ACCE... | [
1005,
4
] | [
1022,
41
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_backwards_compatibility | (self) |
While the old chinese language codes are being deprecated, they should
still work as before the new language codes were introduced.
refs #18419 -- this is explicitly for backwards compatibility and
should be removed in Django 1.9
|
While the old chinese language codes are being deprecated, they should
still work as before the new language codes were introduced. | def test_backwards_compatibility(self):
"""
While the old chinese language codes are being deprecated, they should
still work as before the new language codes were introduced.
refs #18419 -- this is explicitly for backwards compatibility and
should be removed in Django 1.9
... | [
"def",
"test_backwards_compatibility",
"(",
"self",
")",
":",
"g",
"=",
"get_language_from_request",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"}",
"r",
".",
"META",
"=",
"{",
"'HTTP_ACCEPT_LANGUAGE'",
":",
... | [
1033,
4
] | [
1048,
39
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_special_fallback_language | (self) |
Some languages may have special fallbacks that don't follow the simple
'fr-ca' -> 'fr' logic (notably Chinese codes).
|
Some languages may have special fallbacks that don't follow the simple
'fr-ca' -> 'fr' logic (notably Chinese codes).
| def test_special_fallback_language(self):
"""
Some languages may have special fallbacks that don't follow the simple
'fr-ca' -> 'fr' logic (notably Chinese codes).
"""
r = self.rf.get('/')
r.COOKIES = {}
r.META = {'HTTP_ACCEPT_LANGUAGE': 'zh-my,en'}
self.a... | [
"def",
"test_special_fallback_language",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"}",
"r",
".",
"META",
"=",
"{",
"'HTTP_ACCEPT_LANGUAGE'",
":",
"'zh-my,en'",
"}",
"self",
".",
"... | [
1050,
4
] | [
1058,
65
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_parse_language_cookie | (self) |
Now test that we parse language preferences stored in a cookie correctly.
|
Now test that we parse language preferences stored in a cookie correctly.
| def test_parse_language_cookie(self):
"""
Now test that we parse language preferences stored in a cookie correctly.
"""
g = get_language_from_request
r = self.rf.get('/')
r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'}
r.META = {}
self.assertEqual('pt... | [
"def",
"test_parse_language_cookie",
"(",
"self",
")",
":",
"g",
"=",
"get_language_from_request",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"settings",
".",
"LANGUAGE_COOKIE_NAME",
":",
"'pt-br'",
"}",
"r",
... | [
1060,
4
] | [
1092,
39
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_percent_formatting_in_blocktrans | (self) |
Test that using Python's %-formatting is properly escaped in blocktrans,
singular or plural
|
Test that using Python's %-formatting is properly escaped in blocktrans,
singular or plural
| def test_percent_formatting_in_blocktrans(self):
"""
Test that using Python's %-formatting is properly escaped in blocktrans,
singular or plural
"""
t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}")
t_plur = Templat... | [
"def",
"test_percent_formatting_in_blocktrans",
"(",
"self",
")",
":",
"t_sing",
"=",
"Template",
"(",
"\"{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}\"",
")",
"t_plur",
"=",
"Template",
"(",
"\"{% load i18n %}{% blocktrans count num as number... | [
1116,
4
] | [
1127,
116
] | python | en | ['en', 'error', 'th'] | False |
MiscTests.test_cache_resetting | (self) |
#14170 after setting LANGUAGE, cache should be cleared and languages
previously valid should not be used.
|
#14170 after setting LANGUAGE, cache should be cleared and languages
previously valid should not be used.
| def test_cache_resetting(self):
"""
#14170 after setting LANGUAGE, cache should be cleared and languages
previously valid should not be used.
"""
g = get_language_from_request
r = self.rf.get('/')
r.COOKIES = {}
r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'}
... | [
"def",
"test_cache_resetting",
"(",
"self",
")",
":",
"g",
"=",
"get_language_from_request",
"r",
"=",
"self",
".",
"rf",
".",
"get",
"(",
"'/'",
")",
"r",
".",
"COOKIES",
"=",
"{",
"}",
"r",
".",
"META",
"=",
"{",
"'HTTP_ACCEPT_LANGUAGE'",
":",
"'pt-b... | [
1129,
4
] | [
1140,
46
] | python | en | ['en', 'error', 'th'] | False |
TestLanguageInfo.test_fallback_language_code | (self) |
get_language_info return the first fallback language info if the lang_info
struct does not contain the 'name' key.
|
get_language_info return the first fallback language info if the lang_info
struct does not contain the 'name' key.
| def test_fallback_language_code(self):
"""
get_language_info return the first fallback language info if the lang_info
struct does not contain the 'name' key.
"""
li = get_language_info('zh-my')
self.assertEqual(li['code'], 'zh-hans')
li = get_language_info('zh-cn'... | [
"def",
"test_fallback_language_code",
"(",
"self",
")",
":",
"li",
"=",
"get_language_info",
"(",
"'zh-my'",
")",
"self",
".",
"assertEqual",
"(",
"li",
"[",
"'code'",
"]",
",",
"'zh-hans'",
")",
"li",
"=",
"get_language_info",
"(",
"'zh-cn'",
")",
"self",
... | [
1233,
4
] | [
1241,
45
] | python | en | ['en', 'error', 'th'] | False |
MultipleLocaleActivationTests.test_single_locale_activation | (self) |
Simple baseline behavior with one locale for all the supported i18n constructs.
|
Simple baseline behavior with one locale for all the supported i18n constructs.
| def test_single_locale_activation(self):
"""
Simple baseline behavior with one locale for all the supported i18n constructs.
"""
with translation.override('fr'):
self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui')
self.assertEqual(Template("{% ... | [
"def",
"test_single_locale_activation",
"(",
"self",
")",
":",
"with",
"translation",
".",
"override",
"(",
"'fr'",
")",
":",
"self",
".",
"assertEqual",
"(",
"Template",
"(",
"\"{{ _('Yes') }}\"",
")",
".",
"render",
"(",
"Context",
"(",
"{",
"}",
")",
")... | [
1257,
4
] | [
1264,
122
] | python | en | ['en', 'error', 'th'] | False |
TranslationFilesMissing.test_failure_finding_default_mo_files | (self) |
Ensure IOError is raised if the default language is unparseable.
Refs: #18192
|
Ensure IOError is raised if the default language is unparseable.
Refs: #18192
| def test_failure_finding_default_mo_files(self):
'''
Ensure IOError is raised if the default language is unparseable.
Refs: #18192
'''
self.patchGettextFind()
trans_real._translations = {}
self.assertRaises(IOError, activate, 'en') | [
"def",
"test_failure_finding_default_mo_files",
"(",
"self",
")",
":",
"self",
".",
"patchGettextFind",
"(",
")",
"trans_real",
".",
"_translations",
"=",
"{",
"}",
"self",
".",
"assertRaises",
"(",
"IOError",
",",
"activate",
",",
"'en'",
")"
] | [
1469,
4
] | [
1476,
50
] | python | en | ['en', 'error', 'th'] | False |
_find_all_simple | (path) |
Find all files under 'path'
|
Find all files under 'path'
| def _find_all_simple(path):
"""
Find all files under 'path'
"""
results = (
os.path.join(base, file)
for base, dirs, files in os.walk(path, followlinks=True)
for file in files
)
return filter(os.path.isfile, results) | [
"def",
"_find_all_simple",
"(",
"path",
")",
":",
"results",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"file",
")",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"followlinks",
"=",
"True",
... | [
223,
0
] | [
232,
42
] | python | en | ['en', 'error', 'th'] | False |
findall | (dir=os.curdir) |
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
|
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
| def findall(dir=os.curdir):
"""
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
"""
files = _find_all_simple(dir)
if dir == os.curdir:
make_rel = functools.partial(os.path.relpath, start=dir)
files = m... | [
"def",
"findall",
"(",
"dir",
"=",
"os",
".",
"curdir",
")",
":",
"files",
"=",
"_find_all_simple",
"(",
"dir",
")",
"if",
"dir",
"==",
"os",
".",
"curdir",
":",
"make_rel",
"=",
"functools",
".",
"partial",
"(",
"os",
".",
"path",
".",
"relpath",
... | [
235,
0
] | [
244,
22
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.find | (cls, where='.', exclude=(), include=('*',)) | Return a list all Python packages found within directory 'where'
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the appropriate local path syntax.
'exclude' is a sequence of ... | Return a list all Python packages found within directory 'where' | def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the ap... | [
"def",
"find",
"(",
"cls",
",",
"where",
"=",
"'.'",
",",
"exclude",
"=",
"(",
")",
",",
"include",
"=",
"(",
"'*'",
",",
")",
")",
":",
"return",
"list",
"(",
"cls",
".",
"_find_packages_iter",
"(",
"convert_path",
"(",
"where",
")",
",",
"cls",
... | [
55,
4
] | [
75,
41
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder._find_packages_iter | (cls, where, exclude, include) |
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
|
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
| def _find_packages_iter(cls, where, exclude, include):
"""
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
"""
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
... | [
"def",
"_find_packages_iter",
"(",
"cls",
",",
"where",
",",
"exclude",
",",
"include",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"where",
",",
"followlinks",
"=",
"True",
")",
":",
"# Copy dirs to iterate over it, t... | [
78,
4
] | [
103,
32
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder._looks_like_package | (path) | Does a directory look like a package? | Does a directory look like a package? | def _looks_like_package(path):
"""Does a directory look like a package?"""
return os.path.isfile(os.path.join(path, '__init__.py')) | [
"def",
"_looks_like_package",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'__init__.py'",
")",
")"
] | [
106,
4
] | [
108,
64
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder._build_filter | (*patterns) |
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
|
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
| def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns) | [
"def",
"_build_filter",
"(",
"*",
"patterns",
")",
":",
"return",
"lambda",
"name",
":",
"any",
"(",
"fnmatchcase",
"(",
"name",
",",
"pat",
"=",
"pat",
")",
"for",
"pat",
"in",
"patterns",
")"
] | [
111,
4
] | [
116,
79
] | python | en | ['en', 'error', 'th'] | False |
Command.__init__ | (self, dist, **kw) |
Construct the command for dist, updating
vars(self) with any keyword parameters.
|
Construct the command for dist, updating
vars(self) with any keyword parameters.
| def __init__(self, dist, **kw):
"""
Construct the command for dist, updating
vars(self) with any keyword parameters.
"""
_Command.__init__(self, dist)
vars(self).update(kw) | [
"def",
"__init__",
"(",
"self",
",",
"dist",
",",
"*",
"*",
"kw",
")",
":",
"_Command",
".",
"__init__",
"(",
"self",
",",
"dist",
")",
"vars",
"(",
"self",
")",
".",
"update",
"(",
"kw",
")"
] | [
178,
4
] | [
184,
29
] | python | en | ['en', 'error', 'th'] | False |
Command.ensure_string_list | (self, option) | r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
| r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
| def ensure_string_list(self, option):
r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
"""
val = getattr(self, ... | [
"def",
"ensure_string_list",
"(",
"self",
",",
"option",
")",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"option",
")",
"if",
"val",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"val",
",",
"string_types",
")",
":",
"setattr",
"(",
"self"... | [
196,
4
] | [
215,
36
] | python | en | ['en', 'en', 'en'] | True |
Command.send | (self, users: List[UserProfile]) | Sends one-use only links for resetting password to target users | Sends one-use only links for resetting password to target users | def send(self, users: List[UserProfile]) -> None:
"""Sends one-use only links for resetting password to target users"""
for user_profile in users:
context = {
"email": user_profile.delivery_email,
"reset_url": generate_password_reset_url(user_profile, default_... | [
"def",
"send",
"(",
"self",
",",
"users",
":",
"List",
"[",
"UserProfile",
"]",
")",
"->",
"None",
":",
"for",
"user_profile",
"in",
"users",
":",
"context",
"=",
"{",
"\"email\"",
":",
"user_profile",
".",
"delivery_email",
",",
"\"reset_url\"",
":",
"g... | [
41,
4
] | [
57,
13
] | python | en | ['en', 'en', 'en'] | True |
DeactivatedRealmTest.test_send_deactivated_realm | (self) |
rest_dispatch rejects requests in a deactivated realm, both /json and api
|
rest_dispatch rejects requests in a deactivated realm, both /json and api | def test_send_deactivated_realm(self) -> None:
"""
rest_dispatch rejects requests in a deactivated realm, both /json and api
"""
realm = get_realm("zulip")
do_deactivate_realm(get_realm("zulip"), acting_user=None)
result = self.client_post(
"/json/messages",... | [
"def",
"test_send_deactivated_realm",
"(",
"self",
")",
"->",
"None",
":",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"do_deactivate_realm",
"(",
"get_realm",
"(",
"\"zulip\"",
")",
",",
"acting_user",
"=",
"None",
")",
"result",
"=",
"self",
".",
"cl... | [
1033,
4
] | [
1084,
9
] | python | en | ['en', 'error', 'th'] | False |
DeactivatedRealmTest.test_fetch_api_key_deactivated_realm | (self) |
authenticated_json_view views fail in a deactivated realm
|
authenticated_json_view views fail in a deactivated realm | def test_fetch_api_key_deactivated_realm(self) -> None:
"""
authenticated_json_view views fail in a deactivated realm
"""
realm = get_realm("zulip")
user_profile = self.example_user("hamlet")
test_password = "abcd1234"
user_profile.set_password(test_password)
... | [
"def",
"test_fetch_api_key_deactivated_realm",
"(",
"self",
")",
"->",
"None",
":",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"",
")",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"test_password",
"=",
"\"abcd1234\"",
"user_profile",
".... | [
1086,
4
] | [
1102,
9
] | python | en | ['en', 'error', 'th'] | False |
DeactivatedRealmTest.test_webhook_deactivated_realm | (self) |
Using a webhook while in a deactivated realm fails
|
Using a webhook while in a deactivated realm fails | def test_webhook_deactivated_realm(self) -> None:
"""
Using a webhook while in a deactivated realm fails
"""
do_deactivate_realm(get_realm("zulip"), acting_user=None)
user_profile = self.example_user("hamlet")
api_key = get_api_key(user_profile)
url = f"/api/v1/e... | [
"def",
"test_webhook_deactivated_realm",
"(",
"self",
")",
"->",
"None",
":",
"do_deactivate_realm",
"(",
"get_realm",
"(",
"\"zulip\"",
")",
",",
"acting_user",
"=",
"None",
")",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"api_key... | [
1104,
4
] | [
1117,
9
] | python | en | ['en', 'error', 'th'] | False |
LoginRequiredTest.test_login_required | (self) |
Verifies the zulip_login_required decorator blocks deactivated users.
|
Verifies the zulip_login_required decorator blocks deactivated users.
| def test_login_required(self) -> None:
"""
Verifies the zulip_login_required decorator blocks deactivated users.
"""
user_profile = self.example_user("hamlet")
# Verify fails if logged-out
result = self.client_get("/accounts/accept_terms/")
self.assertEqual(resul... | [
"def",
"test_login_required",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"# Verify fails if logged-out",
"result",
"=",
"self",
".",
"client_get",
"(",
"\"/accounts/accept_terms/\"",
")",
"self",
... | [
1121,
4
] | [
1151,
49
] | python | en | ['en', 'error', 'th'] | False |
InactiveUserTest.test_send_deactivated_user | (self) |
rest_dispatch rejects requests from deactivated users, both /json and api
|
rest_dispatch rejects requests from deactivated users, both /json and api | def test_send_deactivated_user(self) -> None:
"""
rest_dispatch rejects requests from deactivated users, both /json and api
"""
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
do_deactivate_user(user_profile, acting_user=None)
result = s... | [
"def",
"test_send_deactivated_user",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"self",
".",
"login_user",
"(",
"user_profile",
")",
"do_deactivate_user",
"(",
"user_profile",
",",
"acting_user",
... | [
1185,
4
] | [
1231,
90
] | python | en | ['en', 'error', 'th'] | False |
InactiveUserTest.test_fetch_api_key_deactivated_user | (self) |
authenticated_json_view views fail with a deactivated user
|
authenticated_json_view views fail with a deactivated user | def test_fetch_api_key_deactivated_user(self) -> None:
"""
authenticated_json_view views fail with a deactivated user
"""
user_profile = self.example_user("hamlet")
email = user_profile.delivery_email
test_password = "abcd1234"
user_profile.set_password(test_pass... | [
"def",
"test_fetch_api_key_deactivated_user",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"email",
"=",
"user_profile",
".",
"delivery_email",
"test_password",
"=",
"\"abcd1234\"",
"user_profile",
".... | [
1233,
4
] | [
1248,
90
] | python | en | ['en', 'error', 'th'] | False |
InactiveUserTest.test_login_deactivated_user | (self) |
logging in fails with an inactive user
|
logging in fails with an inactive user | def test_login_deactivated_user(self) -> None:
"""
logging in fails with an inactive user
"""
user_profile = self.example_user("hamlet")
do_deactivate_user(user_profile, acting_user=None)
result = self.login_with_return(self.example_email("hamlet"))
self.assert_... | [
"def",
"test_login_deactivated_user",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"do_deactivate_user",
"(",
"user_profile",
",",
"acting_user",
"=",
"None",
")",
"result",
"=",
"self",
".",
"l... | [
1250,
4
] | [
1259,
76
] | python | en | ['en', 'error', 'th'] | False |
InactiveUserTest.test_login_deactivated_mirror_dummy | (self) |
logging in fails with an inactive user
|
logging in fails with an inactive user | def test_login_deactivated_mirror_dummy(self) -> None:
"""
logging in fails with an inactive user
"""
user_profile = self.example_user("hamlet")
user_profile.is_mirror_dummy = True
user_profile.save()
password = initial_password(user_profile.delivery_email)
... | [
"def",
"test_login_deactivated_mirror_dummy",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"user_profile",
".",
"is_mirror_dummy",
"=",
"True",
"user_profile",
".",
"save",
"(",
")",
"password",
"... | [
1261,
4
] | [
1300,
79
] | python | en | ['en', 'error', 'th'] | False |
InactiveUserTest.test_webhook_deactivated_user | (self) |
Deactivated users can't use webhooks
|
Deactivated users can't use webhooks | def test_webhook_deactivated_user(self) -> None:
"""
Deactivated users can't use webhooks
"""
user_profile = self.example_user("hamlet")
do_deactivate_user(user_profile, acting_user=None)
api_key = get_api_key(user_profile)
url = f"/api/v1/external/jira?api_key=... | [
"def",
"test_webhook_deactivated_user",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"do_deactivate_user",
"(",
"user_profile",
",",
"acting_user",
"=",
"None",
")",
"api_key",
"=",
"get_api_key",
... | [
1302,
4
] | [
1314,
90
] | python | en | ['en', 'error', 'th'] | False |
TestUserAgentParsing.test_user_agent_parsing | (self) | Test for our user agent parsing logic, using a large data set. | Test for our user agent parsing logic, using a large data set. | def test_user_agent_parsing(self) -> None:
"""Test for our user agent parsing logic, using a large data set."""
user_agents_parsed: Dict[str, int] = defaultdict(int)
user_agents_path = os.path.join(
settings.DEPLOY_ROOT, "zerver/tests/fixtures/user_agents_unique"
)
wi... | [
"def",
"test_user_agent_parsing",
"(",
"self",
")",
"->",
"None",
":",
"user_agents_parsed",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"defaultdict",
"(",
"int",
")",
"user_agents_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"DE... | [
1954,
4
] | [
1969,
61
] | python | en | ['en', 'en', 'en'] | True |
make_contour | (polygon_points) |
method 1
|
method 1
| def make_contour(polygon_points):
"""
method 1
"""
# position vertices on circle and add noise
r = np.random.uniform(128, 256)
noise = r / 3
points = []
for n in range(polygon_points):
phi = 2 * np.pi / polygon_points * n
x = r * np.cos(phi)
y = r * np.sin(phi)
... | [
"def",
"make_contour",
"(",
"polygon_points",
")",
":",
"# position vertices on circle and add noise",
"r",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"128",
",",
"256",
")",
"noise",
"=",
"r",
"/",
"3",
"points",
"=",
"[",
"]",
"for",
"n",
"in",
"ra... | [
106,
0
] | [
123,
17
] | python | en | ['en', 'error', 'th'] | False |
remove_one_line | (line) |
method a
|
method a
| def remove_one_line(line):
"""
method a
"""
start = np.random.randint(0, len(line) - 1)
line = line[start:-1] + line[0:start]
return line, start | [
"def",
"remove_one_line",
"(",
"line",
")",
":",
"start",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"line",
")",
"-",
"1",
")",
"line",
"=",
"line",
"[",
"start",
":",
"-",
"1",
"]",
"+",
"line",
"[",
"0",
":",
"sta... | [
180,
0
] | [
187,
22
] | python | en | ['en', 'error', 'th'] | False |
shuffle_line | (line) |
method b
|
method b
| def shuffle_line(line):
"""
method b
"""
# get angle and radii
angles = []
radii = []
line.append(line[1])
for i in range(len(line) - 2):
angle, radius = dist_angle(line[i], line[i + 1], line[i + 2])
angles.append(angle)
radii.append(radius)
# shuffle
np.... | [
"def",
"shuffle_line",
"(",
"line",
")",
":",
"# get angle and radii",
"angles",
"=",
"[",
"]",
"radii",
"=",
"[",
"]",
"line",
".",
"append",
"(",
"line",
"[",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"line",
")",
"-",
"2",
")"... | [
210,
0
] | [
250,
25
] | python | en | ['en', 'error', 'th'] | False |
make_contour_both | (polygon_points) |
method c
|
method c
| def make_contour_both(polygon_points):
"""
method c
"""
diff = np.random.rand() * 15 * 4 + 10 * 4 # differenz zwischen 20px und 50px
minr = 0
radius = 256 - minr
while 1:
radii = np.random.random(polygon_points) * radius + minr
radii_closed = np.copy(radii)
phis =... | [
"def",
"make_contour_both",
"(",
"polygon_points",
")",
":",
"diff",
"=",
"np",
".",
"random",
".",
"rand",
"(",
")",
"*",
"15",
"*",
"4",
"+",
"10",
"*",
"4",
"# differenz zwischen 20px und 50px",
"minr",
"=",
"0",
"radius",
"=",
"256",
"-",
"minr",
"... | [
253,
0
] | [
325,
32
] | python | en | ['en', 'error', 'th'] | False |
set_seed_rep | (method) |
Set seed and number of repetitions. Both depend on the type of the data set. For example a different seed is used
for test and training set
:param method: type of the data set [string]
:return: number of [int]
|
Set seed and number of repetitions. Both depend on the type of the data set. For example a different seed is used
for test and training set
:param method: type of the data set [string]
:return: number of [int]
| def set_seed_rep(method):
"""
Set seed and number of repetitions. Both depend on the type of the data set. For example a different seed is used
for test and training set
:param method: type of the data set [string]
:return: number of [int]
"""
if method.endswith("val"):
np.random.see... | [
"def",
"set_seed_rep",
"(",
"method",
")",
":",
"if",
"method",
".",
"endswith",
"(",
"\"val\"",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"0",
")",
"num_rep",
"=",
"200",
"elif",
"method",
".",
"endswith",
"(",
"\"test\"",
")",
":",
"np",
"... | [
541,
0
] | [
557,
18
] | python | en | ['en', 'error', 'th'] | False |
set1_otf | (closedness) |
This function can be used to generate a training image of set1 on-the-fly
:param closedness: label, either 0 (closed) or 1 (open) [int]
:return: line-drawing
|
This function can be used to generate a training image of set1 on-the-fly
:param closedness: label, either 0 (closed) or 1 (open) [int]
:return: line-drawing
| def set1_otf(closedness):
"""
This function can be used to generate a training image of set1 on-the-fly
:param closedness: label, either 0 (closed) or 1 (open) [int]
:return: line-drawing
"""
polygon_points = np.random.randint(3, 10)
open_lines, closed_lines = define_image(polygon_points, 1)... | [
"def",
"set1_otf",
"(",
"closedness",
")",
":",
"polygon_points",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"3",
",",
"10",
")",
"open_lines",
",",
"closed_lines",
"=",
"define_image",
"(",
"polygon_points",
",",
"1",
")",
"if",
"closedness",
"==",
... | [
565,
0
] | [
576,
40
] | python | en | ['en', 'error', 'th'] | False |
make_full_dataset | (top_dir, set_num, debug) |
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 1-13, 24, 25]
:param debug: generate only seven images [bool]
|
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 1-13, 24, 25]
:param debug: generate only seven images [bool]
| def make_full_dataset(top_dir, set_num, debug):
"""
generate and save the full data set for a specified variation
:param top_dir: where to save the images [string]
:param set_num: number that specifies the variation [one of: 1-13, 24, 25]
:param debug: generate only seven images [bool]
"""
... | [
"def",
"make_full_dataset",
"(",
"top_dir",
",",
"set_num",
",",
"debug",
")",
":",
"save",
"=",
"True",
"stim_folder",
"=",
"top_dir",
"+",
"\"set\"",
"+",
"str",
"(",
"set_num",
")",
"+",
"\"/linedrawing/\"",
"if",
"set_num",
"==",
"1",
":",
"methods",
... | [
579,
0
] | [
669,
25
] | python | en | ['en', 'error', 'th'] | False |
get_isolated_page | (request: HttpRequest) | Accept a GET param `?nav=no` to render an isolated, navless page. | Accept a GET param `?nav=no` to render an isolated, navless page. | def get_isolated_page(request: HttpRequest) -> bool:
"""Accept a GET param `?nav=no` to render an isolated, navless page."""
return request.GET.get("nav") == "no" | [
"def",
"get_isolated_page",
"(",
"request",
":",
"HttpRequest",
")",
"->",
"bool",
":",
"return",
"request",
".",
"GET",
".",
"get",
"(",
"\"nav\"",
")",
"==",
"\"no\""
] | [
88,
0
] | [
90,
41
] | python | en | ['en', 'en', '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... | [
41,
0
] | [
71,
31
] | python | en | ['en', 'en', 'en'] | True |
main | (_) | Classify all images using the sample defense. | Classify all images using the sample defense. | def main(_):
"""Classify all images using the sample defense."""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
nb_classes = 1001
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
# Prepare graph
x_input = tf.placeholder(tf.float32,... | [
"def",
"main",
"(",
"_",
")",
":",
"batch_shape",
"=",
"[",
"FLAGS",
".",
"batch_size",
",",
"FLAGS",
".",
"image_height",
",",
"FLAGS",
".",
"image_width",
",",
"3",
"]",
"nb_classes",
"=",
"1001",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf"... | [
74,
0
] | [
105,
75
] | python | en | ['en', 'en', 'en'] | True |
to_usd | (my_price) |
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
|
Converts a numeric value to usd-formatted string, for printing and display purposes. | def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" | [
"def",
"to_usd",
"(",
"my_price",
")",
":",
"return",
"f\"${my_price:,.2f}\""
] | [
10,
0
] | [
20,
30
] | python | en | ['en', 'error', 'th'] | False |
calculate_rectangle_area | (length, width) |
Computes the area of a rectangle, given its length and width.
Params:
length (int or float) like 10
width (int or float) like 3
Examples:
calculate_rectangle_area(10, 3)
calculate_rectangle_area(length=10, width=3)
calculate_rectangle_area(width=3, length=10)
|
Computes the area of a rectangle, given its length and width. | def calculate_rectangle_area(length, width):
"""
Computes the area of a rectangle, given its length and width.
Params:
length (int or float) like 10
width (int or float) like 3
Examples:
calculate_rectangle_area(10, 3)
calculate_rectangle_area(length=10, width=3)
... | [
"def",
"calculate_rectangle_area",
"(",
"length",
",",
"width",
")",
":",
"return",
"length",
"*",
"width"
] | [
23,
0
] | [
36,
25
] | python | en | ['en', 'error', 'th'] | False |
calculate_triangle_area | (base, height) |
Computes the area of a triangle, given its base and height.
Params:
base (int or float) like 8
height (int or float) like 6
Examples:
calculate_triangle_area(8, 6)
calculate_triangle_area(base=8, height=6)
calculate_triangle_area(height=6, base=8)
|
Computes the area of a triangle, given its base and height. | def calculate_triangle_area(base, height):
"""
Computes the area of a triangle, given its base and height.
Params:
base (int or float) like 8
height (int or float) like 6
Examples:
calculate_triangle_area(8, 6)
calculate_triangle_area(base=8, height=6)
calculate... | [
"def",
"calculate_triangle_area",
"(",
"base",
",",
"height",
")",
":",
"return",
"0.5",
"*",
"base",
"*",
"height"
] | [
39,
0
] | [
52,
30
] | python | en | ['en', 'error', 'th'] | False |
_wrap | (f) |
Wraps a callable `f` in a function that warns that the function is deprecated.
|
Wraps a callable `f` in a function that warns that the function is deprecated.
| def _wrap(f):
"""
Wraps a callable `f` in a function that warns that the function is deprecated.
"""
def wrapper(*args, **kwargs):
"""
Issues a deprecation warning and passes through the arguments.
"""
warnings.warn(
str(f)
+ " is deprecated. Swit... | [
"def",
"_wrap",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Issues a deprecation warning and passes through the arguments.\n \"\"\"",
"warnings",
".",
"warn",
"(",
"str",
"(",
"f",
")",
"+",
... | [
20,
0
] | [
37,
18
] | python | en | ['en', 'error', 'th'] | False |
reduce_function | (
op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None
) |
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the defa... |
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param input_tensor: The tensor to reduce. Should have numeric type.
:param axis: The dimensions to reduce. If None (the defa... | def reduce_function(
op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None
):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:param inpu... | [
"def",
"reduce_function",
"(",
"op_func",
",",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"None",
",",
"name",
"=",
"None",
",",
"reduction_indices",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`reduce_function` is deprecated a... | [
48,
0
] | [
76,
14
] | python | en | ['en', 'error', 'th'] | False |
softmax_cross_entropy_with_logits | (sentinel=None, labels=None, logits=None, dim=-1) |
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
|
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
| def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1):
"""
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle
deprecated warning
"""
# Make sure that all arguments were passed as named arguments.
if sentinel is not None:
name = "softmax_c... | [
"def",
"softmax_cross_entropy_with_logits",
"(",
"sentinel",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"logits",
"=",
"None",
",",
"dim",
"=",
"-",
"1",
")",
":",
"# Make sure that all arguments were passed as named arguments.",
"if",
"sentinel",
"is",
"not",
... | [
79,
0
] | [
104,
15
] | python | en | ['en', 'error', 'th'] | False |
get_opening_hours | (time_zone, periods, begin, end=None) |
Returns opening and closing times for a given date range
Return value is a dict where keys are days on the range
and values are a list of Day objects for that day's active period
containing opening and closing hours
:rtype : dict[str, list[dict[str, datetime.datetime]]]
:type periods:... |
Returns opening and closing times for a given date range | def get_opening_hours(time_zone, periods, begin, end=None):
"""
Returns opening and closing times for a given date range
Return value is a dict where keys are days on the range
and values are a list of Day objects for that day's active period
containing opening and closing hours
:rtype... | [
"def",
"get_opening_hours",
"(",
"time_zone",
",",
"periods",
",",
"begin",
",",
"end",
"=",
"None",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"time_zone",
")",
"if",
"begin",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"begin",
",",
... | [
31,
0
] | [
101,
16
] | python | en | ['en', 'error', 'th'] | False |
Period.save_closedness | (self) |
Recalculate and save the `closed`ness state for the day.
|
Recalculate and save the `closed`ness state for the day.
| def save_closedness(self):
"""
Recalculate and save the `closed`ness state for the day.
"""
self._check_closed()
self.save(force_update=True, update_fields=("closed",)) | [
"def",
"save_closedness",
"(",
"self",
")",
":",
"self",
".",
"_check_closed",
"(",
")",
"self",
".",
"save",
"(",
"force_update",
"=",
"True",
",",
"update_fields",
"=",
"(",
"\"closed\"",
",",
")",
")"
] | [
163,
4
] | [
168,
63
] | python | en | ['en', 'error', 'th'] | False |
reset_urlconf | (sender, **kwargs) | Reset the URLconf after each request is finished. | Reset the URLconf after each request is finished. | def reset_urlconf(sender, **kwargs):
"""Reset the URLconf after each request is finished."""
set_urlconf(None) | [
"def",
"reset_urlconf",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"set_urlconf",
"(",
"None",
")"
] | [
160,
0
] | [
162,
21
] | python | en | ['en', 'en', 'en'] | True |
BaseHandler.load_middleware | (self) |
Populate middleware lists from settings.MIDDLEWARE.
Must be called after the environment is fixed (see __call__ in subclasses).
|
Populate middleware lists from settings.MIDDLEWARE. | def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE.
Must be called after the environment is fixed (see __call__ in subclasses).
"""
self._view_middleware = []
self._template_response_middleware = []
self._exception_middleware = []
... | [
"def",
"load_middleware",
"(",
"self",
")",
":",
"self",
".",
"_view_middleware",
"=",
"[",
"]",
"self",
".",
"_template_response_middleware",
"=",
"[",
"]",
"self",
".",
"_exception_middleware",
"=",
"[",
"]",
"handler",
"=",
"convert_exception_to_response",
"(... | [
22,
4
] | [
61,
40
] | python | en | ['en', 'error', 'th'] | False |
BaseHandler.get_response | (self, request) | Return an HttpResponse object for the given HttpRequest. | Return an HttpResponse object for the given HttpRequest. | def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
response._resource_closers.append(request.close)
if r... | [
"def",
"get_response",
"(",
"self",
",",
"request",
")",
":",
"# Setup default url resolver for this thread",
"set_urlconf",
"(",
"settings",
".",
"ROOT_URLCONF",
")",
"response",
"=",
"self",
".",
"_middleware_chain",
"(",
"request",
")",
"response",
".",
"_resourc... | [
70,
4
] | [
82,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseHandler._get_response | (self, request) |
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
|
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
| def _get_response(self, request):
"""
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
"""
response = None
if hasattr(request, 'urlconf'):
... | [
"def",
"_get_response",
"(",
"self",
",",
"request",
")",
":",
"response",
"=",
"None",
"if",
"hasattr",
"(",
"request",
",",
"'urlconf'",
")",
":",
"urlconf",
"=",
"request",
".",
"urlconf",
"set_urlconf",
"(",
"urlconf",
")",
"resolver",
"=",
"get_resolv... | [
84,
4
] | [
146,
23
] | python | en | ['en', 'error', 'th'] | False |
BaseHandler.process_exception_by_middleware | (self, exception, request) |
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
|
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
| def process_exception_by_middleware(self, exception, request):
"""
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
"""
for middleware_method in self._exception_middleware:
response = middleware_method(re... | [
"def",
"process_exception_by_middleware",
"(",
"self",
",",
"exception",
",",
"request",
")",
":",
"for",
"middleware_method",
"in",
"self",
".",
"_exception_middleware",
":",
"response",
"=",
"middleware_method",
"(",
"request",
",",
"exception",
")",
"if",
"resp... | [
148,
4
] | [
157,
13
] | python | en | ['en', 'error', 'th'] | False |
main | (argv=None) |
Make a confidence report and save it to disk.
|
Make a confidence report and save it to disk.
| def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print(filepath)
make_confidence_report_bundled(
filepath=filepath,
test_start=FLAGS.test_start,
t... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"print",
"(",
"filepath",
")",
"make_confidence_report_bundled",
"(",
"filep... | [
42,
0
] | [
59,
5
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_custom_modelforms_with_fields_fieldsets | (self) |
# Regression test for #8027: custom ModelForms with fields/fieldsets
|
# Regression test for #8027: custom ModelForms with fields/fieldsets
| def test_custom_modelforms_with_fields_fieldsets(self):
"""
# Regression test for #8027: custom ModelForms with fields/fieldsets
"""
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
ValidFields.val... | [
"def",
"test_custom_modelforms_with_fields_fieldsets",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"module",
"=",
"'django.contrib.admin.options'",
"... | [
50,
4
] | [
56,
38
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_custom_get_form_with_fieldsets | (self) |
Ensure that the fieldsets validation is skipped when the ModelAdmin.get_form() method
is overridden.
Refs #19445.
|
Ensure that the fieldsets validation is skipped when the ModelAdmin.get_form() method
is overridden.
Refs #19445.
| def test_custom_get_form_with_fieldsets(self):
"""
Ensure that the fieldsets validation is skipped when the ModelAdmin.get_form() method
is overridden.
Refs #19445.
"""
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', module='django... | [
"def",
"test_custom_get_form_with_fieldsets",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"module",
"=",
"'django.contrib.admin.options'",
")",
"Va... | [
58,
4
] | [
66,
45
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_exclude_values | (self) |
Tests for basic validation of 'exclude' option values (#12689)
|
Tests for basic validation of 'exclude' option values (#12689)
| def test_exclude_values(self):
"""
Tests for basic validation of 'exclude' option values (#12689)
"""
class ExcludedFields1(admin.ModelAdmin):
exclude = ('foo')
self.assertRaisesMessage(ImproperlyConfigured,
"'ExcludedFields1.exclude' must be a list or tu... | [
"def",
"test_exclude_values",
"(",
"self",
")",
":",
"class",
"ExcludedFields1",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"exclude",
"=",
"(",
"'foo'",
")",
"self",
".",
"assertRaisesMessage",
"(",
"ImproperlyConfigured",
",",
"\"'ExcludedFields1.exclude' must be ... | [
68,
4
] | [
78,
17
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_exclude_inline_model_admin | (self) |
# Regression test for #9932 - exclude in InlineModelAdmin
# should not contain the ForeignKey field used in ModelAdmin.model
|
# Regression test for #9932 - exclude in InlineModelAdmin
# should not contain the ForeignKey field used in ModelAdmin.model
| def test_exclude_inline_model_admin(self):
"""
# Regression test for #9932 - exclude in InlineModelAdmin
# should not contain the ForeignKey field used in ModelAdmin.model
"""
class SongInline(admin.StackedInline):
model = Song
exclude = ['album']
... | [
"def",
"test_exclude_inline_model_admin",
"(",
"self",
")",
":",
"class",
"SongInline",
"(",
"admin",
".",
"StackedInline",
")",
":",
"model",
"=",
"Song",
"exclude",
"=",
"[",
"'album'",
"]",
"class",
"AlbumAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",... | [
103,
4
] | [
119,
18
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_app_label_in_admin_validation | (self) |
Regression test for #15669 - Include app label in admin validation messages
|
Regression test for #15669 - Include app label in admin validation messages
| def test_app_label_in_admin_validation(self):
"""
Regression test for #15669 - Include app label in admin validation messages
"""
class RawIdNonexistingAdmin(admin.ModelAdmin):
raw_id_fields = ('nonexisting',)
with warnings.catch_warnings(record=True):
wa... | [
"def",
"test_app_label_in_admin_validation",
"(",
"self",
")",
":",
"class",
"RawIdNonexistingAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"raw_id_fields",
"=",
"(",
"'nonexisting'",
",",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
... | [
121,
4
] | [
133,
22
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_fk_exclusion | (self) |
Regression test for #11709 - when testing for fk excluding (when exclude is
given) make sure fk_name is honored or things blow up when there is more
than one fk to the parent model.
|
Regression test for #11709 - when testing for fk excluding (when exclude is
given) make sure fk_name is honored or things blow up when there is more
than one fk to the parent model.
| def test_fk_exclusion(self):
"""
Regression test for #11709 - when testing for fk excluding (when exclude is
given) make sure fk_name is honored or things blow up when there is more
than one fk to the parent model.
"""
class TwoAlbumFKAndAnEInline(admin.TabularInline):
... | [
"def",
"test_fk_exclusion",
"(",
"self",
")",
":",
"class",
"TwoAlbumFKAndAnEInline",
"(",
"admin",
".",
"TabularInline",
")",
":",
"model",
"=",
"TwoAlbumFKAndAnE",
"exclude",
"=",
"(",
"\"e\"",
",",
")",
"fk_name",
"=",
"\"album1\"",
"class",
"MyAdmin",
"(",... | [
135,
4
] | [
151,
35
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_graceful_m2m_fail | (self) |
Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
specifies the 'through' option is included in the 'fields' or the 'fieldsets'
ModelAdmin options.
|
Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
specifies the 'through' option is included in the 'fields' or the 'fieldsets'
ModelAdmin options.
| def test_graceful_m2m_fail(self):
"""
Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
specifies the 'through' option is included in the 'fields' or the 'fieldsets'
ModelAdmin options.
"""
class BookAdmin(admin.ModelAdmin):
field... | [
"def",
"test_graceful_m2m_fail",
"(",
"self",
")",
":",
"class",
"BookAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"fields",
"=",
"[",
"'authors'",
"]",
"self",
".",
"assertRaisesMessage",
"(",
"ImproperlyConfigured",
",",
"\"'BookAdmin.fields' can't include t... | [
254,
4
] | [
267,
17
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_explicit_through_override | (self) |
Regression test for #12209 -- If the explicitly provided through model
is specified as a string, the admin should still be able use
Model.m2m_field.through
|
Regression test for #12209 -- If the explicitly provided through model
is specified as a string, the admin should still be able use
Model.m2m_field.through
| def test_explicit_through_override(self):
"""
Regression test for #12209 -- If the explicitly provided through model
is specified as a string, the admin should still be able use
Model.m2m_field.through
"""
class AuthorsInline(admin.TabularInline):
model = Boo... | [
"def",
"test_explicit_through_override",
"(",
"self",
")",
":",
"class",
"AuthorsInline",
"(",
"admin",
".",
"TabularInline",
")",
":",
"model",
"=",
"Book",
".",
"authors",
".",
"through",
"class",
"BookAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"in... | [
299,
4
] | [
316,
36
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_non_model_fields | (self) |
Regression for ensuring ModelAdmin.fields can contain non-model fields
that broke with r11737
|
Regression for ensuring ModelAdmin.fields can contain non-model fields
that broke with r11737
| def test_non_model_fields(self):
"""
Regression for ensuring ModelAdmin.fields can contain non-model fields
that broke with r11737
"""
class SongForm(forms.ModelForm):
extra_data = forms.CharField()
class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
f... | [
"def",
"test_non_model_fields",
"(",
"self",
")",
":",
"class",
"SongForm",
"(",
"forms",
".",
"ModelForm",
")",
":",
"extra_data",
"=",
"forms",
".",
"CharField",
"(",
")",
"class",
"FieldsOnFormOnlyAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"form",... | [
318,
4
] | [
332,
48
] | python | en | ['en', 'error', 'th'] | False |
ValidationTestCase.test_non_model_first_field | (self) |
Regression for ensuring ModelAdmin.field can handle first elem being a
non-model field (test fix for UnboundLocalError introduced with r16225).
|
Regression for ensuring ModelAdmin.field can handle first elem being a
non-model field (test fix for UnboundLocalError introduced with r16225).
| def test_non_model_first_field(self):
"""
Regression for ensuring ModelAdmin.field can handle first elem being a
non-model field (test fix for UnboundLocalError introduced with r16225).
"""
class SongForm(forms.ModelForm):
extra_data = forms.CharField()
c... | [
"def",
"test_non_model_first_field",
"(",
"self",
")",
":",
"class",
"SongForm",
"(",
"forms",
".",
"ModelForm",
")",
":",
"extra_data",
"=",
"forms",
".",
"CharField",
"(",
")",
"class",
"Meta",
":",
"model",
"=",
"Song",
"fields",
"=",
"'__all__'",
"clas... | [
334,
4
] | [
352,
48
] | python | en | ['en', 'error', 'th'] | False |
get_extract_command_template | (filename) | Returns extraction command based on the filename extension. | Returns extraction command based on the filename extension. | def get_extract_command_template(filename):
"""Returns extraction command based on the filename extension."""
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None | [
"def",
"get_extract_command_template",
"(",
"filename",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"EXTRACT_COMMAND",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"k",
")",
":",
"return",
"v",
"return",
"None"
] | [
41,
0
] | [
46,
15
] | python | en | ['en', 'en', 'en'] | True |
shell_call | (command, **kwargs) | Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '${B}'], A='src_file', B='ds... | Calls shell command with parameter substitution. | def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call([... | [
"def",
"shell_call",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"list",
"(",
"command",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"command",
")",
")",
":",
"m",
"=",
"CMD_VARIABLE_RE",
".",
"match",
"(",
"command",
"[... | [
49,
0
] | [
71,
40
] | python | en | ['en', 'en', 'en'] | True |
make_directory_writable | (dirname) | Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be abl... | Makes directory readable and writable by everybody. | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user ... | [
"def",
"make_directory_writable",
"(",
"dirname",
")",
":",
"retval",
"=",
"shell_call",
"(",
"[",
"\"docker\"",
",",
"\"run\"",
",",
"\"-v\"",
",",
"\"{0}:/output_dir\"",
".",
"format",
"(",
"dirname",
")",
",",
"\"busybox:1.27.2\"",
",",
"\"chmod\"",
",",
"\... | [
74,
0
] | [
103,
17
] | python | en | ['en', 'en', 'en'] | True |
load_defense_output | (filename) | Loads output of defense from given file. | Loads output of defense from given file. | def load_defense_output(filename):
"""Loads output of defense from given file."""
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if not image_filename.endswith(".png"):
image_filename += ".p... | [
"def",
"load_defense_output",
"(",
"filename",
")",
":",
"result",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
":",
"try",
":",
"image_filename",
"=",
"row",
"[",
"0"... | [
106,
0
] | [
119,
17
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator.__init__ | (self, temp_dir, use_gpu) | Initializes instance of SubmissionValidator.
Args:
temp_dir: temporary working directory
use_gpu: whether to use GPU
| Initializes instance of SubmissionValidator. | def __init__(self, temp_dir, use_gpu):
"""Initializes instance of SubmissionValidator.
Args:
temp_dir: temporary working directory
use_gpu: whether to use GPU
"""
self._temp_dir = temp_dir
self._use_gpu = use_gpu
self._tmp_extracted_dir = os.path.join... | [
"def",
"__init__",
"(",
"self",
",",
"temp_dir",
",",
"use_gpu",
")",
":",
"self",
".",
"_temp_dir",
"=",
"temp_dir",
"self",
".",
"_use_gpu",
"=",
"use_gpu",
"self",
".",
"_tmp_extracted_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_t... | [
125,
4
] | [
137,
72
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._prepare_temp_dir | (self) | Cleans up and prepare temporary directory. | Cleans up and prepare temporary directory. | def _prepare_temp_dir(self):
"""Cleans up and prepare temporary directory."""
shell_call(["rm", "-rf", os.path.join(self._temp_dir, "*")])
# NOTE: we do not create self._extracted_submission_dir
# this is intentional because self._tmp_extracted_dir or it's subdir
# will be rename... | [
"def",
"_prepare_temp_dir",
"(",
"self",
")",
":",
"shell_call",
"(",
"[",
"\"rm\"",
",",
"\"-rf\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_dir",
",",
"\"*\"",
")",
"]",
")",
"# NOTE: we do not create self._extracted_submission_dir",
"# ... | [
139,
4
] | [
149,
69
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.