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
CheckSessionCookieHttpOnlyTest.test_session_cookie_httponly_true
(self)
If SESSION_COOKIE_HTTPONLY is on, there's no warning about it.
If SESSION_COOKIE_HTTPONLY is on, there's no warning about it.
def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(self.func(None), [])
[ "def", "test_session_cookie_httponly_true", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 104, 4 ]
[ 108, 45 ]
python
en
['en', 'error', 'th']
False
CheckCSRFMiddlewareTest.test_no_csrf_middleware
(self)
Warn if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES.
Warn if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES.
def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [csrf.W003])
[ "def", "test_no_csrf_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "csrf", ".", "W003", "]", ")" ]
[ 118, 4 ]
[ 122, 54 ]
python
en
['en', 'error', 'th']
False
CheckCSRFCookieSecureTest.test_with_csrf_cookie_secure_false
(self)
Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_SECURE isn't True.
Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_SECURE isn't True.
def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(self.func(None), [csrf.W016])
[ "def", "test_with_csrf_cookie_secure_false", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "csrf", ".", "W016", "]", ")" ]
[ 139, 4 ]
[ 144, 54 ]
python
en
['en', 'error', 'th']
False
CheckCSRFCookieSecureTest.test_with_csrf_cookie_secure_false_no_middleware
(self)
No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_SECURE is False.
No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_SECURE is False.
def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(self.func(None), [])
[ "def", "test_with_csrf_cookie_secure_false_no_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 147, 4 ]
[ 152, 45 ]
python
en
['en', 'error', 'th']
False
CheckCSRFCookieHttpOnlyTest.test_with_csrf_cookie_httponly_false
(self)
Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_HTTPONLY isn't True.
Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_HTTPONLY isn't True.
def test_with_csrf_cookie_httponly_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE_CLASSES but CSRF_COOKIE_HTTPONLY isn't True. """ self.assertEqual(self.func(None), [csrf.W017])
[ "def", "test_with_csrf_cookie_httponly_false", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "csrf", ".", "W017", "]", ")" ]
[ 170, 4 ]
[ 175, 54 ]
python
en
['en', 'error', 'th']
False
CheckCSRFCookieHttpOnlyTest.test_with_csrf_cookie_httponly_false_no_middleware
(self)
No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_HTTPONLY is False.
No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_HTTPONLY is False.
def test_with_csrf_cookie_httponly_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_HTTPONLY is False. """ self.assertEqual(self.func(None), [])
[ "def", "test_with_csrf_cookie_httponly_false_no_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 178, 4 ]
[ 183, 45 ]
python
en
['en', 'error', 'th']
False
CheckSecurityMiddlewareTest.test_no_security_middleware
(self)
Warn if SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
Warn if SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [base.W001])
[ "def", "test_no_security_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W001", "]", ")" ]
[ 199, 4 ]
[ 203, 54 ]
python
en
['en', 'error', 'th']
False
CheckStrictTransportSecurityTest.test_no_sts
(self)
Warn if SECURE_HSTS_SECONDS isn't > 0.
Warn if SECURE_HSTS_SECONDS isn't > 0.
def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(self.func(None), [base.W004])
[ "def", "test_no_sts", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W004", "]", ")" ]
[ 220, 4 ]
[ 224, 54 ]
python
en
['en', 'error', 'th']
False
CheckStrictTransportSecurityTest.test_no_sts_no_middlware
(self)
Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed.
Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed.
def test_no_sts_no_middlware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_sts_no_middlware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 229, 4 ]
[ 234, 45 ]
python
en
['en', 'error', 'th']
False
CheckStrictTransportSecuritySubdomainsTest.test_no_sts_subdomains
(self)
Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True.
Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True.
def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(self.func(None), [base.W005])
[ "def", "test_no_sts_subdomains", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W005", "]", ")" ]
[ 253, 4 ]
[ 257, 54 ]
python
en
['en', 'error', 'th']
False
CheckStrictTransportSecuritySubdomainsTest.test_no_sts_subdomains_no_middlware
(self)
Don't warn if SecurityMiddleware isn't installed.
Don't warn if SecurityMiddleware isn't installed.
def test_no_sts_subdomains_no_middlware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_sts_subdomains_no_middlware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 263, 4 ]
[ 267, 45 ]
python
en
['en', 'error', 'th']
False
CheckStrictTransportSecuritySubdomainsTest.test_no_sts_subdomains_no_seconds
(self)
Don't warn if SECURE_HSTS_SECONDS isn't set.
Don't warn if SECURE_HSTS_SECONDS isn't set.
def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_sts_subdomains_no_seconds", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 273, 4 ]
[ 277, 45 ]
python
en
['en', 'error', 'th']
False
CheckXFrameOptionsMiddlewareTest.test_middleware_not_installed
(self)
Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES.
Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES.
def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [base.W002])
[ "def", "test_middleware_not_installed", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W002", "]", ")" ]
[ 294, 4 ]
[ 298, 54 ]
python
en
['en', 'error', 'th']
False
CheckXFrameOptionsDenyTest.test_x_frame_options_not_deny
(self)
Warn if XFrameOptionsMiddleware is in MIDDLEWARE_CLASSES but X_FRAME_OPTIONS isn't 'DENY'.
Warn if XFrameOptionsMiddleware is in MIDDLEWARE_CLASSES but X_FRAME_OPTIONS isn't 'DENY'.
def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE_CLASSES but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(self.func(None), [base.W019])
[ "def", "test_x_frame_options_not_deny", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W019", "]", ")" ]
[ 315, 4 ]
[ 320, 54 ]
python
en
['en', 'error', 'th']
False
CheckXFrameOptionsDenyTest.test_middleware_not_installed
(self)
No error if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES even if X_FRAME_OPTIONS isn't 'DENY'.
No error if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES even if X_FRAME_OPTIONS isn't 'DENY'.
def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE_CLASSES even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(self.func(None), [])
[ "def", "test_middleware_not_installed", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 323, 4 ]
[ 328, 45 ]
python
en
['en', 'error', 'th']
False
CheckContentTypeNosniffTest.test_no_content_type_nosniff
(self)
Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True.
Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True.
def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(self.func(None), [base.W006])
[ "def", "test_no_content_type_nosniff", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W006", "]", ")" ]
[ 347, 4 ]
[ 351, 54 ]
python
en
['en', 'error', 'th']
False
CheckContentTypeNosniffTest.test_no_content_type_nosniff_no_middleware
(self)
Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_content_type_nosniff_no_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 356, 4 ]
[ 361, 45 ]
python
en
['en', 'error', 'th']
False
CheckXssFilterTest.test_no_xss_filter
(self)
Warn if SECURE_BROWSER_XSS_FILTER isn't True.
Warn if SECURE_BROWSER_XSS_FILTER isn't True.
def test_no_xss_filter(self): """ Warn if SECURE_BROWSER_XSS_FILTER isn't True. """ self.assertEqual(self.func(None), [base.W007])
[ "def", "test_no_xss_filter", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W007", "]", ")" ]
[ 379, 4 ]
[ 383, 54 ]
python
en
['en', 'error', 'th']
False
CheckXssFilterTest.test_no_xss_filter_no_middleware
(self)
Don't warn if SECURE_BROWSER_XSS_FILTER isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
Don't warn if SECURE_BROWSER_XSS_FILTER isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES.
def test_no_xss_filter_no_middleware(self): """ Don't warn if SECURE_BROWSER_XSS_FILTER isn't True and SecurityMiddleware isn't in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_xss_filter_no_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 388, 4 ]
[ 393, 45 ]
python
en
['en', 'error', 'th']
False
CheckSSLRedirectTest.test_no_ssl_redirect
(self)
Warn if SECURE_SSL_REDIRECT isn't True.
Warn if SECURE_SSL_REDIRECT isn't True.
def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(self.func(None), [base.W008])
[ "def", "test_no_ssl_redirect", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W008", "]", ")" ]
[ 411, 4 ]
[ 415, 54 ]
python
en
['en', 'error', 'th']
False
CheckSSLRedirectTest.test_no_ssl_redirect_no_middlware
(self)
Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed.
Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed.
def test_no_ssl_redirect_no_middlware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(self.func(None), [])
[ "def", "test_no_ssl_redirect_no_middlware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 420, 4 ]
[ 425, 45 ]
python
en
['en', 'error', 'th']
False
CheckDebugTest.test_debug_true
(self)
Warn if DEBUG is True.
Warn if DEBUG is True.
def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(self.func(None), [base.W018])
[ "def", "test_debug_true", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "base", ".", "W018", "]", ")" ]
[ 478, 4 ]
[ 482, 54 ]
python
en
['en', 'error', 'th']
False
noise
(x, eps=0.3, order=np.inf, clip_min=None, clip_max=None)
A weak attack that just picks a random point in the attacker's action space. When combined with an attack bundling function, this can be used to implement random search. References: https://arxiv.org/abs/1802.00420 recommends random search to help identify gradient masking https://ope...
A weak attack that just picks a random point in the attacker's action space. When combined with an attack bundling function, this can be used to implement random search.
def noise(x, eps=0.3, order=np.inf, clip_min=None, clip_max=None): """ A weak attack that just picks a random point in the attacker's action space. When combined with an attack bundling function, this can be used to implement random search. References: https://arxiv.org/abs/1802.00420 recommend...
[ "def", "noise", "(", "x", ",", "eps", "=", "0.3", ",", "order", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ")", ":", "if", "order", "!=", "np", ".", "inf", ":", "raise", "NotImplementedError", "(", "norm", ...
[ 8, 0 ]
[ 41, 16 ]
python
en
['en', 'error', 'th']
False
OracleCreation.sql_indexes_for_field
(self, model, f, style)
Return any spatial index creation SQL for the field.
Return any spatial index creation SQL for the field.
def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(OracleCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): ...
[ "def", "sql_indexes_for_field", "(", "self", ",", "model", ",", "f", ",", "style", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "db", ".", "models", ".", "fields", "import", "GeometryField", "output", "=", "super", "(", "OracleCreation", ...
[ 6, 4 ]
[ 42, 21 ]
python
en
['en', 'en', 'en']
True
DiscoverRunnerTest.test_empty_label
(self)
If the test label is empty, discovery should happen on the current working directory.
If the test label is empty, discovery should happen on the current working directory.
def test_empty_label(self): """ If the test label is empty, discovery should happen on the current working directory. """ with change_cwd("."): suite = DiscoverRunner().build_suite([]) self.assertEqual( suite._tests[0].id().split(".")[0], ...
[ "def", "test_empty_label", "(", "self", ")", ":", "with", "change_cwd", "(", "\".\"", ")", ":", "suite", "=", "DiscoverRunner", "(", ")", ".", "build_suite", "(", "[", "]", ")", "self", ".", "assertEqual", "(", "suite", ".", "_tests", "[", "0", "]", ...
[ 65, 4 ]
[ 75, 13 ]
python
en
['en', 'error', 'th']
False
DiscoverRunnerTest.test_ignore_adjacent
(self)
When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module. This results in tests from adjacent modules being run when they should not. The discover runner avoids this behavior.
When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module.
def test_ignore_adjacent(self): """ When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module. This results in tests from adjacent modules being run when they should not. The discover runner avoids this be...
[ "def", "test_ignore_adjacent", "(", "self", ")", ":", "count", "=", "DiscoverRunner", "(", ")", ".", "build_suite", "(", "[", "\"test_discovery_sample.empty\"", "]", ",", ")", ".", "countTestCases", "(", ")", "self", ".", "assertEqual", "(", "count", ",", "0...
[ 91, 4 ]
[ 103, 34 ]
python
en
['en', 'error', 'th']
False
projected_gradient_descent
( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=True, rand_minmax=None, sanity_checks=True, )
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to False. or the Madry et al. (2017) method if rand_init is set to True. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1...
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to False. or the Madry et al. (2017) method if rand_init is set to True. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf/1...
def projected_gradient_descent( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=True, rand_minmax=None, sanity_checks=True, ): """ This class implements either the Basic Iterative Method (Kurakin e...
[ "def", "projected_gradient_descent", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "norm", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "rand_init", ...
[ 8, 0 ]
[ 152, 16 ]
python
en
['en', 'error', 'th']
False
get_host_platform
()
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included...
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included...
def get_host_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although th...
[ "def", "get_host_platform", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "if", "'amd64'", "in", "sys", ".", "version", ".", "lower", "(", ")", ":", "return", "'win-amd64'", "if", "'(arm)'", "in", "sys", ".", "version", ".", "lower", "("...
[ 17, 0 ]
[ 95, 50 ]
python
en
['en', 'en', 'en']
True
convert_path
(pathname)
Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can ...
Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can ...
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the...
[ "def", "convert_path", "(", "pathname", ")", ":", "if", "os", ".", "sep", "==", "'/'", ":", "return", "pathname", "if", "not", "pathname", ":", "return", "pathname", "if", "pathname", "[", "0", "]", "==", "'/'", ":", "raise", "ValueError", "(", "\"path...
[ 108, 0 ]
[ 131, 31 ]
python
en
['en', 'en', 'en']
True
change_root
(new_root, pathname)
Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.
Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.
def change_root (new_root, pathname): """Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS. """ if...
[ "def", "change_root", "(", "new_root", ",", "pathname", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "pathname", ")", ":", "return", "os", ".", "path", ".", "join", "(", "new_root", ","...
[ 136, 0 ]
[ 155, 83 ]
python
en
['en', 'en', 'en']
True
check_environ
()
Ensure that 'os.environ' has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes: HOME - user's home directory (Unix only) PLAT - description of the current platform, including hardware and OS (see 'get_platf...
Ensure that 'os.environ' has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes: HOME - user's home directory (Unix only) PLAT - description of the current platform, including hardware and OS (see 'get_platf...
def check_environ (): """Ensure that 'os.environ' has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes: HOME - user's home directory (Unix only) PLAT - description of the current platform, including hardware ...
[ "def", "check_environ", "(", ")", ":", "global", "_environ_checked", "if", "_environ_checked", ":", "return", "if", "os", ".", "name", "==", "'posix'", "and", "'HOME'", "not", "in", "os", ".", "environ", ":", "try", ":", "import", "pwd", "os", ".", "envi...
[ 159, 0 ]
[ 183, 24 ]
python
en
['en', 'en', 'en']
True
subst_vars
(s, local_vars)
Perform shell/Perl-style variable substitution on 'string'. Every occurrence of '$' followed by a name is considered a variable, and variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. 'os.environ' is first checked/augmented to guar...
Perform shell/Perl-style variable substitution on 'string'. Every occurrence of '$' followed by a name is considered a variable, and variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. 'os.environ' is first checked/augmented to guar...
def subst_vars (s, local_vars): """Perform shell/Perl-style variable substitution on 'string'. Every occurrence of '$' followed by a name is considered a variable, and variable is substituted by the value found in the 'local_vars' dictionary, or in 'os.environ' if it's not in 'local_vars'. 'os.envi...
[ "def", "subst_vars", "(", "s", ",", "local_vars", ")", ":", "check_environ", "(", ")", "def", "_subst", "(", "match", ",", "local_vars", "=", "local_vars", ")", ":", "var_name", "=", "match", ".", "group", "(", "1", ")", "if", "var_name", "in", "local_...
[ 186, 0 ]
[ 206, 56 ]
python
en
['en', 'en', 'en']
True
split_quoted
(s)
Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The b...
Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The b...
def split_quoted (s): """Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can ...
[ "def", "split_quoted", "(", "s", ")", ":", "# This is a nice algorithm for splitting up a single string, since it", "# doesn't require character-by-character examination. It was a little", "# bit of a brain-bender to get it working right, though...", "if", "_wordchars_re", "is", "None", "...
[ 226, 0 ]
[ 282, 16 ]
python
en
['en', 'en', 'en']
True
execute
(func, args, msg=None, verbose=0, dry_run=0)
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to e...
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to e...
def execute (func, args, msg=None, verbose=0, dry_run=0): """Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is s...
[ "def", "execute", "(", "func", ",", "args", ",", "msg", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "\"%s%r\"", "%", "(", "func", ".", "__name__", ",", "args", ")", "if"...
[ 287, 0 ]
[ 303, 19 ]
python
en
['en', 'en', 'en']
True
strtobool
(val)
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else.
Convert a string representation of truth to true (1) or false (0).
def strtobool (val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'y...
[ "def", "strtobool", "(", "val", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "'y'", ",", "'yes'", ",", "'t'", ",", "'true'", ",", "'on'", ",", "'1'", ")", ":", "return", "1", "elif", "val", "in", "(", "'n'", ",...
[ 306, 0 ]
[ 319, 59 ]
python
en
['en', 'pt', 'en']
True
byte_compile
(py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None)
Byte-compile a collection of Python source files to .pyc files in a __pycache__ subdirectory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize 1 - normal optimization (like "python -O")...
Byte-compile a collection of Python source files to .pyc files in a __pycache__ subdirectory. 'py_files' is a list of files to compile; any files that don't end in ".py" are silently skipped. 'optimize' must be one of the following: 0 - don't optimize 1 - normal optimization (like "python -O")...
def byte_compile (py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None): """Byte-compile a collection of Python source files to .pyc files in a __pycache__ subdirectory. 'py_files' is a list of f...
[ "def", "byte_compile", "(", "py_files", ",", "optimize", "=", "0", ",", "force", "=", "0", ",", "prefix", "=", "None", ",", "base_dir", "=", "None", ",", "verbose", "=", "1", ",", "dry_run", "=", "0", ",", "direct", "=", "None", ")", ":", "# Late i...
[ 322, 0 ]
[ 467, 47 ]
python
en
['en', 'en', 'en']
True
rfc822_escape
(header)
Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline.
Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline.
def rfc822_escape (header): """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ lines = header.split('\n') sep = '\n' + 8 * ' ' return sep.join(lines)
[ "def", "rfc822_escape", "(", "header", ")", ":", "lines", "=", "header", ".", "split", "(", "'\\n'", ")", "sep", "=", "'\\n'", "+", "8", "*", "' '", "return", "sep", ".", "join", "(", "lines", ")" ]
[ 471, 0 ]
[ 477, 26 ]
python
en
['en', 'en', 'en']
True
run_2to3
(files, fixer_names=None, options=None, explicit=None)
Invoke 2to3 on a list of Python files. The files should all come from the build area, as the modification is done in-place. To reduce the build time, only files modified since the last invocation of this function should be passed in the files argument.
Invoke 2to3 on a list of Python files. The files should all come from the build area, as the modification is done in-place. To reduce the build time, only files modified since the last invocation of this function should be passed in the files argument.
def run_2to3(files, fixer_names=None, options=None, explicit=None): """Invoke 2to3 on a list of Python files. The files should all come from the build area, as the modification is done in-place. To reduce the build time, only files modified since the last invocation of this function should be passed...
[ "def", "run_2to3", "(", "files", ",", "fixer_names", "=", "None", ",", "options", "=", "None", ",", "explicit", "=", "None", ")", ":", "if", "not", "files", ":", "return", "# Make this class local, to delay import of 2to3", "from", "lib2to3", ".", "refactor", ...
[ 481, 0 ]
[ 506, 33 ]
python
en
['en', 'haw', 'en']
True
copydir_run_2to3
(src, dest, template=None, fixer_names=None, options=None, explicit=None)
Recursively copy a directory, only copying new and changed files, running run_2to3 over all newly copied Python modules afterward. If you give a template string, it's parsed like a MANIFEST.in.
Recursively copy a directory, only copying new and changed files, running run_2to3 over all newly copied Python modules afterward.
def copydir_run_2to3(src, dest, template=None, fixer_names=None, options=None, explicit=None): """Recursively copy a directory, only copying new and changed files, running run_2to3 over all newly copied Python modules afterward. If you give a template string, it's parsed like a MANIFES...
[ "def", "copydir_run_2to3", "(", "src", ",", "dest", ",", "template", "=", "None", ",", "fixer_names", "=", "None", ",", "options", "=", "None", ",", "explicit", "=", "None", ")", ":", "from", "distutils", ".", "dir_util", "import", "mkpath", "from", "dis...
[ 508, 0 ]
[ 539, 17 ]
python
en
['en', 'en', 'en']
True
PythonNeuropodExecutor.__init__
(self, neuropod_path, load_custom_ops=True)
Load a python neuropod :param neuropod_path: The path to a python neuropod package
Load a python neuropod
def __init__(self, neuropod_path, load_custom_ops=True): """ Load a python neuropod :param neuropod_path: The path to a python neuropod package """ super(PythonNeuropodExecutor, self).__init__(neuropod_path) self.neuropod_path = neuropod_path # Load the model ...
[ "def", "__init__", "(", "self", ",", "neuropod_path", ",", "load_custom_ops", "=", "True", ")", ":", "super", "(", "PythonNeuropodExecutor", ",", "self", ")", ".", "__init__", "(", "neuropod_path", ")", "self", ".", "neuropod_path", "=", "neuropod_path", "# Lo...
[ 61, 4 ]
[ 137, 79 ]
python
en
['en', 'error', 'th']
False
PythonNeuropodExecutor.forward
(self, inputs)
Run inference using the specifed inputs. :param inputs: A dict mapping input names to values. This must match the input spec in the neuropod config for the loaded model. Ex: {'x1': np.array([5]), 'x2': np.array([6])} ...
Run inference using the specifed inputs.
def forward(self, inputs): """ Run inference using the specifed inputs. :param inputs: A dict mapping input names to values. This must match the input spec in the neuropod config for the loaded model. Ex: {'x1': np.array([5]), 'x2': n...
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "out", "=", "self", ".", "model", "(", "*", "*", "inputs", ")", "# Make sure everything is a numpy array", "for", "key", ",", "value", "in", "out", ".", "items", "(", ")", ":", "if", "not", "isins...
[ 139, 4 ]
[ 163, 18 ]
python
en
['en', 'error', 'th']
False
register_serializer
(format, serializer_module, serializers=None)
Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global ...
Register a new serializer.
def register_serializer(format, serializer_module, serializers=None): """Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers``...
[ "def", "register_serializer", "(", "format", ",", "serializer_module", ",", "serializers", "=", "None", ")", ":", "if", "serializers", "is", "None", "and", "not", "_serializers", ":", "_load_serializers", "(", ")", "try", ":", "module", "=", "importlib", ".", ...
[ 52, 0 ]
[ 81, 36 ]
python
en
['en', 'en', 'en']
True
unregister_serializer
(format)
Unregister a given serializer. This is not a thread-safe operation.
Unregister a given serializer. This is not a thread-safe operation.
def unregister_serializer(format): "Unregister a given serializer. This is not a thread-safe operation." if not _serializers: _load_serializers() if format not in _serializers: raise SerializerDoesNotExist(format) del _serializers[format]
[ "def", "unregister_serializer", "(", "format", ")", ":", "if", "not", "_serializers", ":", "_load_serializers", "(", ")", "if", "format", "not", "in", "_serializers", ":", "raise", "SerializerDoesNotExist", "(", "format", ")", "del", "_serializers", "[", "format...
[ 84, 0 ]
[ 90, 28 ]
python
en
['en', 'en', 'en']
True
serialize
(format, queryset, **options)
Serialize a queryset (or any iterator that returns database objects) using a certain serializer.
Serialize a queryset (or any iterator that returns database objects) using a certain serializer.
def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue()
[ "def", "serialize", "(", "format", ",", "queryset", ",", "*", "*", "options", ")", ":", "s", "=", "get_serializer", "(", "format", ")", "(", ")", "s", ".", "serialize", "(", "queryset", ",", "*", "*", "options", ")", "return", "s", ".", "getvalue", ...
[ 121, 0 ]
[ 128, 23 ]
python
en
['en', 'error', 'th']
False
deserialize
(format, stream_or_string, **options)
Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``.
Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``.
def deserialize(format, stream_or_string, **options): """ Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objec...
[ "def", "deserialize", "(", "format", ",", "stream_or_string", ",", "*", "*", "options", ")", ":", "d", "=", "get_deserializer", "(", "format", ")", "return", "d", "(", "stream_or_string", ",", "*", "*", "options", ")" ]
[ 131, 0 ]
[ 139, 41 ]
python
en
['en', 'error', 'th']
False
_load_serializers
()
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: ...
[ "def", "_load_serializers", "(", ")", ":", "global", "_serializers", "serializers", "=", "{", "}", "for", "format", "in", "BUILTIN_SERIALIZERS", ":", "register_serializer", "(", "format", ",", "BUILTIN_SERIALIZERS", "[", "format", "]", ",", "serializers", ")", "...
[ 142, 0 ]
[ 155, 30 ]
python
en
['en', 'error', 'th']
False
sort_dependencies
(app_list)
Sort a list of (app_config, models) pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first.
Sort a list of (app_config, models) pairs into a single list of models.
def sort_dependencies(app_list): """Sort a list of (app_config, models) pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. ...
[ "def", "sort_dependencies", "(", "app_list", ")", ":", "# Process the list of models, and get the list of dependencies", "model_dependencies", "=", "[", "]", "models", "=", "set", "(", ")", "for", "app_config", ",", "model_list", "in", "app_list", ":", "if", "model_li...
[ 158, 0 ]
[ 233, 21 ]
python
en
['en', 'en', 'en']
True
interactive_debug
(sig: int, frame: FrameType)
Interrupt running process, and provide a python prompt for interactive debugging.
Interrupt running process, and provide a python prompt for interactive debugging.
def interactive_debug(sig: int, frame: FrameType) -> None: """Interrupt running process, and provide a python prompt for interactive debugging.""" d = {"_frame": frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) message = "Si...
[ "def", "interactive_debug", "(", "sig", ":", "int", ",", "frame", ":", "FrameType", ")", "->", "None", ":", "d", "=", "{", "\"_frame\"", ":", "frame", "}", "# Allow access to frame object.", "d", ".", "update", "(", "frame", ".", "f_globals", ")", "# Unles...
[ 22, 0 ]
[ 32, 23 ]
python
en
['en', 'en', 'en']
True
maybe_tracemalloc_listen
()
If tracemalloc tracing enabled, listen for requests to dump a snapshot. To trigger once this is listening: echo | socat -u stdin unix-sendto:/tmp/tracemalloc.$pid To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini , and add e.g. ` PYTHONTRACEMALLOC=5` to the `env=` line. This function ...
If tracemalloc tracing enabled, listen for requests to dump a snapshot.
def maybe_tracemalloc_listen() -> None: """If tracemalloc tracing enabled, listen for requests to dump a snapshot. To trigger once this is listening: echo | socat -u stdin unix-sendto:/tmp/tracemalloc.$pid To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini , and add e.g. ` PYTHONTRACEM...
[ "def", "maybe_tracemalloc_listen", "(", ")", "->", "None", ":", "if", "os", ".", "environ", ".", "get", "(", "\"PYTHONTRACEMALLOC\"", ")", ":", "# If the server was started with `tracemalloc` tracing on, then", "# listen for a signal to dump `tracemalloc` snapshots.", "tracemal...
[ 93, 0 ]
[ 112, 28 ]
python
en
['en', 'en', 'en']
True
get_version
(version=None)
Return a PEP 440-compliant version number from VERSION.
Return a PEP 440-compliant version number from VERSION.
def get_version(version=None): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases ...
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "version", "=", "get_complete_version", "(", "version", ")", "# Now build the two parts of the version number:", "# main = X.Y[.Z]", "# sub = .devN - for pre-alpha releases", "# | {a|b|rc}N - for alpha, beta, and rc r...
[ 17, 0 ]
[ 38, 21 ]
python
en
['en', 'en', 'en']
True
get_main_version
(version=None)
Return main version (X.Y[.Z]) from VERSION.
Return main version (X.Y[.Z]) from VERSION.
def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return '.'.join(str(x) for x in version[:parts])
[ "def", "get_main_version", "(", "version", "=", "None", ")", ":", "version", "=", "get_complete_version", "(", "version", ")", "parts", "=", "2", "if", "version", "[", "2", "]", "==", "0", "else", "3", "return", "'.'", ".", "join", "(", "str", "(", "...
[ 41, 0 ]
[ 45, 52 ]
python
en
['en', 'en', 'en']
True
get_complete_version
(version=None)
Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided.
Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided.
def get_complete_version(version=None): """ Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] ...
[ "def", "get_complete_version", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "from", "django", "import", "VERSION", "as", "version", "else", ":", "assert", "len", "(", "version", ")", "==", "5", "assert", "version", "[", "3",...
[ 48, 0 ]
[ 59, 18 ]
python
en
['en', 'error', 'th']
False
get_git_changeset
()
Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers.
Return a numeric identifier of the latest git changeset.
def get_git_changeset(): """Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. ...
[ "def", "get_git_changeset", "(", ")", ":", "repo_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ")", "git_log", "=", "subprocess", ".", "run", ...
[ 71, 0 ]
[ 89, 45 ]
python
en
['en', 'en', 'en']
True
get_version_tuple
(version)
Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3').
Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3').
def get_version_tuple(version): """ Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3'). """ loose_version = LooseVersion(version) version_numbers = [] for item in loose_version.version: if not isinstance(item, int): break ver...
[ "def", "get_version_tuple", "(", "version", ")", ":", "loose_version", "=", "LooseVersion", "(", "version", ")", "version_numbers", "=", "[", "]", "for", "item", "in", "loose_version", ".", "version", ":", "if", "not", "isinstance", "(", "item", ",", "int", ...
[ 92, 0 ]
[ 103, 33 ]
python
en
['en', 'error', 'th']
False
attack_selection
(attack_string)
Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager
Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager
def attack_selection(attack_string): """ Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager """ # List of Implemented attacks attacks_list = AVAILABLE_ATTACKS.keys() # Che...
[ "def", "attack_selection", "(", "attack_string", ")", ":", "# List of Implemented attacks", "attacks_list", "=", "AVAILABLE_ATTACKS", ".", "keys", "(", ")", "# Checking for requested attack in list of available attacks.", "if", "attack_string", "is", "None", ":", "raise", ...
[ 50, 0 ]
[ 72, 23 ]
python
en
['en', 'error', 'th']
False
mnist_tutorial
( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=True, testing=False, backprop_through_attack=False, nb_filters=NB_FILTERS, num_threads=None, attack_string=None, )
MNIST cleverhans tutorial :param train_start: index of first training set example. :param train_end: index of last training set example. :param test_start: index of first test set example. :param test_end: index of last test set example. :param nb_epochs: number of epochs to train model. :p...
MNIST cleverhans tutorial :param train_start: index of first training set example. :param train_end: index of last training set example. :param test_start: index of first test set example. :param test_end: index of last test set example. :param nb_epochs: number of epochs to train model. :p...
def mnist_tutorial( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=True, testing=False, backprop_through_attack=False, nb_filters=NB_FILTERS, num_threads=None, attack_s...
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
[ 75, 0 ]
[ 264, 17 ]
python
en
['en', 'error', 'th']
False
default_key_func
(key, key_prefix, version)
Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior.
Default function to generate keys.
def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (k...
[ "def", "default_key_func", "(", "key", ",", "key_prefix", ",", "version", ")", ":", "return", "'%s:%s:%s'", "%", "(", "key_prefix", ",", "version", ",", "key", ")" ]
[ 26, 0 ]
[ 34, 50 ]
python
en
['en', 'error', 'th']
False
get_key_func
(key_func)
Function to decide which key function to use. Defaults to ``default_key_func``.
Function to decide which key function to use.
def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func
[ "def", "get_key_func", "(", "key_func", ")", ":", "if", "key_func", "is", "not", "None", ":", "if", "callable", "(", "key_func", ")", ":", "return", "key_func", "else", ":", "return", "import_string", "(", "key_func", ")", "return", "default_key_func" ]
[ 37, 0 ]
[ 48, 27 ]
python
en
['en', 'error', 'th']
False
BaseCache.get_backend_timeout
(self, timeout=DEFAULT_TIMEOUT)
Returns the timeout value usable by this backend based upon the provided timeout.
Returns the timeout value usable by this backend based upon the provided timeout.
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Returns the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoi...
[ "def", "get_backend_timeout", "(", "self", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "if", "timeout", "==", "DEFAULT_TIMEOUT", ":", "timeout", "=", "self", ".", "default_timeout", "elif", "timeout", "==", "0", ":", "# ticket 21147 - avoid time.time() related...
[ 78, 4 ]
[ 88, 65 ]
python
en
['en', 'error', 'th']
False
BaseCache.make_key
(self, key, version=None)
Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to ...
Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to ...
def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alt...
[ "def", "make_key", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "version", "new_key", "=", "self", ".", "key_func", "(", "key", ",", "self", ".", "key_prefix", ",", ...
[ 90, 4 ]
[ 102, 22 ]
python
en
['en', 'en', 'en']
True
BaseCache.add
(self, key, value, timeout=DEFAULT_TIMEOUT, version=None)
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise.
Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, F...
[ "def", "add", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide an add() method'", ")" ]
[ 104, 4 ]
[ 112, 89 ]
python
en
['en', 'error', 'th']
False
BaseCache.get
(self, key, default=None, version=None)
Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None.
Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None.
def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError('subclasses of BaseCache must provide a get() method')
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a get() method'", ")" ]
[ 114, 4 ]
[ 119, 88 ]
python
en
['en', 'error', 'th']
False
BaseCache.set
(self, key, value, timeout=DEFAULT_TIMEOUT, version=None)
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError('subclasses of BaseCache must provide a set(...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a set() method'", ")" ]
[ 121, 4 ]
[ 126, 88 ]
python
en
['en', 'error', 'th']
False
BaseCache.delete
(self, key, version=None)
Delete a key from the cache, failing silently.
Delete a key from the cache, failing silently.
def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError('subclasses of BaseCache must provide a delete() method')
[ "def", "delete", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a delete() method'", ")" ]
[ 128, 4 ]
[ 132, 91 ]
python
en
['en', 'error', 'th']
False
BaseCache.get_many
(self, keys, version=None)
Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict.
Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values.
def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missin...
[ "def", "get_many", "(", "self", ",", "keys", ",", "version", "=", "None", ")", ":", "d", "=", "{", "}", "for", "k", "in", "keys", ":", "val", "=", "self", ".", "get", "(", "k", ",", "version", "=", "version", ")", "if", "val", "is", "not", "N...
[ 134, 4 ]
[ 147, 16 ]
python
en
['en', 'error', 'th']
False
BaseCache.has_key
(self, key, version=None)
Returns True if the key is in the cache and has not expired.
Returns True if the key is in the cache and has not expired.
def has_key(self, key, version=None): """ Returns True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None
[ "def", "has_key", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "return", "self", ".", "get", "(", "key", ",", "version", "=", "version", ")", "is", "not", "None" ]
[ 149, 4 ]
[ 153, 57 ]
python
en
['en', 'error', 'th']
False
BaseCache.incr
(self, key, delta=1, version=None)
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
Add delta to value in the cache. If the key does not exist, raise a ValueError exception.
def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_valu...
[ "def", "incr", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "version", "=", "version", ")", "if", "value", "is", "None", ":", "raise", "ValueError", "("...
[ 155, 4 ]
[ 165, 24 ]
python
en
['en', 'error', 'th']
False
BaseCache.decr
(self, key, delta=1, version=None)
Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception.
Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception.
def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version)
[ "def", "decr", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "return", "self", ".", "incr", "(", "key", ",", "-", "delta", ",", "version", "=", "version", ")" ]
[ 167, 4 ]
[ 172, 54 ]
python
en
['en', 'error', 'th']
False
BaseCache.__contains__
(self, key)
Returns True if the key is in the cache and has not expired.
Returns True if the key is in the cache and has not expired.
def __contains__(self, key): """ Returns True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. ret...
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "# This is a separate method, rather than just a copy of has_key(),", "# so that it always has the same functionality as has_key(), even", "# if a subclass overrides it.", "return", "self", ".", "has_key", "(", "key", ")" ]
[ 174, 4 ]
[ 181, 32 ]
python
en
['en', 'error', 'th']
False
BaseCache.set_many
(self, data, timeout=DEFAULT_TIMEOUT, version=None)
Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be u...
Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times.
def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout wil...
[ "def", "set_many", "(", "self", ",", "data", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "version", "=", "None", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "self", ".", "set", "(", "key", ",", "value", ",", ...
[ 183, 4 ]
[ 193, 66 ]
python
en
['en', 'error', 'th']
False
BaseCache.delete_many
(self, keys, version=None)
Set a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times.
Set a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times.
def delete_many(self, keys, version=None): """ Set a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version)
[ "def", "delete_many", "(", "self", ",", "keys", ",", "version", "=", "None", ")", ":", "for", "key", "in", "keys", ":", "self", ".", "delete", "(", "key", ",", "version", "=", "version", ")" ]
[ 195, 4 ]
[ 202, 45 ]
python
en
['en', 'error', 'th']
False
BaseCache.clear
(self)
Remove *all* values from the cache at once.
Remove *all* values from the cache at once.
def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError('subclasses of BaseCache must provide a clear() method')
[ "def", "clear", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseCache must provide a clear() method'", ")" ]
[ 204, 4 ]
[ 206, 90 ]
python
en
['en', 'en', 'en']
True
BaseCache.validate_key
(self, key)
Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code.
Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code.
def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn('Cache key will cause erro...
[ "def", "validate_key", "(", "self", ",", "key", ")", ":", "if", "len", "(", "key", ")", ">", "MEMCACHE_MAX_KEY_LENGTH", ":", "warnings", ".", "warn", "(", "'Cache key will cause errors if used with memcached: '", "'%s (longer than %s)'", "%", "(", "key", ",", "MEM...
[ 208, 4 ]
[ 223, 46 ]
python
en
['en', 'error', 'th']
False
BaseCache.incr_version
(self, key, delta=1, version=None)
Adds delta to the cache version for the supplied key. Returns the new version.
Adds delta to the cache version for the supplied key. Returns the new version.
def incr_version(self, key, delta=1, version=None): """Adds delta to the cache version for the supplied key. Returns the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise Val...
[ "def", "incr_version", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "version", "value", "=", "self", ".", "get", "(", "key", ",", "version",...
[ 225, 4 ]
[ 238, 30 ]
python
en
['en', 'en', 'en']
True
BaseCache.decr_version
(self, key, delta=1, version=None)
Substracts delta from the cache version for the supplied key. Returns the new version.
Substracts delta from the cache version for the supplied key. Returns the new version.
def decr_version(self, key, delta=1, version=None): """Substracts delta from the cache version for the supplied key. Returns the new version. """ return self.incr_version(key, -delta, version)
[ "def", "decr_version", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "version", "=", "None", ")", ":", "return", "self", ".", "incr_version", "(", "key", ",", "-", "delta", ",", "version", ")" ]
[ 240, 4 ]
[ 244, 54 ]
python
en
['en', 'en', 'en']
True
BaseCache.close
(self, **kwargs)
Close the cache connection
Close the cache connection
def close(self, **kwargs): """Close the cache connection""" pass
[ "def", "close", "(", "self", ",", "*", "*", "kwargs", ")", ":", "pass" ]
[ 246, 4 ]
[ 248, 12 ]
python
en
['en', 'en', 'en']
True
build_request_repr
(request, path_override=None, GET_override=None, POST_override=None, COOKIES_override=None, META_override=None)
Builds and returns the request's representation string. The request's attributes may be overridden by pre-processed values.
Builds and returns the request's representation string. The request's attributes may be overridden by pre-processed values.
def build_request_repr(request, path_override=None, GET_override=None, POST_override=None, COOKIES_override=None, META_override=None): """ Builds and returns the request's representation string. The request's attributes may be overridden by pre-processed values....
[ "def", "build_request_repr", "(", "request", ",", "path_override", "=", "None", ",", "GET_override", "=", "None", ",", "POST_override", "=", "None", ",", "COOKIES_override", "=", "None", ",", "META_override", "=", "None", ")", ":", "# Since this is called as part ...
[ 460, 0 ]
[ 503, 43 ]
python
en
['en', 'error', 'th']
False
bytes_to_text
(s, encoding)
Converts basestring objects to unicode, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd). Returns any non-basestring objects without change.
Converts basestring objects to unicode, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd).
def bytes_to_text(s, encoding): """ Converts basestring objects to unicode, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd). Returns any non-basestring objects without change. """ if isinstance(s, bytes): return six...
[ "def", "bytes_to_text", "(", "s", ",", "encoding", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "six", ".", "text_type", "(", "s", ",", "encoding", ",", "'replace'", ")", "else", ":", "return", "s" ]
[ 509, 0 ]
[ 520, 16 ]
python
en
['en', 'error', 'th']
False
split_domain_port
(host)
Return a (domain, port) tuple from a given host. Returned domain is lower-cased. If the host is invalid, the domain will be empty.
Return a (domain, port) tuple from a given host.
def split_domain_port(host): """ Return a (domain, port) tuple from a given host. Returned domain is lower-cased. If the host is invalid, the domain will be empty. """ host = host.lower() if not host_validation_re.match(host): return '', '' if host[-1] == ']': # It's a...
[ "def", "split_domain_port", "(", "host", ")", ":", "host", "=", "host", ".", "lower", "(", ")", "if", "not", "host_validation_re", ".", "match", "(", "host", ")", ":", "return", "''", ",", "''", "if", "host", "[", "-", "1", "]", "==", "']'", ":", ...
[ 523, 0 ]
[ 541, 22 ]
python
en
['en', 'error', 'th']
False
validate_host
(host, allowed_hosts)
Validate the given host for this site. Check that the host looks valid and matches a host or host pattern in the given list of ``allowed_hosts``. Any pattern beginning with a period matches a domain and all its subdomains (e.g. ``.example.com`` matches ``example.com`` and any subdomain), ``*`` mat...
Validate the given host for this site.
def validate_host(host, allowed_hosts): """ Validate the given host for this site. Check that the host looks valid and matches a host or host pattern in the given list of ``allowed_hosts``. Any pattern beginning with a period matches a domain and all its subdomains (e.g. ``.example.com`` matches ...
[ "def", "validate_host", "(", "host", ",", "allowed_hosts", ")", ":", "host", "=", "host", "[", ":", "-", "1", "]", "if", "host", ".", "endswith", "(", "'.'", ")", "else", "host", "for", "pattern", "in", "allowed_hosts", ":", "pattern", "=", "pattern", ...
[ 544, 0 ]
[ 574, 16 ]
python
en
['en', 'error', 'th']
False
HttpRequest.get_host
(self)
Returns the HTTP host using the environment or request headers.
Returns the HTTP host using the environment or request headers.
def get_host(self): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in self.META): host = self.META['HTTP_X_FORWARDED_HOST']...
[ "def", "get_host", "(", "self", ")", ":", "# We try three options, in order of decreasing preference.", "if", "settings", ".", "USE_X_FORWARDED_HOST", "and", "(", "'HTTP_X_FORWARDED_HOST'", "in", "self", ".", "META", ")", ":", "host", "=", "self", ".", "META", "[", ...
[ 66, 4 ]
[ 94, 37 ]
python
en
['en', 'en', 'en']
True
HttpRequest.get_signed_cookie
(self, key, default=RAISE_ERROR, salt='', max_age=None)
Attempts to return a signed cookie. If the signature fails or the cookie has expired, raises an exception... unless you provide the default argument in which case that value will be returned instead.
Attempts to return a signed cookie. If the signature fails or the cookie has expired, raises an exception... unless you provide the default argument in which case that value will be returned instead.
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None): """ Attempts to return a signed cookie. If the signature fails or the cookie has expired, raises an exception... unless you provide the default argument in which case that value will be returned instead. ...
[ "def", "get_signed_cookie", "(", "self", ",", "key", ",", "default", "=", "RAISE_ERROR", ",", "salt", "=", "''", ",", "max_age", "=", "None", ")", ":", "try", ":", "cookie_value", "=", "self", ".", "COOKIES", "[", "key", "]", "except", "KeyError", ":",...
[ 104, 4 ]
[ 125, 20 ]
python
en
['en', 'error', 'th']
False
HttpRequest.build_absolute_uri
(self, location=None)
Builds an absolute URI from the location and the variables available in this request. If no ``location`` is specified, the absolute URI is built on ``request.get_full_path()``. Anyway, if the location is absolute, it is simply converted to an RFC 3987 compliant URI and returned ...
Builds an absolute URI from the location and the variables available in this request. If no ``location`` is specified, the absolute URI is built on ``request.get_full_path()``. Anyway, if the location is absolute, it is simply converted to an RFC 3987 compliant URI and returned ...
def build_absolute_uri(self, location=None): """ Builds an absolute URI from the location and the variables available in this request. If no ``location`` is specified, the absolute URI is built on ``request.get_full_path()``. Anyway, if the location is absolute, it is simply conv...
[ "def", "build_absolute_uri", "(", "self", ",", "location", "=", "None", ")", ":", "if", "location", "is", "None", ":", "# Make it an absolute url (but schemeless and domainless) for the", "# edge case that the path starts with '//'.", "location", "=", "'//%s'", "%", "self",...
[ 127, 4 ]
[ 150, 35 ]
python
en
['en', 'error', 'th']
False
HttpRequest.encoding
(self, val)
Sets the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, it is removed and recreated on the next access (so that it is decoded correctly).
Sets the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, it is removed and recreated on the next access (so that it is decoded correctly).
def encoding(self, val): """ Sets the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, it is removed and recreated on the next access (so that it is decoded correctly). """ self._encoding = val if hasattr(self, '_get'): ...
[ "def", "encoding", "(", "self", ",", "val", ")", ":", "self", ".", "_encoding", "=", "val", "if", "hasattr", "(", "self", ",", "'_get'", ")", ":", "del", "self", ".", "_get", "if", "hasattr", "(", "self", ",", "'_post'", ")", ":", "del", "self", ...
[ 182, 4 ]
[ 192, 26 ]
python
en
['en', 'error', 'th']
False
HttpRequest.parse_file_upload
(self, META, post_data)
Returns a tuple of (POST QueryDict, FILES MultiValueDict).
Returns a tuple of (POST QueryDict, FILES MultiValueDict).
def parse_file_upload(self, META, post_data): """Returns a tuple of (POST QueryDict, FILES MultiValueDict).""" self.upload_handlers = ImmutableList( self.upload_handlers, warning="You cannot alter upload handlers after the upload has been processed." ) parser = Mu...
[ "def", "parse_file_upload", "(", "self", ",", "META", ",", "post_data", ")", ":", "self", ".", "upload_handlers", "=", "ImmutableList", "(", "self", ".", "upload_handlers", ",", "warning", "=", "\"You cannot alter upload handlers after the upload has been processed.\"", ...
[ 211, 4 ]
[ 218, 29 ]
python
en
['en', 'la', 'en']
True
HttpRequest._load_post_and_files
(self)
Populate self._post and self._files if the content-type is a form type
Populate self._post and self._files if the content-type is a form type
def _load_post_and_files(self): """Populate self._post and self._files if the content-type is a form type""" if self.method != 'POST': self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict() return if self._read_started and not hasattr(self, '_b...
[ "def", "_load_post_and_files", "(", "self", ")", ":", "if", "self", ".", "method", "!=", "'POST'", ":", "self", ".", "_post", ",", "self", ".", "_files", "=", "QueryDict", "(", "''", ",", "encoding", "=", "self", ".", "_encoding", ")", ",", "MultiValue...
[ 237, 4 ]
[ 267, 94 ]
python
en
['en', 'en', 'en']
True
QueryDict.copy
(self)
Returns a mutable copy of this object.
Returns a mutable copy of this object.
def copy(self): """Returns a mutable copy of this object.""" return self.__deepcopy__({})
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__deepcopy__", "(", "{", "}", ")" ]
[ 428, 4 ]
[ 430, 36 ]
python
en
['en', 'en', 'en']
True
QueryDict.urlencode
(self, safe=None)
Returns an encoded string of all query string arguments. :arg safe: Used to specify characters which do not require quoting, for example:: >>> q = QueryDict('', mutable=True) >>> q['next'] = '/a&b/' >>> q.urlencode() 'next=%2...
Returns an encoded string of all query string arguments.
def urlencode(self, safe=None): """ Returns an encoded string of all query string arguments. :arg safe: Used to specify characters which do not require quoting, for example:: >>> q = QueryDict('', mutable=True) >>> q['next'] = '/a&b/' ...
[ "def", "urlencode", "(", "self", ",", "safe", "=", "None", ")", ":", "output", "=", "[", "]", "if", "safe", ":", "safe", "=", "force_bytes", "(", "safe", ",", "self", ".", "encoding", ")", "encode", "=", "lambda", "k", ",", "v", ":", "'%s=%s'", "...
[ 432, 4 ]
[ 457, 31 ]
python
en
['en', 'error', 'th']
False
load_backend
(backend_name)
Return a database backend's "base" module given a fully qualified database backend name, or raise an error if it doesn't exist.
Return a database backend's "base" module given a fully qualified database backend name, or raise an error if it doesn't exist.
def load_backend(backend_name): """ Return a database backend's "base" module given a fully qualified database backend name, or raise an error if it doesn't exist. """ # This backend was renamed in Django 1.9. if backend_name == 'django.db.backends.postgresql_psycopg2': backend_name = 'd...
[ "def", "load_backend", "(", "backend_name", ")", ":", "# This backend was renamed in Django 1.9.", "if", "backend_name", "==", "'django.db.backends.postgresql_psycopg2'", ":", "backend_name", "=", "'django.db.backends.postgresql'", "try", ":", "return", "import_module", "(", ...
[ 100, 0 ]
[ 128, 17 ]
python
en
['en', 'error', 'th']
False
DatabaseErrorWrapper.__init__
(self, wrapper)
wrapper is a database wrapper. It must have a Database attribute defining PEP-249 exceptions.
wrapper is a database wrapper.
def __init__(self, wrapper): """ wrapper is a database wrapper. It must have a Database attribute defining PEP-249 exceptions. """ self.wrapper = wrapper
[ "def", "__init__", "(", "self", ",", "wrapper", ")", ":", "self", ".", "wrapper", "=", "wrapper" ]
[ 57, 4 ]
[ 63, 30 ]
python
en
['en', 'error', 'th']
False
ConnectionHandler.__init__
(self, databases=None)
databases is an optional dictionary of database definitions (structured like settings.DATABASES).
databases is an optional dictionary of database definitions (structured like settings.DATABASES).
def __init__(self, databases=None): """ databases is an optional dictionary of database definitions (structured like settings.DATABASES). """ self._databases = databases # Connections needs to still be an actual thread local, as it's truly # thread-critical. Datab...
[ "def", "__init__", "(", "self", ",", "databases", "=", "None", ")", ":", "self", ".", "_databases", "=", "databases", "# Connections needs to still be an actual thread local, as it's truly", "# thread-critical. Database backends should use @async_unsafe to protect", "# their code f...
[ 136, 4 ]
[ 147, 55 ]
python
en
['en', 'error', 'th']
False
ConnectionHandler.ensure_defaults
(self, alias)
Put the defaults into the settings dictionary for a given connection where no settings is provided.
Put the defaults into the settings dictionary for a given connection where no settings is provided.
def ensure_defaults(self, alias): """ Put the defaults into the settings dictionary for a given connection where no settings is provided. """ try: conn = self.databases[alias] except KeyError: raise ConnectionDoesNotExist("The connection %s doesn't...
[ "def", "ensure_defaults", "(", "self", ",", "alias", ")", ":", "try", ":", "conn", "=", "self", ".", "databases", "[", "alias", "]", "except", "KeyError", ":", "raise", "ConnectionDoesNotExist", "(", "\"The connection %s doesn't exist\"", "%", "alias", ")", "c...
[ 165, 4 ]
[ 184, 40 ]
python
en
['en', 'error', 'th']
False
ConnectionHandler.prepare_test_settings
(self, alias)
Make sure the test settings are available in the 'TEST' sub-dictionary.
Make sure the test settings are available in the 'TEST' sub-dictionary.
def prepare_test_settings(self, alias): """ Make sure the test settings are available in the 'TEST' sub-dictionary. """ try: conn = self.databases[alias] except KeyError: raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) test...
[ "def", "prepare_test_settings", "(", "self", ",", "alias", ")", ":", "try", ":", "conn", "=", "self", ".", "databases", "[", "alias", "]", "except", "KeyError", ":", "raise", "ConnectionDoesNotExist", "(", "\"The connection %s doesn't exist\"", "%", "alias", ")"...
[ 186, 4 ]
[ 197, 47 ]
python
en
['en', 'error', 'th']
False
ConnectionRouter.__init__
(self, routers=None)
If routers is not specified, default to settings.DATABASE_ROUTERS.
If routers is not specified, default to settings.DATABASE_ROUTERS.
def __init__(self, routers=None): """ If routers is not specified, default to settings.DATABASE_ROUTERS. """ self._routers = routers
[ "def", "__init__", "(", "self", ",", "routers", "=", "None", ")", ":", "self", ".", "_routers", "=", "routers" ]
[ 233, 4 ]
[ 237, 31 ]
python
en
['en', 'error', 'th']
False
ConnectionRouter.get_migratable_models
(self, app_config, db, include_auto_created=False)
Return app models allowed to be migrated on provided db.
Return app models allowed to be migrated on provided db.
def get_migratable_models(self, app_config, db, include_auto_created=False): """Return app models allowed to be migrated on provided db.""" models = app_config.get_models(include_auto_created=include_auto_created) return [model for model in models if self.allow_migrate_model(db, model)]
[ "def", "get_migratable_models", "(", "self", ",", "app_config", ",", "db", ",", "include_auto_created", "=", "False", ")", ":", "models", "=", "app_config", ".", "get_models", "(", "include_auto_created", "=", "include_auto_created", ")", "return", "[", "model", ...
[ 309, 4 ]
[ 312, 81 ]
python
en
['en', 'en', 'en']
True
Marker.evaluate
(self, environment=None)
Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process.
Evaluate a marker.
def evaluate(self, environment=None): """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Pyt...
[ "def", "evaluate", "(", "self", ",", "environment", "=", "None", ")", ":", "current_environment", "=", "default_environment", "(", ")", "if", "environment", "is", "not", "None", ":", "current_environment", ".", "update", "(", "environment", ")", "return", "_ev...
[ 282, 4 ]
[ 295, 68 ]
python
en
['en', 'en', 'en']
True
Storage.open
(self, name, mode='rb')
Retrieve the specified file from storage.
Retrieve the specified file from storage.
def open(self, name, mode='rb'): """Retrieve the specified file from storage.""" return self._open(name, mode)
[ "def", "open", "(", "self", ",", "name", ",", "mode", "=", "'rb'", ")", ":", "return", "self", ".", "_open", "(", "name", ",", "mode", ")" ]
[ 33, 4 ]
[ 35, 37 ]
python
en
['en', 'en', 'en']
True
Storage.save
(self, name, content, max_length=None)
Save new content to the file specified by name. The content should be a proper File object or any Python file-like object, ready to be read from the beginning.
Save new content to the file specified by name. The content should be a proper File object or any Python file-like object, ready to be read from the beginning.
def save(self, name, content, max_length=None): """ Save new content to the file specified by name. The content should be a proper File object or any Python file-like object, ready to be read from the beginning. """ # Get the proper name for the file, as it will actually ...
[ "def", "save", "(", "self", ",", "name", ",", "content", ",", "max_length", "=", "None", ")", ":", "# Get the proper name for the file, as it will actually be saved.", "if", "name", "is", "None", ":", "name", "=", "content", ".", "name", "if", "not", "hasattr", ...
[ 37, 4 ]
[ 51, 40 ]
python
en
['en', 'error', 'th']
False
Storage.get_valid_name
(self, name)
Return a filename, based on the provided filename, that's suitable for use in the target storage system.
Return a filename, based on the provided filename, that's suitable for use in the target storage system.
def get_valid_name(self, name): """ Return a filename, based on the provided filename, that's suitable for use in the target storage system. """ return get_valid_filename(name)
[ "def", "get_valid_name", "(", "self", ",", "name", ")", ":", "return", "get_valid_filename", "(", "name", ")" ]
[ 55, 4 ]
[ 60, 39 ]
python
en
['en', 'error', 'th']
False
Storage.get_alternative_name
(self, file_root, file_ext)
Return an alternative filename, by adding an underscore and a random 7 character alphanumeric string (before the file extension, if one exists) to the filename.
Return an alternative filename, by adding an underscore and a random 7 character alphanumeric string (before the file extension, if one exists) to the filename.
def get_alternative_name(self, file_root, file_ext): """ Return an alternative filename, by adding an underscore and a random 7 character alphanumeric string (before the file extension, if one exists) to the filename. """ return '%s_%s%s' % (file_root, get_random_string(7...
[ "def", "get_alternative_name", "(", "self", ",", "file_root", ",", "file_ext", ")", ":", "return", "'%s_%s%s'", "%", "(", "file_root", ",", "get_random_string", "(", "7", ")", ",", "file_ext", ")" ]
[ 62, 4 ]
[ 68, 70 ]
python
en
['en', 'error', 'th']
False