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
DateFormat.Y
(self)
Year, 4 digits; e.g. '1999
Year, 4 digits; e.g. '1999
def Y(self): "Year, 4 digits; e.g. '1999'" return self.data.year
[ "def", "Y", "(", "self", ")", ":", "return", "self", ".", "data", ".", "year" ]
[ 345, 4 ]
[ 347, 29 ]
python
da
['da', 'ny', 'en']
False
DateFormat.z
(self)
Day of the year, i.e. 1 to 366.
Day of the year, i.e. 1 to 366.
def z(self): """Day of the year, i.e. 1 to 366.""" doy = self.year_days[self.data.month] + self.data.day if self.L() and self.data.month > 2: doy += 1 return doy
[ "def", "z", "(", "self", ")", ":", "doy", "=", "self", ".", "year_days", "[", "self", ".", "data", ".", "month", "]", "+", "self", ".", "data", ".", "day", "if", "self", ".", "L", "(", ")", "and", "self", ".", "data", ".", "month", ">", "2", ...
[ 349, 4 ]
[ 354, 18 ]
python
en
['en', 'en', 'en']
True
api_canarytoken_webhook
( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), )
Construct a response to a webhook event from a Thinkst canarytoken from canarytokens.org. Canarytokens from Thinkst's paid product have a different schema and should use the "thinkst" integration. See linked documentation below for a schema: https://help.canary.tools/hc/en-gb/articles/360002426577...
Construct a response to a webhook event from a Thinkst canarytoken from canarytokens.org. Canarytokens from Thinkst's paid product have a different schema and should use the "thinkst" integration. See linked documentation below for a schema:
def api_canarytoken_webhook( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), ) -> HttpResponse: """ Construct a response to a webhook event from a Thinkst canarytoken from ...
[ "def", "api_canarytoken_webhook", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "message", ":", "Dict", "[", "str", ",", "Any", "]", "=", "REQ", "(", "argument_type", "=", "\"body\"", ")", ",", "user_specified_topic", ":", ...
[ 14, 0 ]
[ 39, 25 ]
python
en
['en', 'error', 'th']
False
create_keras_addition_model
(node_name_mapping=None)
A simple addition model
A simple addition model
def create_keras_addition_model(node_name_mapping=None): """ A simple addition model """ if node_name_mapping is None: class id_dict(dict): def __missing__(self, key): return key node_name_mapping = id_dict() x = Input(batch_shape=(None,), name=node_nam...
[ "def", "create_keras_addition_model", "(", "node_name_mapping", "=", "None", ")", ":", "if", "node_name_mapping", "is", "None", ":", "class", "id_dict", "(", "dict", ")", ":", "def", "__missing__", "(", "self", ",", "key", ")", ":", "return", "key", "node_na...
[ 29, 0 ]
[ 45, 16 ]
python
en
['en', 'error', 'th']
False
newer_pairwise_group
(sources_groups, targets)
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'.
def newer_pairwise_group(sources_groups, targets): """Walk both arguments in parallel, testing if each source group is newer than its corresponding target. Returns a pair of lists (sources_groups, targets) where sources is newer than target, according to the semantics of 'newer_group()'. """ if ...
[ "def", "newer_pairwise_group", "(", "sources_groups", ",", "targets", ")", ":", "if", "len", "(", "sources_groups", ")", "!=", "len", "(", "targets", ")", ":", "raise", "ValueError", "(", "\"'sources_group' and 'targets' must be the same length\"", ")", "# build a pai...
[ 6, 0 ]
[ 24, 31 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper._pyb_path
(self, path)
returns path relative to pyboard. Args: path (str): path to resolve
returns path relative to pyboard.
def _pyb_path(self, path): """returns path relative to pyboard. Args: path (str): path to resolve """ _path = path if path[0] == "/": _path = path[1:] pyb_path = f"{self.pyb_root}{_path}" return pyb_path
[ "def", "_pyb_path", "(", "self", ",", "path", ")", ":", "_path", "=", "path", "if", "path", "[", "0", "]", "==", "\"/\"", ":", "_path", "=", "path", "[", "1", ":", "]", "pyb_path", "=", "f\"{self.pyb_root}{_path}\"", "return", "pyb_path" ]
[ 52, 4 ]
[ 63, 23 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper.repl
(self)
Pyboard raw repl context manager.
Pyboard raw repl context manager.
def repl(self): """Pyboard raw repl context manager.""" self.pyboard.enter_raw_repl() try: yield self.pyboard finally: self.pyboard.exit_raw_repl()
[ "def", "repl", "(", "self", ")", ":", "self", ".", "pyboard", ".", "enter_raw_repl", "(", ")", "try", ":", "yield", "self", ".", "pyboard", "finally", ":", "self", ".", "pyboard", ".", "exit_raw_repl", "(", ")" ]
[ 66, 4 ]
[ 72, 40 ]
python
en
['pl', 'en', 'en']
True
PyboardWrapper.connect
(self)
connect to pyboard.
connect to pyboard.
def connect(self): """connect to pyboard.""" self.log.debug(f"connecting to pydevice @ {self.port}") try: self.rsh.connect(self.port) except SystemExit as e: self.log.debug(f"failed to connect: {str(e)}") raise e else: self.log.debu...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "f\"connecting to pydevice @ {self.port}\"", ")", "try", ":", "self", ".", "rsh", ".", "connect", "(", "self", ".", "port", ")", "except", "SystemExit", "as", "e", ":", "self...
[ 74, 4 ]
[ 84, 33 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper.pyboard
(self)
rshell pyboard instance.
rshell pyboard instance.
def pyboard(self): """rshell pyboard instance.""" if self.connected: dev = rsh.find_serial_device_by_port(self.port) return getattr(dev, "pyb", None)
[ "def", "pyboard", "(", "self", ")", ":", "if", "self", ".", "connected", ":", "dev", "=", "rsh", ".", "find_serial_device_by_port", "(", "self", ".", "port", ")", "return", "getattr", "(", "dev", ",", "\"pyb\"", ",", "None", ")" ]
[ 87, 4 ]
[ 91, 44 ]
python
en
['en', 'en', 'hi']
True
PyboardWrapper.pyb_root
(self)
pyboard root dirname.
pyboard root dirname.
def pyb_root(self): """pyboard root dirname.""" if self.connected: dev = rsh.find_serial_device_by_port(self.port) return getattr(dev, "name_path", "/pyboard/")
[ "def", "pyb_root", "(", "self", ")", ":", "if", "self", ".", "connected", ":", "dev", "=", "rsh", ".", "find_serial_device_by_port", "(", "self", ".", "port", ")", "return", "getattr", "(", "dev", ",", "\"name_path\"", ",", "\"/pyboard/\"", ")" ]
[ 94, 4 ]
[ 98, 57 ]
python
en
['en', 'nl', 'en']
True
PyboardWrapper.copy_file
(self, source, dest=None)
Copies file to pyboard. Args: source (str): path to file dest (str, optional): dest on pyboard. Defaults to None. If None, file is copied to pyboard root. Returns: str: path to dest on pyboard
Copies file to pyboard.
def copy_file(self, source, dest=None): """Copies file to pyboard. Args: source (str): path to file dest (str, optional): dest on pyboard. Defaults to None. If None, file is copied to pyboard root. Returns: str: path to dest on pyboard ...
[ "def", "copy_file", "(", "self", ",", "source", ",", "dest", "=", "None", ")", ":", "src_path", "=", "Path", "(", "source", ")", ".", "resolve", "(", ")", "_dest", "=", "dest", "or", "src_path", ".", "name", "dest", "=", "self", ".", "_pyb_path", "...
[ 100, 4 ]
[ 116, 19 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper._output
(self, data)
Yields everything up to a newline. Args: data (str): Anything to yield before newline
Yields everything up to a newline.
def _output(self, data): """Yields everything up to a newline. Args: data (str): Anything to yield before newline """ if data == "\n": line = "".join(self._outline) self._outline = [] yield line self._outline.append(data)
[ "def", "_output", "(", "self", ",", "data", ")", ":", "if", "data", "==", "\"\\n\"", ":", "line", "=", "\"\"", ".", "join", "(", "self", ".", "_outline", ")", "self", ".", "_outline", "=", "[", "]", "yield", "line", "self", ".", "_outline", ".", ...
[ 118, 4 ]
[ 129, 34 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper._consumer
(self, char)
Pyboard data consumer. When a full line of output is detected, it is formatted then logged to stdout and log file. Args: char (byte): Byte from PyBoard Returns: str: Converted char
Pyboard data consumer.
def _consumer(self, char): """Pyboard data consumer. When a full line of output is detected, it is formatted then logged to stdout and log file. Args: char (byte): Byte from PyBoard Returns: str: Converted char """ char = char.d...
[ "def", "_consumer", "(", "self", ",", "char", ")", ":", "char", "=", "char", ".", "decode", "(", "\"utf-8\"", ")", "line", "=", "next", "(", "self", ".", "_output", "(", "char", ")", ",", "None", ")", "if", "line", ":", "if", "self", ".", "format...
[ 131, 4 ]
[ 151, 19 ]
python
en
['en', 'ha', 'en']
True
PyboardWrapper._exec
(self, command)
Execute bytes on pyboard.
Execute bytes on pyboard.
def _exec(self, command): """Execute bytes on pyboard.""" ret, ret_err = self.pyboard.exec_raw(command, data_consumer=self._consumer) if ret_err: raise PyboardError("exception", ret, ret_err) return ret
[ "def", "_exec", "(", "self", ",", "command", ")", ":", "ret", ",", "ret_err", "=", "self", ".", "pyboard", ".", "exec_raw", "(", "command", ",", "data_consumer", "=", "self", ".", "_consumer", ")", "if", "ret_err", ":", "raise", "PyboardError", "(", "\...
[ 153, 4 ]
[ 158, 18 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper.run
(self, file, format_output=None)
Execute a local script on the pyboard. Args: file (str): path to file or string to run format_output (callable, optional): Callback to format output. Defaults to None. If none, uses print.
Execute a local script on the pyboard.
def run(self, file, format_output=None): """Execute a local script on the pyboard. Args: file (str): path to file or string to run format_output (callable, optional): Callback to format output. Defaults to None. If none, uses print. """ self.form...
[ "def", "run", "(", "self", ",", "file", ",", "format_output", "=", "None", ")", ":", "self", ".", "format_output", "=", "format_output", "try", ":", "with", "file", ".", "open", "(", "\"rb\"", ")", "as", "f", ":", "pyfile", "=", "f", ".", "read", "...
[ 160, 4 ]
[ 182, 22 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper.list_dir
(self, path)
List directory on pyboard. Args: path (str): path to directory
List directory on pyboard.
def list_dir(self, path): """List directory on pyboard. Args: path (str): path to directory """ dir_path = self._pyb_path(path) tree = self.rsh.auto(rsh.listdir, dir_path) return tree
[ "def", "list_dir", "(", "self", ",", "path", ")", ":", "dir_path", "=", "self", ".", "_pyb_path", "(", "path", ")", "tree", "=", "self", ".", "rsh", ".", "auto", "(", "rsh", ".", "listdir", ",", "dir_path", ")", "return", "tree" ]
[ 184, 4 ]
[ 193, 19 ]
python
en
['en', 'en', 'en']
True
PyboardWrapper.copy_dir
(self, path, dest, rsync={})
Copy directory from pyboard to machine. Args: path (str): path to directory dest (str): destination to copy to rsync (dict, optional): additonal args to pass to rsync call. Defaults to {}
Copy directory from pyboard to machine.
def copy_dir(self, path, dest, rsync={}): """Copy directory from pyboard to machine. Args: path (str): path to directory dest (str): destination to copy to rsync (dict, optional): additonal args to pass to rsync call. Defaults to {} """ ...
[ "def", "copy_dir", "(", "self", ",", "path", ",", "dest", ",", "rsync", "=", "{", "}", ")", ":", "dir_path", "=", "self", ".", "_pyb_path", "(", "path", ")", "dest_path", "=", "Path", "(", "str", "(", "dest", ")", ")", "rsync_args", "=", "{", "\"...
[ 195, 4 ]
[ 216, 24 ]
python
en
['en', 'en', 'en']
True
fullurl
(parser, token)
Return an absolute URL (including the scheme and domain) matching the given view with its parameters. This is meant to be identical to the built-in tag `url`, except that it always returns an absolute URL with the scheme and authority parts. For example, take this `url` tag: {% url "articles:...
Return an absolute URL (including the scheme and domain) matching the given view with its parameters.
def fullurl(parser, token): """Return an absolute URL (including the scheme and domain) matching the given view with its parameters. This is meant to be identical to the built-in tag `url`, except that it always returns an absolute URL with the scheme and authority parts. For example, take this `u...
[ "def", "fullurl", "(", "parser", ",", "token", ")", ":", "return", "FullURLNode", "(", "defaulttags", ".", "url", "(", "parser", ",", "token", ")", ")" ]
[ 8, 0 ]
[ 36, 54 ]
python
en
['en', 'en', 'en']
True
buildfullurl
(context, url)
Converts relative URL to absolute. For example: {% buildfullurl article.get_absolute_url %} or: {% buildfullurl "/custom-url/" %}
Converts relative URL to absolute.
def buildfullurl(context, url): """Converts relative URL to absolute. For example: {% buildfullurl article.get_absolute_url %} or: {% buildfullurl "/custom-url/" %} """ return context.request.build_absolute_uri(url)
[ "def", "buildfullurl", "(", "context", ",", "url", ")", ":", "return", "context", ".", "request", ".", "build_absolute_uri", "(", "url", ")" ]
[ 45, 0 ]
[ 57, 50 ]
python
en
['en', 'en', 'en']
True
TestEncodingUtils.test_force_text_exception
(self)
Check that broken __unicode__/__str__ actually raises an error.
Check that broken __unicode__/__str__ actually raises an error.
def test_force_text_exception(self): """ Check that broken __unicode__/__str__ actually raises an error. """ class MyString(object): def __str__(self): return b'\xc3\xb6\xc3\xa4\xc3\xbc' __unicode__ = __str__ # str(s) raises a TypeError o...
[ "def", "test_force_text_exception", "(", "self", ")", ":", "class", "MyString", "(", "object", ")", ":", "def", "__str__", "(", "self", ")", ":", "return", "b'\\xc3\\xb6\\xc3\\xa4\\xc3\\xbc'", "__unicode__", "=", "__str__", "# str(s) raises a TypeError on python 3 if th...
[ 13, 4 ]
[ 26, 60 ]
python
en
['en', 'error', 'th']
False
TestEncodingUtils.test_force_bytes_exception
(self)
Test that force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args.
Test that force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args.
def test_force_bytes_exception(self): """ Test that force_bytes knows how to convert to bytes an exception containing non-ASCII characters in its args. """ error_msg = "This is an exception, voilà" exc = ValueError(error_msg) result = force_bytes(exc) self...
[ "def", "test_force_bytes_exception", "(", "self", ")", ":", "error_msg", "=", "\"This is an exception, voilà\"", "exc", "=", "ValueError", "(", "error_msg", ")", "result", "=", "force_bytes", "(", "exc", ")", "self", ".", "assertEqual", "(", "result", ",", "erro...
[ 28, 4 ]
[ 36, 59 ]
python
en
['en', 'error', 'th']
False
TypesPrintTest.check_signature
( self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any )
Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. func will be decorated with print_types within this function.
Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. func will be decorated with print_types within this function.
def check_signature( self, signature: str, retval: T, func: Callable[..., T], *args: Any, **kwargs: Any ) -> None: """ Checks if print_types outputs `signature` when func is called with *args and **kwargs. Do not decorate func with print_types before passing into this function. ...
[ "def", "check_signature", "(", "self", ",", "signature", ":", "str", ",", "retval", ":", "T", ",", "func", ":", "Callable", "[", "...", ",", "T", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "t...
[ 27, 4 ]
[ 41, 40 ]
python
en
['en', 'error', 'th']
False
check_err
(code)
Checks the given OGRERR, and raises an exception where appropriate.
Checks the given OGRERR, and raises an exception where appropriate.
def check_err(code): "Checks the given OGRERR, and raises an exception where appropriate." if code == OGRERR_NONE: return elif code in OGRERR_DICT: e, msg = OGRERR_DICT[code] raise e(msg) else: raise OGRException('Unknown error code: "%s"' % code)
[ "def", "check_err", "(", "code", ")", ":", "if", "code", "==", "OGRERR_NONE", ":", "return", "elif", "code", "in", "OGRERR_DICT", ":", "e", ",", "msg", "=", "OGRERR_DICT", "[", "code", "]", "raise", "e", "(", "msg", ")", "else", ":", "raise", "OGRExc...
[ 45, 0 ]
[ 54, 61 ]
python
en
['en', 'en', 'en']
True
logout_then_login
(request, login_url=None)
Log out the user if they are logged in. Then redirect to the login page.
Log out the user if they are logged in. Then redirect to the login page.
def logout_then_login(request, login_url=None): """ Log out the user if they are logged in. Then redirect to the login page. """ login_url = resolve_url(login_url or settings.LOGIN_URL) return LogoutView.as_view(next_page=login_url)(request)
[ "def", "logout_then_login", "(", "request", ",", "login_url", "=", "None", ")", ":", "login_url", "=", "resolve_url", "(", "login_url", "or", "settings", ".", "LOGIN_URL", ")", "return", "LogoutView", ".", "as_view", "(", "next_page", "=", "login_url", ")", ...
[ 165, 0 ]
[ 170, 59 ]
python
en
['en', 'error', 'th']
False
redirect_to_login
(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME)
Redirect the user to the login page, passing the given 'next' page.
Redirect the user to the login page, passing the given 'next' page.
def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Redirect the user to the login page, passing the given 'next' page. """ resolved_url = resolve_url(login_url or settings.LOGIN_URL) login_url_parts = list(urlparse(resolved_url)) if redirect_field_name: ...
[ "def", "redirect_to_login", "(", "next", ",", "login_url", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ")", ":", "resolved_url", "=", "resolve_url", "(", "login_url", "or", "settings", ".", "LOGIN_URL", ")", "login_url_parts", "=", "list",...
[ 173, 0 ]
[ 185, 60 ]
python
en
['en', 'error', 'th']
False
LoginView.get_redirect_url
(self)
Return the user-originating redirect URL if it's safe.
Return the user-originating redirect URL if it's safe.
def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = url_has_allowed_host_and_scheme( ...
[ "def", "get_redirect_url", "(", "self", ")", ":", "redirect_to", "=", "self", ".", "request", ".", "POST", ".", "get", "(", "self", ".", "redirect_field_name", ",", "self", ".", "request", ".", "GET", ".", "get", "(", "self", ".", "redirect_field_name", ...
[ 68, 4 ]
[ 79, 49 ]
python
en
['en', 'en', 'en']
True
LoginView.form_valid
(self, form)
Security check complete. Log the user in.
Security check complete. Log the user in.
def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url())
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "auth_login", "(", "self", ".", "request", ",", "form", ".", "get_user", "(", ")", ")", "return", "HttpResponseRedirect", "(", "self", ".", "get_success_url", "(", ")", ")" ]
[ 89, 4 ]
[ 92, 59 ]
python
en
['en', 'en', 'en']
True
LogoutView.post
(self, request, *args, **kwargs)
Logout may be done via POST.
Logout may be done via POST.
def post(self, request, *args, **kwargs): """Logout may be done via POST.""" return self.get(request, *args, **kwargs)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 124, 4 ]
[ 126, 49 ]
python
en
['en', 'fil', 'en']
True
Command.normalize_col_name
(self, col_name, used_column_names, is_relation)
Modify the column name to make it Python-compatible as a field name
Modify the column name to make it Python-compatible as a field name
def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.app...
[ "def", "normalize_col_name", "(", "self", ",", "col_name", ",", "used_column_names", ",", "is_relation", ")", ":", "field_params", "=", "{", "}", "field_notes", "=", "[", "]", "new_name", "=", "col_name", ".", "lower", "(", ")", "if", "new_name", "!=", "co...
[ 147, 4 ]
[ 201, 50 ]
python
en
['en', 'error', 'th']
False
Command.get_field_type
(self, connection, table_name, row)
Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.
Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.
def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_pa...
[ "def", "get_field_type", "(", "self", ",", "connection", ",", "table_name", ",", "row", ")", ":", "field_params", "=", "OrderedDict", "(", ")", "field_notes", "=", "[", "]", "try", ":", "field_type", "=", "connection", ".", "introspection", ".", "get_field_t...
[ 203, 4 ]
[ 239, 52 ]
python
en
['en', 'error', 'th']
False
Command.get_meta
(self, table_name, constraints)
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
def get_meta(self, table_name, constraints): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] for index, params in constraints.item...
[ "def", "get_meta", "(", "self", ",", "table_name", ",", "constraints", ")", ":", "unique_together", "=", "[", "]", "for", "index", ",", "params", "in", "constraints", ".", "items", "(", ")", ":", "if", "params", "[", "'unique'", "]", ":", "columns", "=...
[ 241, 4 ]
[ 263, 19 ]
python
en
['en', 'error', 'th']
False
make_safe_digest
(string: str, hash_func: Callable[[bytes], Any] = hashlib.sha1)
return a hex digest of `string`.
return a hex digest of `string`.
def make_safe_digest(string: str, hash_func: Callable[[bytes], Any] = hashlib.sha1) -> str: """ return a hex digest of `string`. """ # hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must # be encoded. return hash_func(string.encode("utf-8")).hexdigest()
[ "def", "make_safe_digest", "(", "string", ":", "str", ",", "hash_func", ":", "Callable", "[", "[", "bytes", "]", ",", "Any", "]", "=", "hashlib", ".", "sha1", ")", "->", "str", ":", "# hashlib.sha1, md5, etc. expect bytes, so non-ASCII strings must", "# be encoded...
[ 88, 0 ]
[ 94, 56 ]
python
en
['en', 'error', 'th']
False
log_statsd_event
(name: str)
Sends a single event to statsd with the desired name and the current timestamp This can be used to provide vertical lines in generated graphs, for example when doing a prod deploy, bankruptcy request, or other one-off events Note that to draw this event as a vertical line in graphite you can ...
Sends a single event to statsd with the desired name and the current timestamp
def log_statsd_event(name: str) -> None: """ Sends a single event to statsd with the desired name and the current timestamp This can be used to provide vertical lines in generated graphs, for example when doing a prod deploy, bankruptcy request, or other one-off events Note that to draw this e...
[ "def", "log_statsd_event", "(", "name", ":", "str", ")", "->", "None", ":", "event_name", "=", "f\"events.{name}\"", "statsd", ".", "incr", "(", "event_name", ")" ]
[ 97, 0 ]
[ 109, 27 ]
python
en
['en', 'error', 'th']
False
query_chunker
( queries: List[Any], id_collector: Optional[Set[int]] = None, chunk_size: int = 1000, db_chunk_size: Optional[int] = None, )
This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during each yield, preserving id order across all results.. Queries should satisfy these conditions: - They should be Django filters. - They should return Django objects w...
This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during each yield, preserving id order across all results..
def query_chunker( queries: List[Any], id_collector: Optional[Set[int]] = None, chunk_size: int = 1000, db_chunk_size: Optional[int] = None, ) -> Iterator[Any]: """ This merges one or more Django ascending-id queries into a generator that returns chunks of chunk_size row objects during e...
[ "def", "query_chunker", "(", "queries", ":", "List", "[", "Any", "]", ",", "id_collector", ":", "Optional", "[", "Set", "[", "int", "]", "]", "=", "None", ",", "chunk_size", ":", "int", "=", "1000", ",", "db_chunk_size", ":", "Optional", "[", "int", ...
[ 124, 0 ]
[ 181, 51 ]
python
en
['en', 'error', 'th']
False
split_by
(array: List[Any], group_size: int, filler: Any)
Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html
Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html
def split_by(array: List[Any], group_size: int, filler: Any) -> List[List[Any]]: """ Group elements into list of size `group_size` and fill empty cells with `filler`. Recipe from https://docs.python.org/3/library/itertools.html """ args = [iter(array)] * group_size return list(map(list, zip_long...
[ "def", "split_by", "(", "array", ":", "List", "[", "Any", "]", ",", "group_size", ":", "int", ",", "filler", ":", "Any", ")", "->", "List", "[", "List", "[", "Any", "]", "]", ":", "args", "=", "[", "iter", "(", "array", ")", "]", "*", "group_si...
[ 197, 0 ]
[ 203, 64 ]
python
en
['en', 'error', 'th']
False
StatsDWrapper._our_gauge
(self, stat: str, value: float, rate: float = 1, delta: bool = False)
Set a gauge value.
Set a gauge value.
def _our_gauge(self, stat: str, value: float, rate: float = 1, delta: bool = False) -> None: """Set a gauge value.""" from django_statsd.clients import statsd if delta: value_str = f"{value:+g}|g" else: value_str = f"{value:g}|g" statsd._send(stat, value_...
[ "def", "_our_gauge", "(", "self", ",", "stat", ":", "str", ",", "value", ":", "float", ",", "rate", ":", "float", "=", "1", ",", "delta", ":", "bool", "=", "False", ")", "->", "None", ":", "from", "django_statsd", ".", "clients", "import", "statsd", ...
[ 31, 4 ]
[ 39, 43 ]
python
en
['en', 'da', 'en']
True
Loader.get_template_sources
(self, template_name, template_dirs=None)
Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons.
Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons.
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. ...
[ "def", "get_template_sources", "(", "self", ",", "template_name", ",", "template_dirs", "=", "None", ")", ":", "if", "not", "template_dirs", ":", "template_dirs", "=", "settings", ".", "TEMPLATE_DIRS", "for", "template_dir", "in", "template_dirs", ":", "try", ":...
[ 13, 4 ]
[ 31, 20 ]
python
en
['en', 'error', 'th']
False
basic_iterative_method
( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, sanity_checks=True, )
The BasicIterativeMethod attack.
The BasicIterativeMethod attack.
def basic_iterative_method( model_fn, x, eps, eps_iter, nb_iter, norm, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=0.3, sanity_checks=True, ): """ The BasicIterativeMethod attack. """ return projected_gradient_desc...
[ "def", "basic_iterative_method", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "norm", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "rand_init", "=...
[ 7, 0 ]
[ 39, 5 ]
python
en
['en', 'error', 'th']
False
Command.normalize_col_name
(self, col_name, used_column_names, is_relation)
Modify the column name to make it Python-compatible as a field name
Modify the column name to make it Python-compatible as a field name
def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.app...
[ "def", "normalize_col_name", "(", "self", ",", "col_name", ",", "used_column_names", ",", "is_relation", ")", ":", "field_params", "=", "{", "}", "field_notes", "=", "[", "]", "new_name", "=", "col_name", ".", "lower", "(", ")", "if", "new_name", "!=", "co...
[ 175, 4 ]
[ 229, 50 ]
python
en
['en', 'error', 'th']
False
Command.get_field_type
(self, connection, table_name, row)
Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.
Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field.
def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_pa...
[ "def", "get_field_type", "(", "self", ",", "connection", ",", "table_name", ",", "row", ")", ":", "field_params", "=", "{", "}", "field_notes", "=", "[", "]", "try", ":", "field_type", "=", "connection", ".", "introspection", ".", "get_field_type", "(", "r...
[ 231, 4 ]
[ 261, 52 ]
python
en
['en', 'error', 'th']
False
Command.get_meta
(self, table_name, constraints, column_to_field_name, is_view, is_partition)
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name.
def get_meta(self, table_name, constraints, column_to_field_name, is_view, is_partition): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] ...
[ "def", "get_meta", "(", "self", ",", "table_name", ",", "constraints", ",", "column_to_field_name", ",", "is_view", ",", "is_partition", ")", ":", "unique_together", "=", "[", "]", "has_unsupported_constraint", "=", "False", "for", "params", "in", "constraints", ...
[ 263, 4 ]
[ 296, 19 ]
python
en
['en', 'error', 'th']
False
dump
(o, f)
Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed
Writes out dict as toml to a file
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is pass...
[ "def", "dump", "(", "o", ",", "f", ")", ":", "if", "not", "f", ".", "write", ":", "raise", "TypeError", "(", "\"You can only dump an object to a file descriptor\"", ")", "d", "=", "dumps", "(", "o", ")", "f", ".", "write", "(", "d", ")", "return", "d" ...
[ 10, 0 ]
[ 28, 12 ]
python
en
['en', 'en', 'en']
True
dumps
(o, encoder=None)
Stringifies input dict as toml Args: o: Object to dump into toml preserve: Boolean parameter. If true, preserve inline tables. Returns: String containing the toml corresponding to dict
Stringifies input dict as toml
def dumps(o, encoder=None): """Stringifies input dict as toml Args: o: Object to dump into toml preserve: Boolean parameter. If true, preserve inline tables. Returns: String containing the toml corresponding to dict """ retval = "" if encoder is None: encoder ...
[ "def", "dumps", "(", "o", ",", "encoder", "=", "None", ")", ":", "retval", "=", "\"\"", "if", "encoder", "is", "None", ":", "encoder", "=", "TomlEncoder", "(", "o", ".", "__class__", ")", "addtoretval", ",", "sections", "=", "encoder", ".", "dump_secti...
[ 31, 0 ]
[ 63, 17 ]
python
en
['en', 'en', 'en']
True
TomlEncoder.dump_inline_table
(self, section)
Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table
Preserve inline table in its compact syntax instead of expanding into subsection.
def dump_inline_table(self, section): """Preserve inline table in its compact syntax instead of expanding into subsection. https://github.com/toml-lang/toml#user-content-inline-table """ retval = "" if isinstance(section, dict): val_list = [] for ...
[ "def", "dump_inline_table", "(", "self", ",", "section", ")", ":", "retval", "=", "\"\"", "if", "isinstance", "(", "section", ",", "dict", ")", ":", "val_list", "=", "[", "]", "for", "k", ",", "v", "in", "section", ".", "items", "(", ")", ":", "val...
[ 136, 4 ]
[ 151, 52 ]
python
en
['en', 'en', 'en']
True
MirroredMessageUsersTest.test_zephyr_mirror_new_recipient
(self, ignored: object)
Test mirror dummy user creation for PM recipients
Test mirror dummy user creation for PM recipients
def test_zephyr_mirror_new_recipient(self, ignored: object) -> None: """Test mirror dummy user creation for PM recipients""" client = get_client(name="zephyr_mirror") user = self.mit_user("starnine") sender = self.mit_user("sipbtest") new_user_email = "bob_the_new_user@mit.edu" ...
[ "def", "test_zephyr_mirror_new_recipient", "(", "self", ",", "ignored", ":", "object", ")", "->", "None", ":", "client", "=", "get_client", "(", "name", "=", "\"zephyr_mirror\"", ")", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "sender", ...
[ 62, 4 ]
[ 87, 44 ]
python
de
['nb', 'de', 'en']
False
MirroredMessageUsersTest.test_zephyr_mirror_new_sender
(self, ignored: object)
Test mirror dummy user creation for sender when sending to stream
Test mirror dummy user creation for sender when sending to stream
def test_zephyr_mirror_new_sender(self, ignored: object) -> None: """Test mirror dummy user creation for sender when sending to stream""" client = get_client(name="zephyr_mirror") user = self.mit_user("starnine") sender_email = "new_sender@mit.edu" recipients = ["stream_name"] ...
[ "def", "test_zephyr_mirror_new_sender", "(", "self", ",", "ignored", ":", "object", ")", "->", "None", ":", "client", "=", "get_client", "(", "name", "=", "\"zephyr_mirror\"", ")", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "sender_email",...
[ 93, 4 ]
[ 110, 54 ]
python
en
['en', 'no', 'en']
True
data_mnist
( datadir=tempfile.gettempdir(), train_start=0, train_end=60000, test_start=0, test_end=10000, )
Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :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 ex...
Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :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 ex...
def data_mnist( datadir=tempfile.gettempdir(), train_start=0, train_end=60000, test_start=0, test_end=10000, ): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_en...
[ "def", "data_mnist", "(", "datadir", "=", "tempfile", ".", "gettempdir", "(", ")", ",", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", ")", ":", "assert", "isinstance", "(", "tr...
[ 260, 0 ]
[ 305, 43 ]
python
en
['en', 'error', 'th']
False
data_cifar10
(train_start=0, train_end=50000, test_start=0, test_end=10000)
Preprocess CIFAR10 dataset :return:
Preprocess CIFAR10 dataset :return:
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_cols = 32 nb_classes = 10 # the data, shuffled and split between train and test sets (x_train, y_...
[ "def", "data_cifar10", "(", "train_start", "=", "0", ",", "train_end", "=", "50000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ")", ":", "# These values are specific to CIFAR10", "img_rows", "=", "32", "img_cols", "=", "32", "nb_classes", "="...
[ 309, 0 ]
[ 346, 43 ]
python
en
['en', 'error', 'th']
False
Dataset.get_factory
(self)
Returns a picklable callable that recreates the dataset.
Returns a picklable callable that recreates the dataset.
def get_factory(self): """Returns a picklable callable that recreates the dataset.""" return Factory(type(self), self.kwargs)
[ "def", "get_factory", "(", "self", ")", ":", "return", "Factory", "(", "type", "(", "self", ")", ",", "self", ".", "kwargs", ")" ]
[ 54, 4 ]
[ 57, 47 ]
python
en
['en', 'en', 'en']
True
Dataset.get_set
(self, which_set)
Returns the training set or test set as an (x_data, y_data) tuple. :param which_set: 'train' or 'test'
Returns the training set or test set as an (x_data, y_data) tuple. :param which_set: 'train' or 'test'
def get_set(self, which_set): """Returns the training set or test set as an (x_data, y_data) tuple. :param which_set: 'train' or 'test' """ return (getattr(self, "x_" + which_set), getattr(self, "y_" + which_set))
[ "def", "get_set", "(", "self", ",", "which_set", ")", ":", "return", "(", "getattr", "(", "self", ",", "\"x_\"", "+", "which_set", ")", ",", "getattr", "(", "self", ",", "\"y_\"", "+", "which_set", ")", ")" ]
[ 59, 4 ]
[ 63, 81 ]
python
en
['en', 'en', 'en']
True
Factory.__call__
(self)
Returns the created object.
Returns the created object.
def __call__(self): """Returns the created object.""" return self.cls(**self.kwargs)
[ "def", "__call__", "(", "self", ")", ":", "return", "self", ".", "cls", "(", "*", "*", "self", ".", "kwargs", ")" ]
[ 195, 4 ]
[ 197, 38 ]
python
en
['en', 'en', 'en']
True
find
(path, all=False)
Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list.
Find a static file with the given path using all enabled finders.
def find(path, all=False): """ Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list. """ searched_locations[:] = [] matches = [] for finder in get_f...
[ "def", "find", "(", "path", ",", "all", "=", "False", ")", ":", "searched_locations", "[", ":", "]", "=", "[", "]", "matches", "=", "[", "]", "for", "finder", "in", "get_finders", "(", ")", ":", "result", "=", "finder", ".", "find", "(", "path", ...
[ 257, 0 ]
[ 276, 30 ]
python
en
['en', 'error', 'th']
False
get_finder
(import_path)
Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
def get_finder(import_path): """ Import the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a subclass ...
[ "def", "get_finder", "(", "import_path", ")", ":", "Finder", "=", "import_string", "(", "import_path", ")", "if", "not", "issubclass", "(", "Finder", ",", "BaseFinder", ")", ":", "raise", "ImproperlyConfigured", "(", "'Finder \"%s\" is not a subclass of \"%s\"'", "%...
[ 285, 0 ]
[ 294, 19 ]
python
en
['en', 'error', 'th']
False
BaseFinder.find
(self, path, all=False)
Given a relative file path, find an absolute file path. If the ``all`` parameter is False (default) return only the first found file path; if True, return a list of all found files paths.
Given a relative file path, find an absolute file path.
def find(self, path, all=False): """ Given a relative file path, find an absolute file path. If the ``all`` parameter is False (default) return only the first found file path; if True, return a list of all found files paths. """ raise NotImplementedError('subclasses of B...
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseFinder must provide a find() method'", ")" ]
[ 29, 4 ]
[ 36, 90 ]
python
en
['en', 'error', 'th']
False
BaseFinder.list
(self, ignore_patterns)
Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance.
Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance.
def list(self, ignore_patterns): """ Given an optional list of paths to ignore, return a two item iterable consisting of the relative path and storage instance. """ raise NotImplementedError('subclasses of BaseFinder must provide a list() method')
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseFinder must provide a list() method'", ")" ]
[ 38, 4 ]
[ 43, 90 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.find
(self, path, all=False)
Look for files in the extra locations as defined in STATICFILES_DIRS.
Look for files in the extra locations as defined in STATICFILES_DIRS.
def find(self, path, all=False): """ Look for files in the extra locations as defined in STATICFILES_DIRS. """ matches = [] for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) matched_path ...
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "if", "root", "not", "in", "searched_locations", ":", "searched_locations", ".", ...
[ 94, 4 ]
[ 107, 22 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.find_location
(self, root, path, prefix=None)
Find a requested static file in a location and return the found absolute path (or ``None`` if no match).
Find a requested static file in a location and return the found absolute path (or ``None`` if no match).
def find_location(self, root, path, prefix=None): """ Find a requested static file in a location and return the found absolute path (or ``None`` if no match). """ if prefix: prefix = '%s%s' % (prefix, os.sep) if not path.startswith(prefix): ...
[ "def", "find_location", "(", "self", ",", "root", ",", "path", ",", "prefix", "=", "None", ")", ":", "if", "prefix", ":", "prefix", "=", "'%s%s'", "%", "(", "prefix", ",", "os", ".", "sep", ")", "if", "not", "path", ".", "startswith", "(", "prefix"...
[ 109, 4 ]
[ 121, 23 ]
python
en
['en', 'error', 'th']
False
FileSystemFinder.list
(self, ignore_patterns)
List all files in all locations.
List all files in all locations.
def list(self, ignore_patterns): """ List all files in all locations. """ for prefix, root in self.locations: storage = self.storages[root] for path in utils.get_files(storage, ignore_patterns): yield path, storage
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "prefix", ",", "root", "in", "self", ".", "locations", ":", "storage", "=", "self", ".", "storages", "[", "root", "]", "for", "path", "in", "utils", ".", "get_files", "(", "storage", ...
[ 123, 4 ]
[ 130, 35 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.list
(self, ignore_patterns)
List all files in all app storages.
List all files in all app storages.
def list(self, ignore_patterns): """ List all files in all app storages. """ for storage in self.storages.values(): if storage.exists(''): # check if storage location exists for path in utils.get_files(storage, ignore_patterns): yield path...
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "storage", "in", "self", ".", "storages", ".", "values", "(", ")", ":", "if", "storage", ".", "exists", "(", "''", ")", ":", "# check if storage location exists", "for", "path", "in", "...
[ 159, 4 ]
[ 166, 39 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.find
(self, path, all=False)
Look for files in the app directories.
Look for files in the app directories.
def find(self, path, all=False): """ Look for files in the app directories. """ matches = [] for app in self.apps: app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location)...
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "app", "in", "self", ".", "apps", ":", "app_location", "=", "self", ".", "storages", "[", "app", "]", ".", "location", "if", "app_location...
[ 168, 4 ]
[ 182, 22 ]
python
en
['en', 'error', 'th']
False
AppDirectoriesFinder.find_in_app
(self, app, path)
Find a requested static file in an app's static locations.
Find a requested static file in an app's static locations.
def find_in_app(self, app, path): """ Find a requested static file in an app's static locations. """ storage = self.storages.get(app) if storage: # only try to find a file if the source dir actually exists if storage.exists(path): matched_p...
[ "def", "find_in_app", "(", "self", ",", "app", ",", "path", ")", ":", "storage", "=", "self", ".", "storages", ".", "get", "(", "app", ")", "if", "storage", ":", "# only try to find a file if the source dir actually exists", "if", "storage", ".", "exists", "("...
[ 184, 4 ]
[ 194, 39 ]
python
en
['en', 'error', 'th']
False
BaseStorageFinder.find
(self, path, all=False)
Look for files in the default file storage, if it's local.
Look for files in the default file storage, if it's local.
def find(self, path, all=False): """ Look for files in the default file storage, if it's local. """ try: self.storage.path('') except NotImplementedError: pass else: if self.storage.location not in searched_locations: se...
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "try", ":", "self", ".", "storage", ".", "path", "(", "''", ")", "except", "NotImplementedError", ":", "pass", "else", ":", "if", "self", ".", "storage", ".", "location", ...
[ 216, 4 ]
[ 232, 17 ]
python
en
['en', 'error', 'th']
False
BaseStorageFinder.list
(self, ignore_patterns)
List all files of the storage.
List all files of the storage.
def list(self, ignore_patterns): """ List all files of the storage. """ for path in utils.get_files(self.storage, ignore_patterns): yield path, self.storage
[ "def", "list", "(", "self", ",", "ignore_patterns", ")", ":", "for", "path", "in", "utils", ".", "get_files", "(", "self", ".", "storage", ",", "ignore_patterns", ")", ":", "yield", "path", ",", "self", ".", "storage" ]
[ 234, 4 ]
[ 239, 36 ]
python
en
['en', 'error', 'th']
False
create_dependency_source
( requirement: str, name: Optional[str] = None, **kwargs: Any )
Factory for creating a dependency source object. Args: requirement (str): Package name/path/constraints in string form. name (str, optional): Override package name. Defaults to None. Returns: Appropriate Dependency Source
Factory for creating a dependency source object.
def create_dependency_source( requirement: str, name: Optional[str] = None, **kwargs: Any ) -> Union[LocalDependencySource, PackageDependencySource, VCSDependencySource]: """Factory for creating a dependency source object. Args: requirement (str): Package name/path/constraints in string form. ...
[ "def", "create_dependency_source", "(", "requirement", ":", "str", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Union", "[", "LocalDependencySource", ",", "PackageDependencySource", ",", "VCSDep...
[ 19, 0 ]
[ 43, 49 ]
python
en
['en', 'en', 'en']
True
serialize
(input, tree="etree", encoding=None, **serializer_opts)
Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created ...
Serializes the input token stream using the specified treewalker
def serialize(input, tree="etree", encoding=None, **serializer_opts): """Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the...
[ "def", "serialize", "(", "input", ",", "tree", "=", "\"etree\"", ",", "encoding", "=", "None", ",", "*", "*", "serializer_opts", ")", ":", "# XXX: Should we cache this?", "walker", "=", "treewalkers", ".", "getTreeWalker", "(", "tree", ")", "s", "=", "HTMLSe...
[ 74, 0 ]
[ 100, 44 ]
python
en
['en', 'en', 'en']
True
HTMLSerializer.__init__
(self, **kwargs)
Initialize HTMLSerializer :arg inject_meta_charset: Whether or not to inject the meta charset. Defaults to ``True``. :arg quote_attr_values: Whether to quote attribute values that don't require quoting per legacy browser behavior (``"legacy"``), when required by th...
Initialize HTMLSerializer
def __init__(self, **kwargs): """Initialize HTMLSerializer :arg inject_meta_charset: Whether or not to inject the meta charset. Defaults to ``True``. :arg quote_attr_values: Whether to quote attribute values that don't require quoting per legacy browser behavior (``"le...
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "unexpected_args", "=", "frozenset", "(", "kwargs", ")", "-", "frozenset", "(", "self", ".", "options", ")", "if", "len", "(", "unexpected_args", ")", ">", "0", ":", "raise", "TypeError...
[ 134, 4 ]
[ 221, 27 ]
python
de
['de', 'en', 'nl']
False
HTMLSerializer.render
(self, treewalker, encoding=None)
Serializes the stream from the treewalker into a string :arg treewalker: the treewalker to serialize :arg encoding: the string encoding to use :returns: the serialized tree Example: >>> from html5lib import parse, getTreeWalker >>> from html5lib.serializer import HTM...
Serializes the stream from the treewalker into a string
def render(self, treewalker, encoding=None): """Serializes the stream from the treewalker into a string :arg treewalker: the treewalker to serialize :arg encoding: the string encoding to use :returns: the serialized tree Example: >>> from html5lib import parse, getTr...
[ "def", "render", "(", "self", ",", "treewalker", ",", "encoding", "=", "None", ")", ":", "if", "encoding", ":", "return", "b\"\"", ".", "join", "(", "list", "(", "self", ".", "serialize", "(", "treewalker", ",", "encoding", ")", ")", ")", "else", ":"...
[ 374, 4 ]
[ 397, 60 ]
python
en
['en', 'en', 'en']
True
standardize_headers
(input_headers: Union[None, Dict[str, Any]])
This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers NOTE: Historically, Django's headers were not case-insensitive. We're still c...
This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers
def standardize_headers(input_headers: Union[None, Dict[str, Any]]) -> Dict[str, str]: """This method can be used to standardize a dictionary of headers with the standard format that Django expects. For reference, refer to: https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest....
[ "def", "standardize_headers", "(", "input_headers", ":", "Union", "[", "None", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "canonical_headers", "=", "{", "}", "if", "not", "input_headers", ":", ...
[ 97, 0 ]
[ 117, 28 ]
python
en
['en', 'en', 'en']
True
get_fixture_http_headers
(integration_name: str, fixture_name: str)
For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP headers goes with the given test fixture.
For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP headers goes with the given test fixture.
def get_fixture_http_headers(integration_name: str, fixture_name: str) -> Dict["str", "str"]: """For integrations that require custom HTTP headers for some (or all) of their test fixtures, this method will call a specially named function from the target integration module to determine what set of HTTP h...
[ "def", "get_fixture_http_headers", "(", "integration_name", ":", "str", ",", "fixture_name", ":", "str", ")", "->", "Dict", "[", "\"str\"", ",", "\"str\"", "]", ":", "view_module_name", "=", "f\"zerver.webhooks.{integration_name}.view\"", "try", ":", "# TODO: We may w...
[ 141, 0 ]
[ 155, 43 ]
python
en
['en', 'en', 'en']
True
get_http_headers_from_filename
(http_header_key: str)
If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use this method in the headers.py file for the integration.
If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use this method in the headers.py file for the integration.
def get_http_headers_from_filename(http_header_key: str) -> Callable[[str], Dict[str, str]]: """If an integration requires an event type kind of HTTP header which can be easily (statically) determined, then name the fixtures in the format of "header_value__other_details" or even "header_value" and the use t...
[ "def", "get_http_headers_from_filename", "(", "http_header_key", ":", "str", ")", "->", "Callable", "[", "[", "str", "]", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "def", "fixture_to_headers", "(", "filename", ":", "str", ")", "->", "Dict", "["...
[ 158, 0 ]
[ 171, 29 ]
python
en
['en', 'en', 'en']
True
unix_milliseconds_to_timestamp
(milliseconds: Any, webhook: str)
If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time.
If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time.
def unix_milliseconds_to_timestamp(milliseconds: Any, webhook: str) -> datetime: """If an integration requires time input in unix milliseconds, this helper checks to ensure correct type and will catch any errors related to type or value and raise a JsonableError. Returns a datetime representing the time...
[ "def", "unix_milliseconds_to_timestamp", "(", "milliseconds", ":", "Any", ",", "webhook", ":", "str", ")", "->", "datetime", ":", "try", ":", "# timestamps are in milliseconds so divide by 1000", "seconds", "=", "milliseconds", "/", "1000", "return", "timestamp_to_datet...
[ 174, 0 ]
[ 184, 94 ]
python
en
['en', 'en', 'en']
True
user_passes_test
(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME)
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes.
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. ...
[ "def", "user_passes_test", "(", "test_func", ",", "login_url", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "def", "_wrapped_view", "(", "req...
[ 9, 0 ]
[ 34, 20 ]
python
en
['en', 'error', 'th']
False
login_required
(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None)
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary.
Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary.
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=lo...
[ "def", "login_required", "(", "function", "=", "None", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "login_url", "=", "None", ")", ":", "actual_decorator", "=", "user_passes_test", "(", "lambda", "u", ":", "u", ".", "is_authenticated", ",", "logi...
[ 37, 0 ]
[ 49, 27 ]
python
en
['en', 'error', 'th']
False
permission_required
(perm, login_url=None, raise_exception=False)
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised.
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised.
def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ d...
[ "def", "permission_required", "(", "perm", ",", "login_url", "=", "None", ",", "raise_exception", "=", "False", ")", ":", "def", "check_perms", "(", "user", ")", ":", "if", "isinstance", "(", "perm", ",", "str", ")", ":", "perms", "=", "(", "perm", ","...
[ 52, 0 ]
[ 72, 61 ]
python
en
['en', 'error', 'th']
False
_get_failure_view
()
Returns the view to be used for CSRF rejections
Returns the view to be used for CSRF rejections
def _get_failure_view(): """ Returns the view to be used for CSRF rejections """ return get_callable(settings.CSRF_FAILURE_VIEW)
[ "def", "_get_failure_view", "(", ")", ":", "return", "get_callable", "(", "settings", ".", "CSRF_FAILURE_VIEW", ")" ]
[ 29, 0 ]
[ 33, 51 ]
python
en
['en', 'error', 'th']
False
get_token
(request)
Returns the CSRF token required for a POST form. The token is an alphanumeric value. A side effect of calling this function is to make the csrf_protect decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie' header to the outgoing response. For this reason, you may need to use...
Returns the CSRF token required for a POST form. The token is an alphanumeric value.
def get_token(request): """ Returns the CSRF token required for a POST form. The token is an alphanumeric value. A side effect of calling this function is to make the csrf_protect decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie' header to the outgoing response. For t...
[ "def", "get_token", "(", "request", ")", ":", "request", ".", "META", "[", "\"CSRF_COOKIE_USED\"", "]", "=", "True", "return", "request", ".", "META", ".", "get", "(", "\"CSRF_COOKIE\"", ",", "None", ")" ]
[ 40, 0 ]
[ 51, 48 ]
python
en
['en', 'error', 'th']
False
rotate_token
(request)
Changes the CSRF token in use for a request - should be done on login for security purposes.
Changes the CSRF token in use for a request - should be done on login for security purposes.
def rotate_token(request): """ Changes the CSRF token in use for a request - should be done on login for security purposes. """ request.META.update({ "CSRF_COOKIE_USED": True, "CSRF_COOKIE": _get_new_csrf_key(), })
[ "def", "rotate_token", "(", "request", ")", ":", "request", ".", "META", ".", "update", "(", "{", "\"CSRF_COOKIE_USED\"", ":", "True", ",", "\"CSRF_COOKIE\"", ":", "_get_new_csrf_key", "(", ")", ",", "}", ")" ]
[ 54, 0 ]
[ 62, 6 ]
python
en
['en', 'error', 'th']
False
serve
(request, path, document_root=None, show_indexes=False)
Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may als...
Serve static files below a given point in the directory structure.
def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in yo...
[ "def", "serve", "(", "request", ",", "path", ",", "document_root", "=", "None", ",", "show_indexes", "=", "False", ")", ":", "path", "=", "posixpath", ".", "normpath", "(", "path", ")", ".", "lstrip", "(", "'/'", ")", "fullpath", "=", "Path", "(", "s...
[ 18, 0 ]
[ 53, 19 ]
python
en
['en', 'error', 'th']
False
was_modified_since
(header=None, mtime=0, size=0)
Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking ab...
Was something modified since the user last downloaded it?
def was_modified_since(header=None, mtime=0, size=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. ...
[ "def", "was_modified_since", "(", "header", "=", "None", ",", "mtime", "=", "0", ",", "size", "=", "0", ")", ":", "try", ":", "if", "header", "is", "None", ":", "raise", "ValueError", "matches", "=", "re", ".", "match", "(", "r\"^([^;]+)(; length=([0-9]+...
[ 107, 0 ]
[ 134, 16 ]
python
en
['en', 'error', 'th']
False
MigrationQuestioner.ask_initial
(self, app_label)
Should we create an initial migration for the app?
Should we create an initial migration for the app?
def ask_initial(self, app_label): "Should we create an initial migration for the app?" # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Otherwise, we look to see if it has a migrations module # without any P...
[ "def", "ask_initial", "(", "self", ",", "app_label", ")", ":", "# If it was specified on the command line, definitely true", "if", "app_label", "in", "self", ".", "specified_apps", ":", "return", "True", "# Otherwise, we look to see if it has a migrations module", "# without an...
[ 26, 4 ]
[ 51, 86 ]
python
en
['en', 'en', 'en']
True
MigrationQuestioner.ask_not_null_addition
(self, field_name, model_name)
Adding a NOT NULL field to a model
Adding a NOT NULL field to a model
def ask_not_null_addition(self, field_name, model_name): "Adding a NOT NULL field to a model" # None means quit return None
[ "def", "ask_not_null_addition", "(", "self", ",", "field_name", ",", "model_name", ")", ":", "# None means quit", "return", "None" ]
[ 53, 4 ]
[ 56, 19 ]
python
en
['en', 'en', 'en']
True
MigrationQuestioner.ask_not_null_alteration
(self, field_name, model_name)
Changing a NULL field to NOT NULL
Changing a NULL field to NOT NULL
def ask_not_null_alteration(self, field_name, model_name): "Changing a NULL field to NOT NULL" # None means quit return None
[ "def", "ask_not_null_alteration", "(", "self", ",", "field_name", ",", "model_name", ")", ":", "# None means quit", "return", "None" ]
[ 58, 4 ]
[ 61, 19 ]
python
en
['en', 'en', 'en']
True
MigrationQuestioner.ask_rename
(self, model_name, old_name, new_name, field_instance)
Was this field really renamed?
Was this field really renamed?
def ask_rename(self, model_name, old_name, new_name, field_instance): "Was this field really renamed?" return self.defaults.get("ask_rename", False)
[ "def", "ask_rename", "(", "self", ",", "model_name", ",", "old_name", ",", "new_name", ",", "field_instance", ")", ":", "return", "self", ".", "defaults", ".", "get", "(", "\"ask_rename\"", ",", "False", ")" ]
[ 63, 4 ]
[ 65, 53 ]
python
en
['en', 'en', 'en']
True
MigrationQuestioner.ask_rename_model
(self, old_model_state, new_model_state)
Was this model really renamed?
Was this model really renamed?
def ask_rename_model(self, old_model_state, new_model_state): "Was this model really renamed?" return self.defaults.get("ask_rename_model", False)
[ "def", "ask_rename_model", "(", "self", ",", "old_model_state", ",", "new_model_state", ")", ":", "return", "self", ".", "defaults", ".", "get", "(", "\"ask_rename_model\"", ",", "False", ")" ]
[ 67, 4 ]
[ 69, 59 ]
python
en
['en', 'en', 'en']
True
MigrationQuestioner.ask_merge
(self, app_label)
Do you really want to merge these migrations?
Do you really want to merge these migrations?
def ask_merge(self, app_label): "Do you really want to merge these migrations?" return self.defaults.get("ask_merge", False)
[ "def", "ask_merge", "(", "self", ",", "app_label", ")", ":", "return", "self", ".", "defaults", ".", "get", "(", "\"ask_merge\"", ",", "False", ")" ]
[ 71, 4 ]
[ 73, 52 ]
python
en
['en', 'en', 'en']
True
InteractiveMigrationQuestioner.ask_not_null_addition
(self, field_name, model_name)
Adding a NOT NULL field to a model
Adding a NOT NULL field to a model
def ask_not_null_addition(self, field_name, model_name): "Adding a NOT NULL field to a model" if not self.dry_run: choice = self._choice_input( "You are trying to add a non-nullable field '%s' to %s without a default; " "we can't do that (the database needs so...
[ "def", "ask_not_null_addition", "(", "self", ",", "field_name", ",", "model_name", ")", ":", "if", "not", "self", ".", "dry_run", ":", "choice", "=", "self", ".", "_choice_input", "(", "\"You are trying to add a non-nullable field '%s' to %s without a default; \"", "\"w...
[ 121, 4 ]
[ 137, 19 ]
python
en
['en', 'en', 'en']
True
InteractiveMigrationQuestioner.ask_not_null_alteration
(self, field_name, model_name)
Changing a NULL field to NOT NULL
Changing a NULL field to NOT NULL
def ask_not_null_alteration(self, field_name, model_name): "Changing a NULL field to NOT NULL" if not self.dry_run: choice = self._choice_input( "You are trying to change the nullable field '%s' on %s to non-nullable " "without a default; we can't do that (the...
[ "def", "ask_not_null_alteration", "(", "self", ",", "field_name", ",", "model_name", ")", ":", "if", "not", "self", ".", "dry_run", ":", "choice", "=", "self", ".", "_choice_input", "(", "\"You are trying to change the nullable field '%s' on %s to non-nullable \"", "\"w...
[ 139, 4 ]
[ 161, 19 ]
python
en
['en', 'en', 'en']
True
InteractiveMigrationQuestioner.ask_rename
(self, model_name, old_name, new_name, field_instance)
Was this field really renamed?
Was this field really renamed?
def ask_rename(self, model_name, old_name, new_name, field_instance): "Was this field really renamed?" return self._boolean_input("Did you rename %s.%s to %s.%s (a %s)? [y/N]" % (model_name, old_name, model_name, new_name, field_instance.__class__.__name__), False)
[ "def", "ask_rename", "(", "self", ",", "model_name", ",", "old_name", ",", "new_name", ",", "field_instance", ")", ":", "return", "self", ".", "_boolean_input", "(", "\"Did you rename %s.%s to %s.%s (a %s)? [y/N]\"", "%", "(", "model_name", ",", "old_name", ",", "...
[ 163, 4 ]
[ 165, 170 ]
python
en
['en', 'en', 'en']
True
InteractiveMigrationQuestioner.ask_rename_model
(self, old_model_state, new_model_state)
Was this model really renamed?
Was this model really renamed?
def ask_rename_model(self, old_model_state, new_model_state): "Was this model really renamed?" return self._boolean_input("Did you rename the %s.%s model to %s? [y/N]" % (old_model_state.app_label, old_model_state.name, new_model_state.name), False)
[ "def", "ask_rename_model", "(", "self", ",", "old_model_state", ",", "new_model_state", ")", ":", "return", "self", ".", "_boolean_input", "(", "\"Did you rename the %s.%s model to %s? [y/N]\"", "%", "(", "old_model_state", ".", "app_label", ",", "old_model_state", ".",...
[ 167, 4 ]
[ 169, 162 ]
python
en
['en', 'en', 'en']
True
create_python_neuropod
( neuropod_path, data_paths, code_path_spec, entrypoint_package, entrypoint, requirements=None, **kwargs )
Packages arbitrary python code as a neuropod package. {common_doc_pre} :param data_paths: A list of dicts containing the paths to any data files that needs to be packaged. !!! note "" ***Example***: ...
Packages arbitrary python code as a neuropod package.
def create_python_neuropod( neuropod_path, data_paths, code_path_spec, entrypoint_package, entrypoint, requirements=None, **kwargs ): """ Packages arbitrary python code as a neuropod package. {common_doc_pre} :param data_paths: A list of dicts containing the paths ...
[ "def", "create_python_neuropod", "(", "neuropod_path", ",", "data_paths", ",", "code_path_spec", ",", "entrypoint_package", ",", "entrypoint", ",", "requirements", "=", "None", ",", "*", "*", "kwargs", ")", ":", "neuropod_data_path", "=", "os", ".", "path", ".",...
[ 24, 0 ]
[ 156, 9 ]
python
en
['en', 'error', 'th']
False
install_pytorch
(version)
:param version: The version of torch. This can be something like "1.2.0" or "1.1.0.dev20190601"
:param version: The version of torch. This can be something like "1.2.0" or "1.1.0.dev20190601"
def install_pytorch(version): """ :param version: The version of torch. This can be something like "1.2.0" or "1.1.0.dev20190601" """ pip_args = [] # Get the torch cuda string (e.g. cpu, cu90, cu92, cu100) torch_cuda_string = "cu{}".format(CUDA_VERSION.replace(".", "...
[ "def", "install_pytorch", "(", "version", ")", ":", "pip_args", "=", "[", "]", "# Get the torch cuda string (e.g. cpu, cu90, cu92, cu100)", "torch_cuda_string", "=", "\"cu{}\"", ".", "format", "(", "CUDA_VERSION", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ")",...
[ 36, 0 ]
[ 114, 25 ]
python
en
['en', 'error', 'th']
False
module_to_dict
(module, omittable=lambda k: k.startswith('_') or not k.isupper())
Convert a module namespace to a Python dictionary.
Convert a module namespace to a Python dictionary.
def module_to_dict(module, omittable=lambda k: k.startswith('_') or not k.isupper()): """Convert a module namespace to a Python dictionary.""" return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)}
[ "def", "module_to_dict", "(", "module", ",", "omittable", "=", "lambda", "k", ":", "k", ".", "startswith", "(", "'_'", ")", "or", "not", "k", ".", "isupper", "(", ")", ")", ":", "return", "{", "k", ":", "repr", "(", "getattr", "(", "module", ",", ...
[ 3, 0 ]
[ 5, 81 ]
python
en
['en', 'en', 'en']
True
test_setup
(mock_micropy_path)
Tests MicroPy Initial Setup
Tests MicroPy Initial Setup
def test_setup(mock_micropy_path): """Tests MicroPy Initial Setup""" expect_mp_dir = mock_micropy_path expect_stubs_dir = mock_micropy_path / "stubs" mp = main.MicroPy() assert expect_mp_dir.exists() assert expect_stubs_dir.exists() # Test after inital setup mp_ = main.MicroPy() asse...
[ "def", "test_setup", "(", "mock_micropy_path", ")", ":", "expect_mp_dir", "=", "mock_micropy_path", "expect_stubs_dir", "=", "mock_micropy_path", "/", "\"stubs\"", "mp", "=", "main", ".", "MicroPy", "(", ")", "assert", "expect_mp_dir", ".", "exists", "(", ")", "...
[ 12, 0 ]
[ 21, 42 ]
python
en
['en', 'en', 'en']
True
test_add_stub
(mock_micropy, shared_datadir)
Test Adding Valid Stub
Test Adding Valid Stub
def test_add_stub(mock_micropy, shared_datadir): """Test Adding Valid Stub""" fware_path = shared_datadir / "fware_test_stub" stub_path = shared_datadir / "esp8266_test_stub" stubs = mock_micropy.stubs fware_stub = stubs.add(fware_path, data.STUB_DIR) stub = stubs.add(stub_path, data.STUB_DIR) ...
[ "def", "test_add_stub", "(", "mock_micropy", ",", "shared_datadir", ")", ":", "fware_path", "=", "shared_datadir", "/", "\"fware_test_stub\"", "stub_path", "=", "shared_datadir", "/", "\"esp8266_test_stub\"", "stubs", "=", "mock_micropy", ".", "stubs", "fware_stub", "...
[ 24, 0 ]
[ 34, 59 ]
python
en
['en', 'et', 'en']
True
test_create_stub
(mock_micropy, mocker, shared_datadir, tmp_path)
should create and add stubs
should create and add stubs
def test_create_stub(mock_micropy, mocker, shared_datadir, tmp_path): """should create and add stubs""" mock_micropy.stubs.add((shared_datadir / "fware_test_stub")) tmp_stub_path = tmp_path / "createtest" tmp_stub_path.mkdir() copytree(str(shared_datadir / "stubber_test_stub"), str(tmp_stub_path / "...
[ "def", "test_create_stub", "(", "mock_micropy", ",", "mocker", ",", "shared_datadir", ",", "tmp_path", ")", ":", "mock_micropy", ".", "stubs", ".", "add", "(", "(", "shared_datadir", "/", "\"fware_test_stub\"", ")", ")", "tmp_stub_path", "=", "tmp_path", "/", ...
[ 37, 0 ]
[ 61, 45 ]
python
en
['en', 'en', 'en']
True
test_create_stubs_pymin_check
(mocker, mock_micropy)
should exit without pymin
should exit without pymin
def test_create_stubs_pymin_check(mocker, mock_micropy): """should exit without pymin""" mocker.patch("micropy.main.utils.PyboardWrapper") mocker.patch("micropy.main.StubManager") mock_stubber = mocker.patch.object(main, "stubber") mock_exit = mocker.spy(main.sys, "exit") mock_stubber.minify_scr...
[ "def", "test_create_stubs_pymin_check", "(", "mocker", ",", "mock_micropy", ")", ":", "mocker", ".", "patch", "(", "\"micropy.main.utils.PyboardWrapper\"", ")", "mocker", ".", "patch", "(", "\"micropy.main.StubManager\"", ")", "mock_stubber", "=", "mocker", ".", "patc...
[ 64, 0 ]
[ 76, 40 ]
python
en
['en', 'en', 'en']
True
bdist_rpm._make_spec_file
(self)
Generate the text of an RPM spec file and return it as a list of strings (one per line).
Generate the text of an RPM spec file and return it as a list of strings (one per line).
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_ve...
[ "def", "_make_spec_file", "(", "self", ")", ":", "# definitions and headers", "spec_file", "=", "[", "'%define name '", "+", "self", ".", "distribution", ".", "get_name", "(", ")", ",", "'%define version '", "+", "self", ".", "distribution", ".", "get_version", ...
[ 390, 4 ]
[ 557, 24 ]
python
en
['en', 'en', 'en']
True
bdist_rpm._format_changelog
(self, changelog)
Format the changelog correctly and convert it to a list of strings
Format the changelog correctly and convert it to a list of strings
def _format_changelog(self, changelog): """Format the changelog correctly and convert it to a list of strings """ if not changelog: return changelog new_changelog = [] for line in changelog.strip().split('\n'): line = line.strip() if line[0] ==...
[ "def", "_format_changelog", "(", "self", ",", "changelog", ")", ":", "if", "not", "changelog", ":", "return", "changelog", "new_changelog", "=", "[", "]", "for", "line", "in", "changelog", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ":", "...
[ 559, 4 ]
[ 578, 28 ]
python
en
['en', 'en', 'en']
True
ensure_default_manager
(cls)
Ensures that a Model subclass contains a default manager and sets the _default_manager attribute on the class. Also sets up the _base_manager points to a plain Manager instance (which could be the same as _default_manager if it's not a subclass of Manager).
Ensures that a Model subclass contains a default manager and sets the _default_manager attribute on the class. Also sets up the _base_manager points to a plain Manager instance (which could be the same as _default_manager if it's not a subclass of Manager).
def ensure_default_manager(cls): """ Ensures that a Model subclass contains a default manager and sets the _default_manager attribute on the class. Also sets up the _base_manager points to a plain Manager instance (which could be the same as _default_manager if it's not a subclass of Manager). ...
[ "def", "ensure_default_manager", "(", "cls", ")", ":", "if", "cls", ".", "_meta", ".", "abstract", ":", "setattr", "(", "cls", ",", "'objects'", ",", "AbstractManagerDescriptor", "(", "cls", ")", ")", "return", "elif", "cls", ".", "_meta", ".", "swapped", ...
[ 10, 0 ]
[ 52, 13 ]
python
en
['en', 'error', 'th']
False
move_rows
( base_model: Model, raw_query: Composable, *, src_db_table: Optional[str] = None, returning_id: bool = False, **kwargs: Composable, )
Core helper for bulk moving rows between a table and its archive table
Core helper for bulk moving rows between a table and its archive table
def move_rows( base_model: Model, raw_query: Composable, *, src_db_table: Optional[str] = None, returning_id: bool = False, **kwargs: Composable, ) -> List[int]: """Core helper for bulk moving rows between a table and its archive table""" if src_db_table is None: # Use base_model...
[ "def", "move_rows", "(", "base_model", ":", "Model", ",", "raw_query", ":", "Composable", ",", "*", ",", "src_db_table", ":", "Optional", "[", "str", "]", "=", "None", ",", "returning_id", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Compo...
[ 92, 0 ]
[ 119, 21 ]
python
en
['en', 'en', 'en']
True