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
BaseStorage._get
(self, *args, **kwargs)
Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``. **This method must be implemente...
Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)``.
def _get(self, *args, **kwargs): """ Retrieves a list of stored messages. Returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were, in fact, stored and retrieved; e.g., ``(messages, all_retrieved)`...
[ "def", "_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseStorage must provide a _get() method'", ")" ]
[ 96, 4 ]
[ 109, 91 ]
python
en
['en', 'error', 'th']
False
BaseStorage._store
(self, messages, response, *args, **kwargs)
Stores a list of messages, returning a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.**
Stores a list of messages, returning a list of any messages which could not be stored.
def _store(self, messages, response, *args, **kwargs): """ Stores a list of messages, returning a list of any messages which could not be stored. One type of object must be able to be stored, ``Message``. **This method must be implemented by a subclass.** """ ra...
[ "def", "_store", "(", "self", ",", "messages", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseStorage must provide a _store() method'", ")" ]
[ 111, 4 ]
[ 120, 93 ]
python
en
['en', 'error', 'th']
False
BaseStorage._prepare_messages
(self, messages)
Prepares a list of messages for storage.
Prepares a list of messages for storage.
def _prepare_messages(self, messages): """ Prepares a list of messages for storage. """ for message in messages: message._prepare()
[ "def", "_prepare_messages", "(", "self", ",", "messages", ")", ":", "for", "message", "in", "messages", ":", "message", ".", "_prepare", "(", ")" ]
[ 122, 4 ]
[ 127, 30 ]
python
en
['en', 'error', 'th']
False
BaseStorage.update
(self, response)
Stores all unread messages. If the backend has yet to be iterated, previously stored messages will be stored again. Otherwise, only messages added after the last iteration will be stored.
Stores all unread messages.
def update(self, response): """ Stores all unread messages. If the backend has yet to be iterated, previously stored messages will be stored again. Otherwise, only messages added after the last iteration will be stored. """ self._prepare_messages(self._queued_mes...
[ "def", "update", "(", "self", ",", "response", ")", ":", "self", ".", "_prepare_messages", "(", "self", ".", "_queued_messages", ")", "if", "self", ".", "used", ":", "return", "self", ".", "_store", "(", "self", ".", "_queued_messages", ",", "response", ...
[ 129, 4 ]
[ 142, 50 ]
python
en
['en', 'error', 'th']
False
BaseStorage.add
(self, level, message, extra_tags='')
Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``).
Queues a message to be stored.
def add(self, level, message, extra_tags=''): """ Queues a message to be stored. The message is only queued if it contained something and its level is not less than the recording level (``self.level``). """ if not message: return # Check that the mess...
[ "def", "add", "(", "self", ",", "level", ",", "message", ",", "extra_tags", "=", "''", ")", ":", "if", "not", "message", ":", "return", "# Check that the message level is not less than the recording level.", "level", "=", "int", "(", "level", ")", "if", "level",...
[ 144, 4 ]
[ 160, 45 ]
python
en
['en', 'error', 'th']
False
BaseStorage._get_level
(self)
Returns the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used.
Returns the minimum recorded level.
def _get_level(self): """ Returns the minimum recorded level. The default level is the ``MESSAGE_LEVEL`` setting. If this is not found, the ``INFO`` level is used. """ if not hasattr(self, '_level'): self._level = getattr(settings, 'MESSAGE_LEVEL', constants....
[ "def", "_get_level", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_level'", ")", ":", "self", ".", "_level", "=", "getattr", "(", "settings", ",", "'MESSAGE_LEVEL'", ",", "constants", ".", "INFO", ")", "return", "self", ".", "_lev...
[ 162, 4 ]
[ 171, 26 ]
python
en
['en', 'error', 'th']
False
BaseStorage._set_level
(self, value=None)
Sets a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method).
Sets a custom minimum recorded level.
def _set_level(self, value=None): """ Sets a custom minimum recorded level. If set to ``None``, the default level will be used (see the ``_get_level`` method). """ if value is None and hasattr(self, '_level'): del self._level else: self._l...
[ "def", "_set_level", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", "and", "hasattr", "(", "self", ",", "'_level'", ")", ":", "del", "self", ".", "_level", "else", ":", "self", ".", "_level", "=", "int", "(", "value"...
[ 173, 4 ]
[ 183, 36 ]
python
en
['en', 'error', 'th']
False
escape
(text)
Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. """ return mark_safe(force_text(text).replace('&', '&amp;').replace('<', '&lt;') .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
[ "def", "escape", "(", "text", ")", ":", "return", "mark_safe", "(", "force_text", "(", "text", ")", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", ".", "replace", "(", "'>'", ",", "'&gt;'", ")", "."...
[ 42, 0 ]
[ 48, 75 ]
python
en
['en', 'error', 'th']
False
escapejs
(value)
Hex encodes characters for use in JavaScript strings.
Hex encodes characters for use in JavaScript strings.
def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" return mark_safe(force_text(value).translate(_js_escapes))
[ "def", "escapejs", "(", "value", ")", ":", "return", "mark_safe", "(", "force_text", "(", "value", ")", ".", "translate", "(", "_js_escapes", ")", ")" ]
[ 69, 0 ]
[ 71, 62 ]
python
en
['en', 'en', 'en']
True
conditional_escape
(text)
Similar to escape(), except that it doesn't operate on pre-escaped strings.
Similar to escape(), except that it doesn't operate on pre-escaped strings.
def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. """ if hasattr(text, '__html__'): return text.__html__() else: return escape(text)
[ "def", "conditional_escape", "(", "text", ")", ":", "if", "hasattr", "(", "text", ",", "'__html__'", ")", ":", "return", "text", ".", "__html__", "(", ")", "else", ":", "return", "escape", "(", "text", ")" ]
[ 75, 0 ]
[ 82, 27 ]
python
en
['en', 'error', 'th']
False
format_html
(format_string, *args, **kwargs)
Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments.
Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments.
def format_html(format_string, *args, **kwargs): """ Similar to str.format, but passes all arguments through conditional_escape, and calls 'mark_safe' on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(condit...
[ "def", "format_html", "(", "format_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args_safe", "=", "map", "(", "conditional_escape", ",", "args", ")", "kwargs_safe", "=", "dict", "(", "(", "k", ",", "conditional_escape", "(", "v", ")", ...
[ 85, 0 ]
[ 93, 69 ]
python
en
['en', 'error', 'th']
False
format_html_join
(sep, format_string, args_generator)
A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed...
A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape.
def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an ite...
[ "def", "format_html_join", "(", "sep", ",", "format_string", ",", "args_generator", ")", ":", "return", "mark_safe", "(", "conditional_escape", "(", "sep", ")", ".", "join", "(", "format_html", "(", "format_string", ",", "*", "tuple", "(", "args", ")", ")", ...
[ 96, 0 ]
[ 113, 36 ]
python
en
['en', 'error', 'th']
False
linebreaks
(value, autoescape=False)
Converts newlines into <p> and <br />s.
Converts newlines into <p> and <br />s.
def linebreaks(value, autoescape=False): """Converts newlines into <p> and <br />s.""" value = normalize_newlines(value) paras = re.split('\n{2,}', value) if autoescape: paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras] else: paras = ['<p>%s</p>' % p.replace('\...
[ "def", "linebreaks", "(", "value", ",", "autoescape", "=", "False", ")", ":", "value", "=", "normalize_newlines", "(", "value", ")", "paras", "=", "re", ".", "split", "(", "'\\n{2,}'", ",", "value", ")", "if", "autoescape", ":", "paras", "=", "[", "'<p...
[ 116, 0 ]
[ 124, 29 ]
python
en
['en', 'en', 'en']
True
_strip_once
(value)
Internal tag stripping utility used by strip_tags.
Internal tag stripping utility used by strip_tags.
def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() try: s.feed(value) except HTMLParseError: return value try: s.close() except (HTMLParseError, UnboundLocalError): # UnboundLocalError because of http://bugs...
[ "def", "_strip_once", "(", "value", ")", ":", "s", "=", "MLStripper", "(", ")", "try", ":", "s", ".", "feed", "(", "value", ")", "except", "HTMLParseError", ":", "return", "value", "try", ":", "s", ".", "close", "(", ")", "except", "(", "HTMLParseErr...
[ 152, 0 ]
[ 168, 27 ]
python
en
['en', 'error', 'th']
False
strip_tags
(value)
Returns the given HTML with all tags stripped.
Returns the given HTML with all tags stripped.
def strip_tags(value): """Returns the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. while '<' in value and '>' in value: new_value = _strip_once(value) ...
[ "def", "strip_tags", "(", "value", ")", ":", "# Note: in typical case this loop executes _strip_once once. Loop condition", "# is redundant, but helps to reduce number of executions of _strip_once.", "while", "'<'", "in", "value", "and", "'>'", "in", "value", ":", "new_value", "=...
[ 171, 0 ]
[ 181, 16 ]
python
en
['en', 'en', 'en']
True
remove_tags
(html, tags)
Returns the given HTML with given tags removed.
Returns the given HTML with given tags removed.
def remove_tags(html, tags): """Returns the given HTML with given tags removed.""" warnings.warn( "django.utils.html.remove_tags() and the removetags template filter " "are deprecated. Consider using the bleach library instead.", RemovedInDjango20Warning, stacklevel=3 ) tags = [r...
[ "def", "remove_tags", "(", "html", ",", "tags", ")", ":", "warnings", ".", "warn", "(", "\"django.utils.html.remove_tags() and the removetags template filter \"", "\"are deprecated. Consider using the bleach library instead.\"", ",", "RemovedInDjango20Warning", ",", "stacklevel", ...
[ 185, 0 ]
[ 198, 15 ]
python
en
['en', 'en', 'en']
True
strip_spaces_between_tags
(value)
Returns the given HTML with spaces between tags removed.
Returns the given HTML with spaces between tags removed.
def strip_spaces_between_tags(value): """Returns the given HTML with spaces between tags removed.""" return re.sub(r'>\s+<', '><', force_text(value))
[ "def", "strip_spaces_between_tags", "(", "value", ")", ":", "return", "re", ".", "sub", "(", "r'>\\s+<'", ",", "'><'", ",", "force_text", "(", "value", ")", ")" ]
[ 202, 0 ]
[ 204, 52 ]
python
en
['en', 'en', 'en']
True
strip_entities
(value)
Returns the given HTML with all entities (&something;) stripped.
Returns the given HTML with all entities (&something;) stripped.
def strip_entities(value): """Returns the given HTML with all entities (&something;) stripped.""" warnings.warn( "django.utils.html.strip_entities() is deprecated.", RemovedInDjango20Warning, stacklevel=2 ) return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
[ "def", "strip_entities", "(", "value", ")", ":", "warnings", ".", "warn", "(", "\"django.utils.html.strip_entities() is deprecated.\"", ",", "RemovedInDjango20Warning", ",", "stacklevel", "=", "2", ")", "return", "re", ".", "sub", "(", "r'&(?:\\w+|#\\d+);'", ",", "'...
[ 208, 0 ]
[ 214, 59 ]
python
en
['en', 'en', 'en']
True
smart_urlquote
(url)
Quotes a URL if it isn't already quoted.
Quotes a URL if it isn't already quoted.
def smart_urlquote(url): "Quotes a URL if it isn't already quoted." def unquote_quote(segment): segment = unquote(force_str(segment)) # Tilde is part of RFC3986 Unreserved Characters # http://tools.ietf.org/html/rfc3986#section-2.3 # See also http://bugs.python.org/issue16285 ...
[ "def", "smart_urlquote", "(", "url", ")", ":", "def", "unquote_quote", "(", "segment", ")", ":", "segment", "=", "unquote", "(", "force_str", "(", "segment", ")", ")", "# Tilde is part of RFC3986 Unreserved Characters", "# http://tools.ietf.org/html/rfc3986#section-2.3", ...
[ 218, 0 ]
[ 251, 62 ]
python
en
['en', 'en', 'en']
True
urlize
(text, trim_url_limit=None, nofollow=False, autoescape=False)
Converts any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening p...
Converts any URLs in text into clickable links.
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Converts any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing pu...
[ "def", "urlize", "(", "text", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "autoescape", "=", "False", ")", ":", "safe_input", "=", "isinstance", "(", "text", ",", "SafeData", ")", "def", "trim_url", "(", "x", ",", "limit", "...
[ 254, 0 ]
[ 350, 25 ]
python
en
['en', 'error', 'th']
False
avoid_wrapping
(value)
Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces.
Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces.
def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0")
[ "def", "avoid_wrapping", "(", "value", ")", ":", "return", "value", ".", "replace", "(", "\" \"", ",", "\"\\xa0\"", ")" ]
[ 354, 0 ]
[ 359, 37 ]
python
en
['en', 'error', 'th']
False
render_tex
(tex: str, is_inline: bool = True)
r"""Render a TeX string into HTML using KaTeX Returns the HTML string, or None if there was some error in the TeX syntax Keyword arguments: tex -- Text string with the TeX to render Don't include delimiters ('$$', '\[ \]', etc.) is_inline -- Boolean setting that indicates whether the render...
r"""Render a TeX string into HTML using KaTeX
def render_tex(tex: str, is_inline: bool = True) -> Optional[str]: r"""Render a TeX string into HTML using KaTeX Returns the HTML string, or None if there was some error in the TeX syntax Keyword arguments: tex -- Text string with the TeX to render Don't include delimiters ('$$', '\[ \]', e...
[ "def", "render_tex", "(", "tex", ":", "str", ",", "is_inline", ":", "bool", "=", "True", ")", "->", "Optional", "[", "str", "]", ":", "katex_path", "=", "(", "static_path", "(", "\"webpack-bundles/katex-cli.js\"", ")", "if", "settings", ".", "PRODUCTION", ...
[ 10, 0 ]
[ 42, 19 ]
python
en
['it', 'en', 'en']
True
setup
()
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry.
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry.
def setup(): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. """ from django.apps import apps from django.conf import settings from django.utils.log import configure_logging configure_logging(set...
[ "def", "setup", "(", ")", ":", "from", "django", ".", "apps", "import", "apps", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "utils", ".", "log", "import", "configure_logging", "configure_logging", "(", "settings", ".", "LOGGIN...
[ 12, 0 ]
[ 22, 42 ]
python
en
['en', 'error', 'th']
False
SemaphoreHookTests.get_unknown_event
(self, fixture_name: str)
Return modified payload with revision.reference_type changed
Return modified payload with revision.reference_type changed
def get_unknown_event(self, fixture_name: str) -> str: """Return modified payload with revision.reference_type changed""" fixture_data = orjson.loads( self.webhook_fixture_data("semaphore", fixture_name, file_type="json") ) fixture_data["revision"]["reference_type"] = "unknow...
[ "def", "get_unknown_event", "(", "self", ",", "fixture_name", ":", "str", ")", "->", "str", ":", "fixture_data", "=", "orjson", ".", "loads", "(", "self", ".", "webhook_fixture_data", "(", "\"semaphore\"", ",", "fixture_name", ",", "file_type", "=", "\"json\""...
[ 131, 4 ]
[ 137, 27 ]
python
en
['en', 'en', 'en']
True
Reference.references_table
(self, table)
Return whether or not this instance references the specified table.
Return whether or not this instance references the specified table.
def references_table(self, table): """ Return whether or not this instance references the specified table. """ return False
[ "def", "references_table", "(", "self", ",", "table", ")", ":", "return", "False" ]
[ 9, 4 ]
[ 13, 20 ]
python
en
['en', 'error', 'th']
False
Reference.references_column
(self, table, column)
Return whether or not this instance references the specified column.
Return whether or not this instance references the specified column.
def references_column(self, table, column): """ Return whether or not this instance references the specified column. """ return False
[ "def", "references_column", "(", "self", ",", "table", ",", "column", ")", ":", "return", "False" ]
[ 15, 4 ]
[ 19, 20 ]
python
en
['en', 'error', 'th']
False
Reference.rename_table_references
(self, old_table, new_table)
Rename all references to the old_name to the new_table.
Rename all references to the old_name to the new_table.
def rename_table_references(self, old_table, new_table): """ Rename all references to the old_name to the new_table. """ pass
[ "def", "rename_table_references", "(", "self", ",", "old_table", ",", "new_table", ")", ":", "pass" ]
[ 21, 4 ]
[ 25, 12 ]
python
en
['en', 'error', 'th']
False
Reference.rename_column_references
(self, table, old_column, new_column)
Rename all references to the old_column to the new_column.
Rename all references to the old_column to the new_column.
def rename_column_references(self, table, old_column, new_column): """ Rename all references to the old_column to the new_column. """ pass
[ "def", "rename_column_references", "(", "self", ",", "table", ",", "old_column", ",", "new_column", ")", ":", "pass" ]
[ 27, 4 ]
[ 31, 12 ]
python
en
['en', 'error', 'th']
False
canonicalize_version
(_version)
This is very similar to Version.__str__, but has one subtle difference with the way it handles the release segment.
This is very similar to Version.__str__, but has one subtle difference with the way it handles the release segment.
def canonicalize_version(_version): # type: (str) -> Union[Version, str] """ This is very similar to Version.__str__, but has one subtle difference with the way it handles the release segment. """ try: version = Version(_version) except InvalidVersion: # Legacy versions cann...
[ "def", "canonicalize_version", "(", "_version", ")", ":", "# type: (str) -> Union[Version, str]", "try", ":", "version", "=", "Version", "(", "_version", ")", "except", "InvalidVersion", ":", "# Legacy versions cannot be normalized", "return", "_version", "parts", "=", ...
[ 22, 0 ]
[ 61, 25 ]
python
en
['en', 'error', 'th']
False
test_validate
(schema)
Test for successful validation
Test for successful validation
def test_validate(schema): """Test for successful validation""" schema, pass_file, _ = schema val = utils.Validator(schema_path=schema) val.validate(pass_file)
[ "def", "test_validate", "(", "schema", ")", ":", "schema", ",", "pass_file", ",", "_", "=", "schema", "val", "=", "utils", ".", "Validator", "(", "schema_path", "=", "schema", ")", "val", ".", "validate", "(", "pass_file", ")" ]
[ 20, 0 ]
[ 24, 27 ]
python
en
['en', 'en', 'en']
True
test_fail_validate
(schema)
Test for invalid file
Test for invalid file
def test_fail_validate(schema): """Test for invalid file""" schema, _, fail_file = schema val = utils.Validator(schema_path=schema) with pytest.raises(ValidationError): val.validate(fail_file)
[ "def", "test_fail_validate", "(", "schema", ")", ":", "schema", ",", "_", ",", "fail_file", "=", "schema", "val", "=", "utils", ".", "Validator", "(", "schema_path", "=", "schema", ")", "with", "pytest", ".", "raises", "(", "ValidationError", ")", ":", "...
[ 27, 0 ]
[ 32, 31 ]
python
en
['en', 'en', 'en']
True
test_is_url
(test_urls)
should respond true/false for url
should respond true/false for url
def test_is_url(test_urls): """should respond true/false for url""" u = test_urls assert utils.is_url(u["valid"]) assert utils.is_url(u["valid_https"]) assert not utils.is_url(u["invalid"]) assert not utils.is_url(u["invalid_file"])
[ "def", "test_is_url", "(", "test_urls", ")", ":", "u", "=", "test_urls", "assert", "utils", ".", "is_url", "(", "u", "[", "\"valid\"", "]", ")", "assert", "utils", ".", "is_url", "(", "u", "[", "\"valid_https\"", "]", ")", "assert", "not", "utils", "."...
[ 35, 0 ]
[ 41, 46 ]
python
en
['en', 'pt', 'en']
True
test_ensure_valid_url
(mocker, test_urls)
should ensure url is valid
should ensure url is valid
def test_ensure_valid_url(mocker, test_urls): """should ensure url is valid""" u = test_urls with pytest.raises(InvalidURL): utils.ensure_valid_url(test_urls["invalid"]) with pytest.raises(ConnectionError): mocker.patch.object(utils, "is_url", return_value=True) mock_head = mocke...
[ "def", "test_ensure_valid_url", "(", "mocker", ",", "test_urls", ")", ":", "u", "=", "test_urls", "with", "pytest", ".", "raises", "(", "InvalidURL", ")", ":", "utils", ".", "ensure_valid_url", "(", "test_urls", "[", "\"invalid\"", "]", ")", "with", "pytest"...
[ 44, 0 ]
[ 58, 31 ]
python
en
['en', 'af', 'en']
True
test_ensure_existing_dir
(tmp_path)
should ensure dir exists
should ensure dir exists
def test_ensure_existing_dir(tmp_path): """should ensure dir exists""" not_exist = tmp_path / "i_dont_exist" file = tmp_path / "file.txt" file.touch() with pytest.raises(NotADirectoryError): utils.ensure_existing_dir(not_exist) with pytest.raises(NotADirectoryError): utils.ensure...
[ "def", "test_ensure_existing_dir", "(", "tmp_path", ")", ":", "not_exist", "=", "tmp_path", "/", "\"i_dont_exist\"", "file", "=", "tmp_path", "/", "\"file.txt\"", "file", ".", "touch", "(", ")", "with", "pytest", ".", "raises", "(", "NotADirectoryError", ")", ...
[ 61, 0 ]
[ 73, 26 ]
python
en
['en', 'ca', 'en']
True
test_is_downloadable
(mocker, test_urls)
should check if url can be downloaded from
should check if url can be downloaded from
def test_is_downloadable(mocker, test_urls): """should check if url can be downloaded from""" u = test_urls uheaders = u["headers"] mock_head = mocker.patch.object(requests, "head") head_mock_val = mocker.PropertyMock( side_effect=[uheaders["not_download"], uheaders["can_download"]] ) ...
[ "def", "test_is_downloadable", "(", "mocker", ",", "test_urls", ")", ":", "u", "=", "test_urls", "uheaders", "=", "u", "[", "\"headers\"", "]", "mock_head", "=", "mocker", ".", "patch", ".", "object", "(", "requests", ",", "\"head\"", ")", "head_mock_val", ...
[ 76, 0 ]
[ 87, 44 ]
python
en
['en', 'en', 'en']
True
test_get_url_filename
(test_urls)
should return filename
should return filename
def test_get_url_filename(test_urls): """should return filename""" filename = "archive_test_stub.tar.gz" result = utils.get_url_filename(test_urls["download"]) assert result == filename
[ "def", "test_get_url_filename", "(", "test_urls", ")", ":", "filename", "=", "\"archive_test_stub.tar.gz\"", "result", "=", "utils", ".", "get_url_filename", "(", "test_urls", "[", "\"download\"", "]", ")", "assert", "result", "==", "filename" ]
[ 90, 0 ]
[ 94, 29 ]
python
en
['en', 'id', 'en']
True
test_get_package_meta
(mocker, requests_mock)
should get package meta
should get package meta
def test_get_package_meta(mocker, requests_mock): """should get package meta""" mock_data = { "releases": { "0.0.0": [{"url": "early-version.tar.gz"}], "0.1.0": [ { "url": "do-not-return-me", }, {"url": "return-m...
[ "def", "test_get_package_meta", "(", "mocker", ",", "requests_mock", ")", ":", "mock_data", "=", "{", "\"releases\"", ":", "{", "\"0.0.0\"", ":", "[", "{", "\"url\"", ":", "\"early-version.tar.gz\"", "}", "]", ",", "\"0.1.0\"", ":", "[", "{", "\"url\"", ":",...
[ 131, 0 ]
[ 148, 52 ]
python
en
['en', 'af', 'en']
True
test_extract_tarbytes
(mocker)
should extract tar file from memory
should extract tar file from memory
def test_extract_tarbytes(mocker): """should extract tar file from memory""" test_bytes = bytearray("foobar", "utf-8") mock_io = mocker.patch.object(utils.helpers.io, "BytesIO") mock_io.return_value = io.BytesIO(test_bytes) mock_tarfile = mocker.patch.object(utils.helpers, "tarfile") mock_tar = ...
[ "def", "test_extract_tarbytes", "(", "mocker", ")", ":", "test_bytes", "=", "bytearray", "(", "\"foobar\"", ",", "\"utf-8\"", ")", "mock_io", "=", "mocker", ".", "patch", ".", "object", "(", "utils", ".", "helpers", ".", "io", ",", "\"BytesIO\"", ")", "moc...
[ 151, 0 ]
[ 160, 57 ]
python
en
['en', 'en', 'en']
True
test_iter_requirements
(mocker, tmp_path)
should iter requirements
should iter requirements
def test_iter_requirements(mocker, tmp_path): """should iter requirements""" tmp_file = tmp_path / "tmp_reqs.txt" tmp_file.touch() tmp_file.write_text("micropy-cli==1.0.0") result = next(utils.iter_requirements(tmp_file)) assert result.name == "micropy-cli" assert result.specs == [("==", "1....
[ "def", "test_iter_requirements", "(", "mocker", ",", "tmp_path", ")", ":", "tmp_file", "=", "tmp_path", "/", "\"tmp_reqs.txt\"", "tmp_file", ".", "touch", "(", ")", "tmp_file", ".", "write_text", "(", "\"micropy-cli==1.0.0\"", ")", "result", "=", "next", "(", ...
[ 163, 0 ]
[ 170, 44 ]
python
en
['en', 'en', 'en']
True
test_create_dir_link
(mocker, tmp_path)
Should create a symlink or directory junction if needed
Should create a symlink or directory junction if needed
def test_create_dir_link(mocker, tmp_path): """Should create a symlink or directory junction if needed""" targ_path = tmp_path / "target_dir" targ_path.mkdir() link_path = tmp_path / "link_path" mock_sys = mocker.patch.object(utils.helpers, "sys") mock_platform = type(mock_sys).platform = mocker...
[ "def", "test_create_dir_link", "(", "mocker", ",", "tmp_path", ")", ":", "targ_path", "=", "tmp_path", "/", "\"target_dir\"", "targ_path", ".", "mkdir", "(", ")", "link_path", "=", "tmp_path", "/", "\"link_path\"", "mock_sys", "=", "mocker", ".", "patch", ".",...
[ 173, 0 ]
[ 200, 51 ]
python
en
['en', 'en', 'en']
True
test_is_dir_link
(mocker, tmp_path)
Should test if a path is a symlink or directory junction
Should test if a path is a symlink or directory junction
def test_is_dir_link(mocker, tmp_path): """Should test if a path is a symlink or directory junction""" link_path = tmp_path / "link" targ_path = tmp_path / "target" mock_sys = mocker.patch.object(utils.helpers, "sys") mock_platform = type(mock_sys).platform = mocker.PropertyMock() mock_path = mo...
[ "def", "test_is_dir_link", "(", "mocker", ",", "tmp_path", ")", ":", "link_path", "=", "tmp_path", "/", "\"link\"", "targ_path", "=", "tmp_path", "/", "\"target\"", "mock_sys", "=", "mocker", ".", "patch", ".", "object", "(", "utils", ".", "helpers", ",", ...
[ 203, 0 ]
[ 225, 43 ]
python
en
['en', 'en', 'en']
True
test_is_update_available
(mocker, requests_mock, versions, expect)
Test self-update check method
Test self-update check method
def test_is_update_available(mocker, requests_mock, versions, expect): """Test self-update check method""" fake_data = {"releases": {k: [] for k in versions}} requests_mock.get("https://pypi.org/pypi/micropy-cli/json", json=fake_data) mocker.patch("micropy.__version__", "0.0.0") utils.helpers.get_ca...
[ "def", "test_is_update_available", "(", "mocker", ",", "requests_mock", ",", "versions", ",", "expect", ")", ":", "fake_data", "=", "{", "\"releases\"", ":", "{", "k", ":", "[", "]", "for", "k", "in", "versions", "}", "}", "requests_mock", ".", "get", "(...
[ 236, 0 ]
[ 242, 56 ]
python
en
['id', 'en', 'en']
True
test_stream_download
(mocker)
Test stream download
Test stream download
def test_stream_download(mocker): """Test stream download""" mock_req = mocker.patch.object(utils.helpers, "requests") mock_stream = mocker.MagicMock() mock_stream.headers = {"content-length": "1000"} mock_req.get.return_value = mock_stream tqdm_mock = mocker.patch.object(utils.helpers, "tqdm") ...
[ "def", "test_stream_download", "(", "mocker", ")", ":", "mock_req", "=", "mocker", ".", "patch", ".", "object", "(", "utils", ".", "helpers", ",", "\"requests\"", ")", "mock_stream", "=", "mocker", ".", "MagicMock", "(", ")", "mock_stream", ".", "headers", ...
[ 245, 0 ]
[ 259, 74 ]
python
en
['en', 'de', 'en']
True
find_module
(module, paths=None)
Just like 'imp.find_module()', but with package support
Just like 'imp.find_module()', but with package support
def find_module(module, paths=None): """Just like 'imp.find_module()', but with package support""" spec = find_spec(module, paths) if spec is None: raise ImportError("Can't find %s" % module) if not spec.has_location and hasattr(spec, 'submodule_search_locations'): spec = importlib.util....
[ "def", "find_module", "(", "module", ",", "paths", "=", "None", ")", ":", "spec", "=", "find_spec", "(", "module", ",", "paths", ")", "if", "spec", "is", "None", ":", "raise", "ImportError", "(", "\"Can't find %s\"", "%", "module", ")", "if", "not", "s...
[ 28, 0 ]
[ 67, 43 ]
python
en
['en', 'en', 'en']
True
SNNL_example
( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR, )
A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_fa...
A simple model trained to minimize Cross Entropy and Maximize Soft Nearest Neighbor Loss at each internal layer. This outputs a TSNE of the sign of the adversarial gradients of a trained model. A model with a negative SNNL_factor will show little or no class clusters, while a model with a 0 SNNL_fa...
def SNNL_example( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, nb_filters=NB_FILTERS, SNNL_factor=SNNL_FACTOR, output_dir=OUTPUT_DIR, ): """ A simple model trained to minimize Cross ...
[ "def", "SNNL_example", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_RA...
[ 38, 0 ]
[ 171, 5 ]
python
en
['en', 'error', 'th']
False
shquote
(arg)
Quote an argument for later parsing by shlex.split()
Quote an argument for later parsing by shlex.split()
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split() != [arg]: return repr(arg) return arg
[ "def", "shquote", "(", "arg", ")", ":", "for", "c", "in", "'\"'", ",", "\"'\"", ",", "\"\\\\\"", ",", "\"#\"", ":", "if", "c", "in", "arg", ":", "return", "repr", "(", "arg", ")", "if", "arg", ".", "split", "(", ")", "!=", "[", "arg", "]", ":...
[ 7, 0 ]
[ 14, 14 ]
python
en
['en', 'en', 'en']
True
SessionStore.flush
(self)
Remove the current session data from the database and regenerate the key.
Remove the current session data from the database and regenerate the key.
def flush(self): """ Remove the current session data from the database and regenerate the key. """ self.clear() self.delete(self.session_key) self._session_key = None
[ "def", "flush", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "delete", "(", "self", ".", "session_key", ")", "self", ".", "_session_key", "=", "None" ]
[ 57, 4 ]
[ 64, 32 ]
python
en
['en', 'error', 'th']
False
SessionBase.encode
(self, session_dict)
Return the given session dictionary serialized and encoded as a string.
Return the given session dictionary serialized and encoded as a string.
def encode(self, session_dict): "Return the given session dictionary serialized and encoded as a string." serialized = self.serializer().dumps(session_dict) hash = self._hash(serialized) return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii')
[ "def", "encode", "(", "self", ",", "session_dict", ")", ":", "serialized", "=", "self", ".", "serializer", "(", ")", ".", "dumps", "(", "session_dict", ")", "hash", "=", "self", ".", "_hash", "(", "serialized", ")", "return", "base64", ".", "b64encode", ...
[ 102, 4 ]
[ 106, 82 ]
python
en
['en', 'en', 'en']
True
SessionBase.is_empty
(self)
Return True when there is no session_key and the session is empty.
Return True when there is no session_key and the session is empty.
def is_empty(self): "Return True when there is no session_key and the session is empty." try: return not self._session_key and not self._session_cache except AttributeError: return True
[ "def", "is_empty", "(", "self", ")", ":", "try", ":", "return", "not", "self", ".", "_session_key", "and", "not", "self", ".", "_session_cache", "except", "AttributeError", ":", "return", "True" ]
[ 150, 4 ]
[ 155, 23 ]
python
en
['en', 'en', 'en']
True
SessionBase._get_new_session_key
(self)
Return session key that isn't being used.
Return session key that isn't being used.
def _get_new_session_key(self): "Return session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): return session_key
[ "def", "_get_new_session_key", "(", "self", ")", ":", "while", "True", ":", "session_key", "=", "get_random_string", "(", "32", ",", "VALID_KEY_CHARS", ")", "if", "not", "self", ".", "exists", "(", "session_key", ")", ":", "return", "session_key" ]
[ 157, 4 ]
[ 162, 34 ]
python
en
['en', 'en', 'en']
True
SessionBase._validate_session_key
(self, key)
Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security.
Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security.
def _validate_session_key(self, key): """ Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security. """ return key and len(key) >= 8
[ "def", "_validate_session_key", "(", "self", ",", "key", ")", ":", "return", "key", "and", "len", "(", "key", ")", ">=", "8" ]
[ 169, 4 ]
[ 174, 36 ]
python
en
['en', 'error', 'th']
False
SessionBase._set_session_key
(self, value)
Validate session key on assignment. Invalid values will set to None.
Validate session key on assignment. Invalid values will set to None.
def _set_session_key(self, value): """ Validate session key on assignment. Invalid values will set to None. """ if self._validate_session_key(value): self.__session_key = value else: self.__session_key = None
[ "def", "_set_session_key", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_validate_session_key", "(", "value", ")", ":", "self", ".", "__session_key", "=", "value", "else", ":", "self", ".", "__session_key", "=", "None" ]
[ 179, 4 ]
[ 186, 37 ]
python
en
['en', 'error', 'th']
False
SessionBase._get_session
(self, no_load=False)
Lazily load session from storage (unless "no_load" is True, when only an empty dict is stored) and store it in the current instance.
Lazily load session from storage (unless "no_load" is True, when only an empty dict is stored) and store it in the current instance.
def _get_session(self, no_load=False): """ Lazily load session from storage (unless "no_load" is True, when only an empty dict is stored) and store it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeErr...
[ "def", "_get_session", "(", "self", ",", "no_load", "=", "False", ")", ":", "self", ".", "accessed", "=", "True", "try", ":", "return", "self", ".", "_session_cache", "except", "AttributeError", ":", "if", "self", ".", "session_key", "is", "None", "or", ...
[ 191, 4 ]
[ 204, 34 ]
python
en
['en', 'error', 'th']
False
SessionBase.get_expiry_age
(self, **kwargs)
Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session.
Get the number of seconds until the session expires.
def get_expiry_age(self, **kwargs): """Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modifica...
[ "def", "get_expiry_age", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "modification", "=", "kwargs", "[", "'modification'", "]", "except", "KeyError", ":", "modification", "=", "timezone", ".", "now", "(", ")", "# Make the difference between \"e...
[ 211, 4 ]
[ 234, 49 ]
python
en
['en', 'en', 'en']
True
SessionBase.get_expiry_date
(self, **kwargs)
Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session.
Get session the expiry date (as a datetime object).
def get_expiry_date(self, **kwargs): """Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modifica...
[ "def", "get_expiry_date", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "modification", "=", "kwargs", "[", "'modification'", "]", "except", "KeyError", ":", "modification", "=", "timezone", ".", "now", "(", ")", "# Same comment as in get_expiry_...
[ 236, 4 ]
[ 255, 55 ]
python
en
['en', 'en', 'en']
True
SessionBase.set_expiry
(self, value)
Set a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser cl...
Set a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``.
def set_expiry(self, value): """ Set a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the s...
[ "def", "set_expiry", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "# Remove any custom expiration for this session.", "try", ":", "del", "self", "[", "'_session_expiry'", "]", "except", "KeyError", ":", "pass", "return", "if", "isinstan...
[ 257, 4 ]
[ 281, 39 ]
python
en
['en', 'error', 'th']
False
SessionBase.get_expire_at_browser_close
(self)
Return ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.
Return ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.
def get_expire_at_browser_close(self): """ Return ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ ...
[ "def", "get_expire_at_browser_close", "(", "self", ")", ":", "if", "self", ".", "get", "(", "'_session_expiry'", ")", "is", "None", ":", "return", "settings", ".", "SESSION_EXPIRE_AT_BROWSER_CLOSE", "return", "self", ".", "get", "(", "'_session_expiry'", ")", "=...
[ 283, 4 ]
[ 292, 47 ]
python
en
['en', 'error', 'th']
False
SessionBase.flush
(self)
Remove the current session data from the database and regenerate the key.
Remove the current session data from the database and regenerate the key.
def flush(self): """ Remove the current session data from the database and regenerate the key. """ self.clear() self.delete() self._session_key = None
[ "def", "flush", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "delete", "(", ")", "self", ".", "_session_key", "=", "None" ]
[ 294, 4 ]
[ 301, 32 ]
python
en
['en', 'error', 'th']
False
SessionBase.cycle_key
(self)
Create a new session key, while retaining the current session data.
Create a new session key, while retaining the current session data.
def cycle_key(self): """ Create a new session key, while retaining the current session data. """ data = self._session key = self.session_key self.create() self._session_cache = data if key: self.delete(key)
[ "def", "cycle_key", "(", "self", ")", ":", "data", "=", "self", ".", "_session", "key", "=", "self", ".", "session_key", "self", ".", "create", "(", ")", "self", ".", "_session_cache", "=", "data", "if", "key", ":", "self", ".", "delete", "(", "key",...
[ 303, 4 ]
[ 312, 28 ]
python
en
['en', 'error', 'th']
False
SessionBase.exists
(self, session_key)
Return True if the given session_key already exists.
Return True if the given session_key already exists.
def exists(self, session_key): """ Return True if the given session_key already exists. """ raise NotImplementedError('subclasses of SessionBase must provide an exists() method')
[ "def", "exists", "(", "self", ",", "session_key", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide an exists() method'", ")" ]
[ 316, 4 ]
[ 320, 94 ]
python
en
['en', 'error', 'th']
False
SessionBase.create
(self)
Create a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.
Create a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.
def create(self): """ Create a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError('subclasses of SessionBase must provide a create() metho...
[ "def", "create", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a create() method'", ")" ]
[ 322, 4 ]
[ 328, 93 ]
python
en
['en', 'error', 'th']
False
SessionBase.save
(self, must_create=False)
Save the session data. If 'must_create' is True, create a new session object (or raise CreateError). Otherwise, only update an existing object and don't create one (raise UpdateError if needed).
Save the session data. If 'must_create' is True, create a new session object (or raise CreateError). Otherwise, only update an existing object and don't create one (raise UpdateError if needed).
def save(self, must_create=False): """ Save the session data. If 'must_create' is True, create a new session object (or raise CreateError). Otherwise, only update an existing object and don't create one (raise UpdateError if needed). """ raise NotImplementedError('subclas...
[ "def", "save", "(", "self", ",", "must_create", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a save() method'", ")" ]
[ 330, 4 ]
[ 336, 91 ]
python
en
['en', 'error', 'th']
False
SessionBase.delete
(self, session_key=None)
Delete the session data under this key. If the key is None, use the current session key value.
Delete the session data under this key. If the key is None, use the current session key value.
def delete(self, session_key=None): """ Delete the session data under this key. If the key is None, use the current session key value. """ raise NotImplementedError('subclasses of SessionBase must provide a delete() method')
[ "def", "delete", "(", "self", ",", "session_key", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a delete() method'", ")" ]
[ 338, 4 ]
[ 343, 93 ]
python
en
['en', 'error', 'th']
False
SessionBase.load
(self)
Load the session data and return a dictionary.
Load the session data and return a dictionary.
def load(self): """ Load the session data and return a dictionary. """ raise NotImplementedError('subclasses of SessionBase must provide a load() method')
[ "def", "load", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a load() method'", ")" ]
[ 345, 4 ]
[ 349, 91 ]
python
en
['en', 'error', 'th']
False
SessionBase.clear_expired
(cls)
Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op.
Remove expired sessions from the session store.
def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """...
[ "def", "clear_expired", "(", "cls", ")", ":", "raise", "NotImplementedError", "(", "'This backend does not support clear_expired().'", ")" ]
[ 352, 4 ]
[ 360, 83 ]
python
en
['en', 'error', 'th']
False
make_basic_picklable_cnn
( nb_filters=64, nb_classes=10, input_shape=(None, 28, 28, 1) )
The model for the picklable models tutorial.
The model for the picklable models tutorial.
def make_basic_picklable_cnn( nb_filters=64, nb_classes=10, input_shape=(None, 28, 28, 1) ): """The model for the picklable models tutorial.""" layers = [ Conv2D(nb_filters, (8, 8), (2, 2), "SAME"), ReLU(), Conv2D(nb_filters * 2, (6, 6), (2, 2), "VALID"), ReLU(), Conv...
[ "def", "make_basic_picklable_cnn", "(", "nb_filters", "=", "64", ",", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ")", ":", "layers", "=", "[", "Conv2D", "(", "nb_filters", ",", "(", "8", ",", ...
[ 38, 0 ]
[ 54, 16 ]
python
en
['en', 'en', 'en']
True
plot_reliability_diagram
(confidence, labels, filepath)
Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where to save the diagram :return:
Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where to save the diagram :return:
def plot_reliability_diagram(confidence, labels, filepath): """ Takes in confidence values for predictions and correct labels for the data, plots a reliability diagram. :param confidence: nb_samples x nb_classes (e.g., output of softmax) :param labels: vector of nb_samples :param filepath: where...
[ "def", "plot_reliability_diagram", "(", "confidence", ",", "labels", ",", "filepath", ")", ":", "assert", "len", "(", "confidence", ".", "shape", ")", "==", "2", "assert", "len", "(", "labels", ".", "shape", ")", "==", "1", "assert", "confidence", ".", "...
[ 411, 0 ]
[ 478, 46 ]
python
en
['en', 'error', 'th']
False
DkNNModel.__init__
( self, neighbors, layers, get_activations, train_data, train_labels, nb_classes, scope=None, nb_tables=200, number_bits=17, )
Implements the DkNN algorithm. See https://arxiv.org/abs/1803.04765 for more details. :param neighbors: number of neighbors to find per layer. :param layers: a list of layer names to include in the DkNN. :param get_activations: a callable that takes a np array and a layer name and retu...
Implements the DkNN algorithm. See https://arxiv.org/abs/1803.04765 for more details.
def __init__( self, neighbors, layers, get_activations, train_data, train_labels, nb_classes, scope=None, nb_tables=200, number_bits=17, ): """ Implements the DkNN algorithm. See https://arxiv.org/abs/1803.04765 for more...
[ "def", "__init__", "(", "self", ",", "neighbors", ",", "layers", ",", "get_activations", ",", "train_data", ",", "train_labels", ",", "nb_classes", ",", "scope", "=", "None", ",", "nb_tables", "=", "200", ",", "number_bits", "=", "17", ",", ")", ":", "su...
[ 184, 4 ]
[ 226, 23 ]
python
en
['en', 'error', 'th']
False
DkNNModel.init_lsh
(self)
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data.
def init_lsh(self): """ Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. """ self.query_objects = ( {} ) # contains the object that can be queried to find nearest neighbors at each layer. # mean of training data ...
[ "def", "init_lsh", "(", "self", ")", ":", "self", ".", "query_objects", "=", "(", "{", "}", ")", "# contains the object that can be queried to find nearest neighbors at each layer.", "# mean of training data representation per layer (that needs to be substracted before", "# NearestNe...
[ 228, 4 ]
[ 258, 76 ]
python
en
['en', 'error', 'th']
False
DkNNModel.find_train_knns
(self, data_activations)
Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data.
Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data.
def find_train_knns(self, data_activations): """ Given a data_activation dictionary that contains a np array with activations for each layer, find the knns in the training data. """ knns_ind = {} knns_labels = {} for layer in self.layers: # Pre-proces...
[ "def", "find_train_knns", "(", "self", ",", "data_activations", ")", ":", "knns_ind", "=", "{", "}", "knns_labels", "=", "{", "}", "for", "layer", "in", "self", ".", "layers", ":", "# Pre-process representations of data to normalize and remove training data mean.", "d...
[ 260, 4 ]
[ 301, 36 ]
python
en
['en', 'error', 'th']
False
DkNNModel.nonconformity
(self, knns_labels)
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label.
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label.
def nonconformity(self, knns_labels): """ Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label. """ nb_data = knns_labels[sel...
[ "def", "nonconformity", "(", "self", ",", "knns_labels", ")", ":", "nb_data", "=", "knns_labels", "[", "self", ".", "layers", "[", "0", "]", "]", ".", "shape", "[", "0", "]", "knns_not_in_class", "=", "np", ".", "zeros", "(", "(", "nb_data", ",", "se...
[ 303, 4 ]
[ 326, 32 ]
python
en
['en', 'error', 'th']
False
DkNNModel.preds_conf_cred
(self, knns_not_in_class)
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility.
Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility.
def preds_conf_cred(self, knns_not_in_class): """ Given an array of nb_data x nb_classes dimensions, use conformal prediction to compute the DkNN's prediction, confidence and credibility. """ nb_data = knns_not_in_class.shape[0] preds_knn = np.zeros(nb_data, dtype=np.int3...
[ "def", "preds_conf_cred", "(", "self", ",", "knns_not_in_class", ")", ":", "nb_data", "=", "knns_not_in_class", ".", "shape", "[", "0", "]", "preds_knn", "=", "np", ".", "zeros", "(", "nb_data", ",", "dtype", "=", "np", ".", "int32", ")", "confs", "=", ...
[ 328, 4 ]
[ 354, 38 ]
python
en
['en', 'error', 'th']
False
DkNNModel.fprop_np
(self, data_np)
Performs a forward pass through the DkNN on an numpy array of data.
Performs a forward pass through the DkNN on an numpy array of data.
def fprop_np(self, data_np): """ Performs a forward pass through the DkNN on an numpy array of data. """ if not self.calibrated: raise ValueError( "DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring." ) ...
[ "def", "fprop_np", "(", "self", ",", "data_np", ")", ":", "if", "not", "self", ".", "calibrated", ":", "raise", "ValueError", "(", "\"DkNN needs to be calibrated by calling DkNNModel.calibrate method once before inferring.\"", ")", "data_activations", "=", "self", ".", ...
[ 356, 4 ]
[ 368, 20 ]
python
en
['en', 'error', 'th']
False
DkNNModel.fprop
(self, x)
Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method.
Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method.
def fprop(self, x): """ Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ logits = tf.py_func(self.fprop_np, [x], tf.float32) return {self.O_LOGITS: logits}
[ "def", "fprop", "(", "self", ",", "x", ")", ":", "logits", "=", "tf", ".", "py_func", "(", "self", ".", "fprop_np", ",", "[", "x", "]", ",", "tf", ".", "float32", ")", "return", "{", "self", ".", "O_LOGITS", ":", "logits", "}" ]
[ 370, 4 ]
[ 376, 38 ]
python
en
['en', 'error', 'th']
False
DkNNModel.calibrate
(self, cali_data, cali_labels)
Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels.
Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels.
def calibrate(self, cali_data, cali_labels): """ Runs the DkNN on holdout data to calibrate the credibility metric. :param cali_data: np array of calibration data. :param cali_labels: np vector of calibration labels. """ self.nb_cali = cali_labels.shape[0] self.ca...
[ "def", "calibrate", "(", "self", ",", "cali_data", ",", "cali_labels", ")", ":", "self", ".", "nb_cali", "=", "cali_labels", ".", "shape", "[", "0", "]", "self", ".", "cali_activations", "=", "self", ".", "get_activations", "(", "cali_data", ")", "self", ...
[ 378, 4 ]
[ 408, 43 ]
python
en
['en', 'error', 'th']
False
srs_double
(f)
Create a function prototype for the OSR routines that take the OSRSpatialReference object and return a double value.
Create a function prototype for the OSR routines that take the OSRSpatialReference object and return a double value.
def srs_double(f): """ Create a function prototype for the OSR routines that take the OSRSpatialReference object and return a double value. """ return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True)
[ "def", "srs_double", "(", "f", ")", ":", "return", "double_output", "(", "f", ",", "[", "c_void_p", ",", "POINTER", "(", "c_int", ")", "]", ",", "errcheck", "=", "True", ")" ]
[ 10, 0 ]
[ 15, 70 ]
python
en
['en', 'error', 'th']
False
units_func
(f)
Create a ctypes function prototype for OSR units functions, e.g., OSRGetAngularUnits, OSRGetLinearUnits.
Create a ctypes function prototype for OSR units functions, e.g., OSRGetAngularUnits, OSRGetLinearUnits.
def units_func(f): """ Create a ctypes function prototype for OSR units functions, e.g., OSRGetAngularUnits, OSRGetLinearUnits. """ return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True)
[ "def", "units_func", "(", "f", ")", ":", "return", "double_output", "(", "f", ",", "[", "c_void_p", ",", "POINTER", "(", "c_char_p", ")", "]", ",", "strarg", "=", "True", ")" ]
[ 18, 0 ]
[ 23, 71 ]
python
en
['en', 'error', 'th']
False
ContainerIO.__init__
(self, file, offset, length)
Create file object. :param file: Existing file. :param offset: Start of region, in bytes. :param length: Size of region, in bytes.
Create file object.
def __init__(self, file, offset, length): """ Create file object. :param file: Existing file. :param offset: Start of region, in bytes. :param length: Size of region, in bytes. """ self.fh = file self.pos = 0 self.offset = offset self.leng...
[ "def", "__init__", "(", "self", ",", "file", ",", "offset", ",", "length", ")", ":", "self", ".", "fh", "=", "file", "self", ".", "pos", "=", "0", "self", ".", "offset", "=", "offset", "self", ".", "length", "=", "length", "self", ".", "fh", ".",...
[ 26, 4 ]
[ 38, 28 ]
python
en
['en', 'error', 'th']
False
ContainerIO.seek
(self, offset, mode=io.SEEK_SET)
Move file pointer. :param offset: Offset in bytes. :param mode: Starting position. Use 0 for beginning of region, 1 for current offset, and 2 for end of region. You cannot move the pointer outside the defined region.
Move file pointer.
def seek(self, offset, mode=io.SEEK_SET): """ Move file pointer. :param offset: Offset in bytes. :param mode: Starting position. Use 0 for beginning of region, 1 for current offset, and 2 for end of region. You cannot move the pointer outside the defined region. ...
[ "def", "seek", "(", "self", ",", "offset", ",", "mode", "=", "io", ".", "SEEK_SET", ")", ":", "if", "mode", "==", "1", ":", "self", ".", "pos", "=", "self", ".", "pos", "+", "offset", "elif", "mode", "==", "2", ":", "self", ".", "pos", "=", "...
[ 46, 4 ]
[ 63, 44 ]
python
en
['en', 'error', 'th']
False
ContainerIO.tell
(self)
Get current file pointer. :returns: Offset from start of region, in bytes.
Get current file pointer.
def tell(self): """ Get current file pointer. :returns: Offset from start of region, in bytes. """ return self.pos
[ "def", "tell", "(", "self", ")", ":", "return", "self", ".", "pos" ]
[ 65, 4 ]
[ 71, 23 ]
python
en
['en', 'error', 'th']
False
ContainerIO.read
(self, n=0)
Read data. :param n: Number of bytes to read. If omitted or zero, read until end of region. :returns: An 8-bit string.
Read data.
def read(self, n=0): """ Read data. :param n: Number of bytes to read. If omitted or zero, read until end of region. :returns: An 8-bit string. """ if n: n = min(n, self.length - self.pos) else: n = self.length - self.pos ...
[ "def", "read", "(", "self", ",", "n", "=", "0", ")", ":", "if", "n", ":", "n", "=", "min", "(", "n", ",", "self", ".", "length", "-", "self", ".", "pos", ")", "else", ":", "n", "=", "self", ".", "length", "-", "self", ".", "pos", "if", "n...
[ 73, 4 ]
[ 88, 30 ]
python
en
['en', 'error', 'th']
False
ContainerIO.readline
(self)
Read a line of text. :returns: An 8-bit string.
Read a line of text.
def readline(self): """ Read a line of text. :returns: An 8-bit string. """ s = b"" if "b" in self.fh.mode else "" newline_character = b"\n" if "b" in self.fh.mode else "\n" while True: c = self.read(1) if not c: break ...
[ "def", "readline", "(", "self", ")", ":", "s", "=", "b\"\"", "if", "\"b\"", "in", "self", ".", "fh", ".", "mode", "else", "\"\"", "newline_character", "=", "b\"\\n\"", "if", "\"b\"", "in", "self", ".", "fh", ".", "mode", "else", "\"\\n\"", "while", "...
[ 90, 4 ]
[ 105, 16 ]
python
en
['en', 'error', 'th']
False
ContainerIO.readlines
(self)
Read multiple lines of text. :returns: A list of 8-bit strings.
Read multiple lines of text.
def readlines(self): """ Read multiple lines of text. :returns: A list of 8-bit strings. """ lines = [] while True: s = self.readline() if not s: break lines.append(s) return lines
[ "def", "readlines", "(", "self", ")", ":", "lines", "=", "[", "]", "while", "True", ":", "s", "=", "self", ".", "readline", "(", ")", "if", "not", "s", ":", "break", "lines", ".", "append", "(", "s", ")", "return", "lines" ]
[ 107, 4 ]
[ 119, 20 ]
python
en
['en', 'error', 'th']
False
_to_str
(s)
Convert a filename to a string (on Python 2, explicitly a byte string, not Unicode) as distutils checks for the exact type str.
Convert a filename to a string (on Python 2, explicitly a byte string, not Unicode) as distutils checks for the exact type str.
def _to_str(s): """ Convert a filename to a string (on Python 2, explicitly a byte string, not Unicode) as distutils checks for the exact type str. """ if sys.version_info[0] == 2 and not isinstance(s, str): # Assume it's Unicode, as that's what the PEP says # should be provided....
[ "def", "_to_str", "(", "s", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", "and", "not", "isinstance", "(", "s", ",", "str", ")", ":", "# Assume it's Unicode, as that's what the PEP says", "# should be provided.", "return", "s", ".", "...
[ 77, 0 ]
[ 87, 12 ]
python
en
['en', 'error', 'th']
False
Distribution.patch
(cls)
Replace distutils.dist.Distribution with this class for the duration of this context.
Replace distutils.dist.Distribution with this class for the duration of this context.
def patch(cls): """ Replace distutils.dist.Distribution with this class for the duration of this context. """ orig = distutils.core.Distribution distutils.core.Distribution = cls try: yield finally: distutils.core.Distributi...
[ "def", "patch", "(", "cls", ")", ":", "orig", "=", "distutils", ".", "core", ".", "Distribution", "distutils", ".", "core", ".", "Distribution", "=", "cls", "try", ":", "yield", "finally", ":", "distutils", ".", "core", ".", "Distribution", "=", "orig" ]
[ 63, 4 ]
[ 74, 46 ]
python
en
['en', 'error', 'th']
False
ld_mnist
()
Load training and test data.
Load training and test data.
def ld_mnist(): """Load training and test data.""" def convert_types(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label dataset, info = tfds.load( "mnist", data_dir="gs://tfds-data/datasets", with_info=True, as_supervised=True ) mnist...
[ "def", "ld_mnist", "(", ")", ":", "def", "convert_types", "(", "image", ",", "label", ")", ":", "image", "=", "tf", ".", "cast", "(", "image", ",", "tf", ".", "float32", ")", "image", "/=", "255", "return", "image", ",", "label", "dataset", ",", "i...
[ 35, 0 ]
[ 49, 55 ]
python
en
['en', 'en', 'en']
True
setup
(set_prefix=True)
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True.
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True.
def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf i...
[ "def", "setup", "(", "set_prefix", "=", "True", ")", ":", "from", "django", ".", "apps", "import", "apps", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "urls", "import", "set_script_prefix", "from", "django", ".", "utils", "....
[ 7, 0 ]
[ 23, 42 ]
python
en
['en', 'error', 'th']
False
duration_string
(duration)
Version of str(timedelta) which is not English specific.
Version of str(timedelta) which is not English specific.
def duration_string(duration): """Version of str(timedelta) which is not English specific.""" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) if days: string = '{} '.format(days) + string if mic...
[ "def", "duration_string", "(", "duration", ")", ":", "days", ",", "hours", ",", "minutes", ",", "seconds", ",", "microseconds", "=", "_get_duration_components", "(", "duration", ")", "string", "=", "'{:02d}:{:02d}:{:02d}'", ".", "format", "(", "hours", ",", "m...
[ 17, 0 ]
[ 27, 17 ]
python
en
['en', 'en', 'en']
True
madry_et_al
( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_minmax=0.3, sanity_checks=True, )
The attack from Madry et al 2017
The attack from Madry et al 2017
def madry_et_al( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_minmax=0.3, sanity_checks=True, ): """ The attack from Madry et al 2017 """ return projected_gradient_descent( model_fn, ...
[ "def", "madry_et_al", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "norm", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "rand_minmax", "=", "0.3...
[ 7, 0 ]
[ 38, 5 ]
python
en
['en', 'error', 'th']
False
normalize_name
(name)
Converts camel-case style names into underscore separated words. Example:: >>> normalize_name('oneTwoThree') 'one_two_three' >>> normalize_name('FourFiveSix') 'four_five_six'
Converts camel-case style names into underscore separated words. Example::
def normalize_name(name): """ Converts camel-case style names into underscore separated words. Example:: >>> normalize_name('oneTwoThree') 'one_two_three' >>> normalize_name('FourFiveSix') 'four_five_six' """ new = re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1'...
[ "def", "normalize_name", "(", "name", ")", ":", "new", "=", "re", ".", "sub", "(", "'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'", ",", "'_\\\\1'", ",", "name", ")", "return", "new", ".", "lower", "(", ")", ".", "strip", "(", "'_'", ")" ]
[ 17, 0 ]
[ 28, 33 ]
python
en
['en', 'error', 'th']
False
StepsHelper.all
(self)
Returns the names of all steps/forms.
Returns the names of all steps/forms.
def all(self): "Returns the names of all steps/forms." return list(self._wizard.get_form_list())
[ "def", "all", "(", "self", ")", ":", "return", "list", "(", "self", ".", "_wizard", ".", "get_form_list", "(", ")", ")" ]
[ 46, 4 ]
[ 48, 49 ]
python
en
['en', 'en', 'en']
True
StepsHelper.count
(self)
Returns the total number of steps/forms in this the wizard.
Returns the total number of steps/forms in this the wizard.
def count(self): "Returns the total number of steps/forms in this the wizard." return len(self.all)
[ "def", "count", "(", "self", ")", ":", "return", "len", "(", "self", ".", "all", ")" ]
[ 51, 4 ]
[ 53, 28 ]
python
en
['en', 'en', 'en']
True
StepsHelper.current
(self)
Returns the current step. If no current step is stored in the storage backend, the first step will be returned.
Returns the current step. If no current step is stored in the storage backend, the first step will be returned.
def current(self): """ Returns the current step. If no current step is stored in the storage backend, the first step will be returned. """ return self._wizard.storage.current_step or self.first
[ "def", "current", "(", "self", ")", ":", "return", "self", ".", "_wizard", ".", "storage", ".", "current_step", "or", "self", ".", "first" ]
[ 56, 4 ]
[ 61, 62 ]
python
en
['en', 'error', 'th']
False
StepsHelper.first
(self)
Returns the name of the first step.
Returns the name of the first step.
def first(self): "Returns the name of the first step." return self.all[0]
[ "def", "first", "(", "self", ")", ":", "return", "self", ".", "all", "[", "0", "]" ]
[ 64, 4 ]
[ 66, 26 ]
python
en
['en', 'en', 'en']
True
StepsHelper.last
(self)
Returns the name of the last step.
Returns the name of the last step.
def last(self): "Returns the name of the last step." return self.all[-1]
[ "def", "last", "(", "self", ")", ":", "return", "self", ".", "all", "[", "-", "1", "]" ]
[ 69, 4 ]
[ 71, 27 ]
python
en
['en', 'en', 'en']
True
StepsHelper.next
(self)
Returns the next step.
Returns the next step.
def next(self): "Returns the next step." return self._wizard.get_next_step()
[ "def", "next", "(", "self", ")", ":", "return", "self", ".", "_wizard", ".", "get_next_step", "(", ")" ]
[ 74, 4 ]
[ 76, 43 ]
python
en
['en', 'pt', 'en']
True
StepsHelper.prev
(self)
Returns the previous step.
Returns the previous step.
def prev(self): "Returns the previous step." return self._wizard.get_prev_step()
[ "def", "prev", "(", "self", ")", ":", "return", "self", ".", "_wizard", ".", "get_prev_step", "(", ")" ]
[ 79, 4 ]
[ 81, 43 ]
python
en
['en', 'en', 'en']
True
StepsHelper.index
(self)
Returns the index for the current step.
Returns the index for the current step.
def index(self): "Returns the index for the current step." return self._wizard.get_step_index()
[ "def", "index", "(", "self", ")", ":", "return", "self", ".", "_wizard", ".", "get_step_index", "(", ")" ]
[ 84, 4 ]
[ 86, 44 ]
python
en
['en', 'en', 'en']
True
WizardView.as_view
(cls, *args, **kwargs)
This method is used within urls.py to create unique wizardview instances for every request. We need to override this method because we add some kwargs which are needed to make the wizardview usable.
This method is used within urls.py to create unique wizardview instances for every request. We need to override this method because we add some kwargs which are needed to make the wizardview usable.
def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique wizardview instances for every request. We need to override this method because we add some kwargs which are needed to make the wizardview usable. """ initkwargs = cls.get_initkwarg...
[ "def", "as_view", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "initkwargs", "=", "cls", ".", "get_initkwargs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "super", "(", "WizardView", ",", "cls", ")", ".", "as_view...
[ 114, 4 ]
[ 121, 59 ]
python
en
['en', 'error', 'th']
False
WizardView.get_initkwargs
(cls, form_list=None, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs)
Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tuples of (`step_name`, `form_class`). If you pass a list of forms, the wizardview will convert the class list to (`...
Creates a dict with all needed parameters for the form wizard instances.
def get_initkwargs(cls, form_list=None, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classe...
[ "def", "get_initkwargs", "(", "cls", ",", "form_list", "=", "None", ",", "initial_dict", "=", "None", ",", "instance_dict", "=", "None", ",", "condition_dict", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "...
[ 124, 4 ]
[ 192, 21 ]
python
en
['en', 'error', 'th']
False