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
get_current_url
( environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None, )
A handy helper function that recreates the full URL as IRI for the current request or parts of it. Here's an example: >>> from werkzeug.test import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>...
A handy helper function that recreates the full URL as IRI for the current request or parts of it. Here's an example:
def get_current_url( environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None, ): """A handy helper function that recreates the full URL as IRI for the current request or parts of it. Here's an example: >>> from werkzeug.test import create_environ >>> ...
[ "def", "get_current_url", "(", "environ", ",", "root_only", "=", "False", ",", "strip_querystring", "=", "False", ",", "host_only", "=", "False", ",", "trusted_hosts", "=", "None", ",", ")", ":", "tmp", "=", "[", "environ", "[", "\"wsgi.url_scheme\"", "]", ...
[ 45, 0 ]
[ 98, 35 ]
python
en
['en', 'en', 'en']
True
host_is_trusted
(hostname, trusted_list)
Checks if a host is trusted against a list. This also takes care of port normalization. .. versionadded:: 0.9 :param hostname: the hostname to check :param trusted_list: a list of hostnames to check against. If a hostname starts with a dot it will match against ...
Checks if a host is trusted against a list. This also takes care of port normalization.
def host_is_trusted(hostname, trusted_list): """Checks if a host is trusted against a list. This also takes care of port normalization. .. versionadded:: 0.9 :param hostname: the hostname to check :param trusted_list: a list of hostnames to check against. If a hostname s...
[ "def", "host_is_trusted", "(", "hostname", ",", "trusted_list", ")", ":", "if", "not", "hostname", ":", "return", "False", "if", "isinstance", "(", "trusted_list", ",", "string_types", ")", ":", "trusted_list", "=", "[", "trusted_list", "]", "def", "_normalize...
[ 101, 0 ]
[ 141, 16 ]
python
en
['en', 'en', 'en']
True
get_host
(environ, trusted_hosts=None)
Return the host for the given WSGI environment. This first checks the ``Host`` header. If it's not present, then ``SERVER_NAME`` and ``SERVER_PORT`` are used. The host will only contain the port if it is different than the standard port for the protocol. Optionally, verify that the host is trusted usin...
Return the host for the given WSGI environment. This first checks the ``Host`` header. If it's not present, then ``SERVER_NAME`` and ``SERVER_PORT`` are used. The host will only contain the port if it is different than the standard port for the protocol.
def get_host(environ, trusted_hosts=None): """Return the host for the given WSGI environment. This first checks the ``Host`` header. If it's not present, then ``SERVER_NAME`` and ``SERVER_PORT`` are used. The host will only contain the port if it is different than the standard port for the protocol. ...
[ "def", "get_host", "(", "environ", ",", "trusted_hosts", "=", "None", ")", ":", "if", "\"HTTP_HOST\"", "in", "environ", ":", "rv", "=", "environ", "[", "\"HTTP_HOST\"", "]", "if", "environ", "[", "\"wsgi.url_scheme\"", "]", "==", "\"http\"", "and", "rv", "...
[ 144, 0 ]
[ 178, 13 ]
python
en
['en', 'en', 'en']
True
get_content_length
(environ)
Returns the content length from the WSGI environment as integer. If it's not available or chunked transfer encoding is used, ``None`` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from.
Returns the content length from the WSGI environment as integer. If it's not available or chunked transfer encoding is used, ``None`` is returned.
def get_content_length(environ): """Returns the content length from the WSGI environment as integer. If it's not available or chunked transfer encoding is used, ``None`` is returned. .. versionadded:: 0.9 :param environ: the WSGI environ to fetch the content length from. """ if environ.get...
[ "def", "get_content_length", "(", "environ", ")", ":", "if", "environ", ".", "get", "(", "\"HTTP_TRANSFER_ENCODING\"", ",", "\"\"", ")", "==", "\"chunked\"", ":", "return", "None", "content_length", "=", "environ", ".", "get", "(", "\"CONTENT_LENGTH\"", ")", "...
[ 181, 0 ]
[ 198, 16 ]
python
en
['en', 'en', 'en']
True
get_input_stream
(environ, safe_fallback=True)
Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for sa...
Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length.
def get_input_stream(environ, safe_fallback=True): """Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If ...
[ "def", "get_input_stream", "(", "environ", ",", "safe_fallback", "=", "True", ")", ":", "stream", "=", "environ", "[", "\"wsgi.input\"", "]", "content_length", "=", "get_content_length", "(", "environ", ")", "# A wsgi extension that tells us if the input is terminated. I...
[ 201, 0 ]
[ 234, 48 ]
python
en
['en', 'en', 'en']
True
get_query_string
(environ)
Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the query str...
Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters.
def get_query_string(environ): """Returns the `QUERY_STRING` from the WSGI environment. This also takes care about the WSGI decoding dance on Python 3 environments as a native string. The string returned will be restricted to ASCII characters. .. versionadded:: 0.9 :param environ: the WSGI e...
[ "def", "get_query_string", "(", "environ", ")", ":", "qs", "=", "wsgi_get_bytes", "(", "environ", ".", "get", "(", "\"QUERY_STRING\"", ",", "\"\"", ")", ")", "# QUERY_STRING really should be ascii safe but some browsers", "# will send us some unicode stuff (I am looking at yo...
[ 237, 0 ]
[ 251, 64 ]
python
en
['en', 'en', 'en']
True
get_path_info
(environ, charset="utf-8", errors="replace")
Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path fr...
Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned.
def get_path_info(environ, charset="utf-8", errors="replace"): """Returns the `PATH_INFO` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0...
[ "def", "get_path_info", "(", "environ", ",", "charset", "=", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", ":", "path", "=", "wsgi_get_bytes", "(", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ")", "return", "to_unicode", "(", "pat...
[ 254, 0 ]
[ 268, 69 ]
python
en
['en', 'en', 'en']
True
get_script_name
(environ, charset="utf-8", errors="replace")
Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded:: 0.9 :param environ: the WSGI environment object to get the path ...
Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned.
def get_script_name(environ, charset="utf-8", errors="replace"): """Returns the `SCRIPT_NAME` from the WSGI environment and properly decodes it. This also takes care about the WSGI decoding dance on Python 3 environments. if the `charset` is set to `None` a bytestring is returned. .. versionadded...
[ "def", "get_script_name", "(", "environ", ",", "charset", "=", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", ":", "path", "=", "wsgi_get_bytes", "(", "environ", ".", "get", "(", "\"SCRIPT_NAME\"", ",", "\"\"", ")", ")", "return", "to_unicode", "(", ...
[ 271, 0 ]
[ 285, 69 ]
python
en
['en', 'en', 'en']
True
pop_path_info
(environ, charset="utf-8", errors="replace")
Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/foo//bar``) these are ignored but properly pushed to the `SCRIPT_NAM...
Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
def pop_path_info(environ, charset="utf-8", errors="replace"): """Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` a bytestring is returned. If there are empty segments (``'/fo...
[ "def", "pop_path_info", "(", "environ", ",", "charset", "=", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", ":", "path", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ")", "if", "not", "path", ":", "return", "None", "script_name", "=", "environ",...
[ 288, 0 ]
[ 337, 67 ]
python
en
['en', 'en', 'en']
True
peek_path_info
(environ, charset="utf-8", errors="replace")
Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`pop_path_info` without modifying the environment: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' >>> peek_path_info(env) 'a' If the `charset` is set to `None` ...
Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`pop_path_info` without modifying the environment:
def peek_path_info(environ, charset="utf-8", errors="replace"): """Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like :func:`pop_path_info` without modifying the environment: >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' ...
[ "def", "peek_path_info", "(", "environ", ",", "charset", "=", "\"utf-8\"", ",", "errors", "=", "\"replace\"", ")", ":", "segments", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ".", "lstrip", "(", "\"/\"", ")", ".", "split", "(", ...
[ 340, 0 ]
[ 365, 9 ]
python
en
['en', 'en', 'en']
True
extract_path_info
( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, )
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs.
def extract_path_info( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, ): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a W...
[ "def", "extract_path_info", "(", "environ_or_baseurl", ",", "path_or_url", ",", "charset", "=", "\"utf-8\"", ",", "errors", "=", "\"werkzeug.url_quote\"", ",", "collapse_http_schemes", "=", "True", ",", ")", ":", "def", "_normalize_netloc", "(", "scheme", ",", "ne...
[ 368, 0 ]
[ 461, 57 ]
python
en
['en', 'en', 'en']
True
wrap_file
(environ, file, buffer_size=8192)
Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 0.5 If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the application but to pass it through unchanged. If you wan...
Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`.
def wrap_file(environ, file, buffer_size=8192): """Wraps a file. This uses the WSGI server's file wrapper if available or otherwise the generic :class:`FileWrapper`. .. versionadded:: 0.5 If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the applic...
[ "def", "wrap_file", "(", "environ", ",", "file", ",", "buffer_size", "=", "8192", ")", ":", "return", "environ", ".", "get", "(", "\"wsgi.file_wrapper\"", ",", "FileWrapper", ")", "(", "file", ",", "buffer_size", ")" ]
[ 512, 0 ]
[ 528, 75 ]
python
en
['en', 'en', 'en']
True
_make_chunk_iter
(stream, limit, buffer_size)
Helper for the line and chunk iter functions.
Helper for the line and chunk iter functions.
def _make_chunk_iter(stream, limit, buffer_size): """Helper for the line and chunk iter functions.""" if isinstance(stream, (bytes, bytearray, text_type)): raise TypeError( "Passed a string or byte object instead of true iterator or stream." ) if not hasattr(stream, "read"): ...
[ "def", "_make_chunk_iter", "(", "stream", ",", "limit", ",", "buffer_size", ")", ":", "if", "isinstance", "(", "stream", ",", "(", "bytes", ",", "bytearray", ",", "text_type", ")", ")", ":", "raise", "TypeError", "(", "\"Passed a string or byte object instead of...
[ 665, 0 ]
[ 683, 18 ]
python
en
['en', 'en', 'en']
True
make_line_iter
(stream, limit=None, buffer_size=10 * 1024, cap_at_buffer=False)
Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory. This uses the stream's :meth:`~file.read` method internally as opposite to the :meth:`~file.readline` method that is unsafe and can only be used in violation of the ...
Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory.
def make_line_iter(stream, limit=None, buffer_size=10 * 1024, cap_at_buffer=False): """Safely iterates line-based over an input stream. If the input stream is not a :class:`LimitedStream` the `limit` parameter is mandatory. This uses the stream's :meth:`~file.read` method internally as opposite to the...
[ "def", "make_line_iter", "(", "stream", ",", "limit", "=", "None", ",", "buffer_size", "=", "10", "*", "1024", ",", "cap_at_buffer", "=", "False", ")", ":", "_iter", "=", "_make_chunk_iter", "(", "stream", ",", "limit", ",", "buffer_size", ")", "first_item...
[ 686, 0 ]
[ 768, 22 ]
python
en
['en', 'en', 'en']
True
make_chunk_iter
( stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False )
Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers. .. versionadded:: 0.8 .. versionadded:: 0.9 added support for iterators as input stre...
Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline markers.
def make_chunk_iter( stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False ): """Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline ma...
[ "def", "make_chunk_iter", "(", "stream", ",", "separator", ",", "limit", "=", "None", ",", "buffer_size", "=", "10", "*", "1024", ",", "cap_at_buffer", "=", "False", ")", ":", "_iter", "=", "_make_chunk_iter", "(", "stream", ",", "limit", ",", "buffer_size...
[ 771, 0 ]
[ 841, 27 ]
python
en
['en', 'en', 'en']
True
find_undeclared_variables
(ast)
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Env...
Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned.
def find_undeclared_variables(ast): """Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2...
[ "def", "find_undeclared_variables", "(", "ast", ")", ":", "codegen", "=", "TrackingCodeGenerator", "(", "ast", ".", "environment", ")", "codegen", ".", "visit", "(", "ast", ")", "return", "codegen", ".", "undeclared_identifiers" ]
[ 35, 0 ]
[ 56, 41 ]
python
en
['en', 'en', 'en']
True
find_referenced_templates
(ast)
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env...
Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded.
def find_referenced_templates(ast): """Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta ...
[ "def", "find_referenced_templates", "(", "ast", ")", ":", "for", "node", "in", "ast", ".", "find_all", "(", "(", "nodes", ".", "Extends", ",", "nodes", ".", "FromImport", ",", "nodes", ".", "Import", ",", "nodes", ".", "Include", ")", ")", ":", "if", ...
[ 59, 0 ]
[ 105, 22 ]
python
en
['en', 'en', 'en']
True
TrackingCodeGenerator.write
(self, x)
Don't write.
Don't write.
def write(self, x): """Don't write."""
[ "def", "write", "(", "self", ",", "x", ")", ":" ]
[ 24, 4 ]
[ 25, 26 ]
python
en
['en', 'ht', 'en']
False
TrackingCodeGenerator.enter_frame
(self, frame)
Remember all undeclared identifiers.
Remember all undeclared identifiers.
def enter_frame(self, frame): """Remember all undeclared identifiers.""" CodeGenerator.enter_frame(self, frame) for _, (action, param) in iteritems(frame.symbols.loads): if action == 'resolve': self.undeclared_identifiers.add(param)
[ "def", "enter_frame", "(", "self", ",", "frame", ")", ":", "CodeGenerator", ".", "enter_frame", "(", "self", ",", "frame", ")", "for", "_", ",", "(", "action", ",", "param", ")", "in", "iteritems", "(", "frame", ".", "symbols", ".", "loads", ")", ":"...
[ 27, 4 ]
[ 32, 54 ]
python
en
['en', 'en', 'en']
True
PSDraw.begin_document
(self, id=None)
Set up printing of a document. (Write PostScript DSC header.)
Set up printing of a document. (Write PostScript DSC header.)
def begin_document(self, id=None): """Set up printing of a document. (Write PostScript DSC header.)""" # FIXME: incomplete self.fp.write( b"%!PS-Adobe-3.0\n" b"save\n" b"/showpage { } def\n" b"%%EndComments\n" b"%%BeginDocument\n" ...
[ "def", "begin_document", "(", "self", ",", "id", "=", "None", ")", ":", "# FIXME: incomplete", "self", ".", "fp", ".", "write", "(", "b\"%!PS-Adobe-3.0\\n\"", "b\"save\\n\"", "b\"/showpage { } def\\n\"", "b\"%%EndComments\\n\"", "b\"%%BeginDocument\\n\"", ")", "# self.f...
[ 39, 4 ]
[ 53, 25 ]
python
en
['en', 'lb', 'en']
True
PSDraw.end_document
(self)
Ends printing. (Write PostScript DSC footer.)
Ends printing. (Write PostScript DSC footer.)
def end_document(self): """Ends printing. (Write PostScript DSC footer.)""" self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n") if hasattr(self.fp, "flush"): self.fp.flush()
[ "def", "end_document", "(", "self", ")", ":", "self", ".", "fp", ".", "write", "(", "b\"%%EndDocument\\nrestore showpage\\n%%End\\n\"", ")", "if", "hasattr", "(", "self", ".", "fp", ",", "\"flush\"", ")", ":", "self", ".", "fp", ".", "flush", "(", ")" ]
[ 55, 4 ]
[ 59, 27 ]
python
en
['en', 'en', 'en']
True
PSDraw.setfont
(self, font, size)
Selects which font to use. :param font: A PostScript font name :param size: Size in points.
Selects which font to use.
def setfont(self, font, size): """ Selects which font to use. :param font: A PostScript font name :param size: Size in points. """ font = bytes(font, "UTF-8") if font not in self.isofont: # reencode font self.fp.write(b"/PSDraw-%s ISOLatin...
[ "def", "setfont", "(", "self", ",", "font", ",", "size", ")", ":", "font", "=", "bytes", "(", "font", ",", "\"UTF-8\"", ")", "if", "font", "not", "in", "self", ".", "isofont", ":", "# reencode font", "self", ".", "fp", ".", "write", "(", "b\"/PSDraw-...
[ 61, 4 ]
[ 74, 62 ]
python
en
['en', 'error', 'th']
False
PSDraw.line
(self, xy0, xy1)
Draws a line between the two points. Coordinates are given in PostScript point coordinates (72 points per inch, (0, 0) is the lower left corner of the page).
Draws a line between the two points. Coordinates are given in PostScript point coordinates (72 points per inch, (0, 0) is the lower left corner of the page).
def line(self, xy0, xy1): """ Draws a line between the two points. Coordinates are given in PostScript point coordinates (72 points per inch, (0, 0) is the lower left corner of the page). """ self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))
[ "def", "line", "(", "self", ",", "xy0", ",", "xy1", ")", ":", "self", ".", "fp", ".", "write", "(", "b\"%d %d %d %d Vl\\n\"", "%", "(", "*", "xy0", ",", "*", "xy1", ")", ")" ]
[ 76, 4 ]
[ 82, 57 ]
python
en
['en', 'error', 'th']
False
PSDraw.rectangle
(self, box)
Draws a rectangle. :param box: A 4-tuple of integers whose order and function is currently undocumented. Hint: the tuple is passed into this format string: .. code-block:: python %d %d M %d %d 0 Vr\n
Draws a rectangle.
def rectangle(self, box): """ Draws a rectangle. :param box: A 4-tuple of integers whose order and function is currently undocumented. Hint: the tuple is passed into this format string: .. code-block:: python ...
[ "def", "rectangle", "(", "self", ",", "box", ")", ":", "self", ".", "fp", ".", "write", "(", "b\"%d %d M %d %d 0 Vr\\n\"", "%", "box", ")" ]
[ 84, 4 ]
[ 97, 52 ]
python
en
['en', 'error', 'th']
False
PSDraw.text
(self, xy, text)
Draws text at the given position. You must use :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
Draws text at the given position. You must use :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
def text(self, xy, text): """ Draws text at the given position. You must use :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method. """ text = bytes(text, "UTF-8") text = b"\\(".join(text.split(b"(")) text = b"\\)".join(text.split(b")")) xy += (...
[ "def", "text", "(", "self", ",", "xy", ",", "text", ")", ":", "text", "=", "bytes", "(", "text", ",", "\"UTF-8\"", ")", "text", "=", "b\"\\\\(\"", ".", "join", "(", "text", ".", "split", "(", "b\"(\"", ")", ")", "text", "=", "b\"\\\\)\"", ".", "j...
[ 99, 4 ]
[ 108, 47 ]
python
en
['en', 'error', 'th']
False
PSDraw.image
(self, box, im, dpi=None)
Draw a PIL image, centered in the given box.
Draw a PIL image, centered in the given box.
def image(self, box, im, dpi=None): """Draw a PIL image, centered in the given box.""" # default resolution depends on mode if not dpi: if im.mode == "1": dpi = 200 # fax else: dpi = 100 # greyscale # image size (on paper) ...
[ "def", "image", "(", "self", ",", "box", ",", "im", ",", "dpi", "=", "None", ")", ":", "# default resolution depends on mode", "if", "not", "dpi", ":", "if", "im", ".", "mode", "==", "\"1\"", ":", "dpi", "=", "200", "# fax", "else", ":", "dpi", "=", ...
[ 110, 4 ]
[ 139, 38 ]
python
en
['en', 'en', 'en']
True
_implementation
()
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably...
Return a dict with the Python implementation and version.
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and Py...
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", ...
[ 31, 0 ]
[ 61, 70 ]
python
en
['en', 'en', 'en']
True
info
()
Generate information for a bug report.
Generate information for a bug report.
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } im...
[ "def", "info", "(", ")", ":", "try", ":", "platform_info", "=", "{", "'system'", ":", "platform", ".", "system", "(", ")", ",", "'release'", ":", "platform", ".", "release", "(", ")", ",", "}", "except", "IOError", ":", "platform_info", "=", "{", "'s...
[ 64, 0 ]
[ 122, 5 ]
python
en
['en', 'en', 'en']
True
main
()
Pretty-print the bug information as JSON.
Pretty-print the bug information as JSON.
def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2))
[ "def", "main", "(", ")", ":", "print", "(", "json", ".", "dumps", "(", "info", "(", ")", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", ")" ]
[ 125, 0 ]
[ 127, 55 ]
python
en
['en', 'en', 'en']
True
get_dataset_filter
(expr: Expression, expected_to_file_map: dict)
Given an Iceberg Expression and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset filter using the file column names. Recursively iterate through the expressions to convert each portion one predicate at a time Parameters ---------- expr : iceberg.api...
Given an Iceberg Expression and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset filter using the file column names. Recursively iterate through the expressions to convert each portion one predicate at a time
def get_dataset_filter(expr: Expression, expected_to_file_map: dict) -> ds.Expression: """ Given an Iceberg Expression and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset filter using the file column names. Recursively iterate through the expressions to conv...
[ "def", "get_dataset_filter", "(", "expr", ":", "Expression", ",", "expected_to_file_map", ":", "dict", ")", "->", "ds", ".", "Expression", ":", "if", "expr", "is", "None", ":", "return", "None", "if", "isinstance", "(", "expr", ",", "Predicate", ")", ":", ...
[ 22, 0 ]
[ 58, 69 ]
python
en
['en', 'error', 'th']
False
predicate
(pred: Predicate, field_map: dict)
Given an Iceberg Predicate and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset expression using the file column names. Parameters ---------- pred : iceberg.api.expressions.Predicate An Iceberg Predicate to be converted field_map : dict ...
Given an Iceberg Predicate and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset expression using the file column names.
def predicate(pred: Predicate, field_map: dict) -> ds.Expression: # noqa: ignore=C901 """ Given an Iceberg Predicate and a mapping of names in the iceberg schema to the file schema, convert to an equivalent dataset expression using the file column names. Parameters ---------- pred : iceberg.ap...
[ "def", "predicate", "(", "pred", ":", "Predicate", ",", "field_map", ":", "dict", ")", "->", "ds", ".", "Expression", ":", "# noqa: ignore=C901", "# get column name in the file schema so we can apply the predicate", "col_name", "=", "field_map", ".", "get", "(", "pred...
[ 61, 0 ]
[ 105, 54 ]
python
en
['en', 'error', 'th']
False
and_
(left: ds.Expression, right: ds.Expression)
Given a left and right expression combined them using the `AND` logical operator Parameters ---------- left : pyarrow._dataset.Expression A Dataset `Expression` to logically `AND` right : pyarrow._dataset.Expression A Dataset `Expression` to logically `AND` Returns ------- ...
Given a left and right expression combined them using the `AND` logical operator
def and_(left: ds.Expression, right: ds.Expression) -> ds.Expression: """ Given a left and right expression combined them using the `AND` logical operator Parameters ---------- left : pyarrow._dataset.Expression A Dataset `Expression` to logically `AND` right : pyarrow._dataset.Expressi...
[ "def", "and_", "(", "left", ":", "ds", ".", "Expression", ",", "right", ":", "ds", ".", "Expression", ")", "->", "ds", ".", "Expression", ":", "return", "left", "&", "right" ]
[ 108, 0 ]
[ 123, 23 ]
python
en
['en', 'error', 'th']
False
or_
(left: ds.Expression, right: ds.Expression)
Given a left and right expression combined them using the `OR` logical operator Parameters ---------- left : pyarrow._dataset.Expression A Dataset `Expression` to logically `OR` right : pyarrow._dataset.Expression A Dataset `Expression` to logically `OR` Returns ------- ...
Given a left and right expression combined them using the `OR` logical operator
def or_(left: ds.Expression, right: ds.Expression) -> ds.Expression: """ Given a left and right expression combined them using the `OR` logical operator Parameters ---------- left : pyarrow._dataset.Expression A Dataset `Expression` to logically `OR` right : pyarrow._dataset.Expression ...
[ "def", "or_", "(", "left", ":", "ds", ".", "Expression", ",", "right", ":", "ds", ".", "Expression", ")", "->", "ds", ".", "Expression", ":", "return", "left", "|", "right" ]
[ 126, 0 ]
[ 141, 23 ]
python
en
['en', 'error', 'th']
False
not_
(child: ds.Expression)
Given a child expression create the logical negation Parameters ---------- child : pyarrow._dataset.Expression A Dataset `Expression` to logically `OR` Returns ------- pyarrow._dataset.Expression The negation of the input `Expression`
Given a child expression create the logical negation
def not_(child: ds.Expression) -> ds.Expression: """ Given a child expression create the logical negation Parameters ---------- child : pyarrow._dataset.Expression A Dataset `Expression` to logically `OR` Returns ------- pyarrow._dataset.Expression The negation of the in...
[ "def", "not_", "(", "child", ":", "ds", ".", "Expression", ")", "->", "ds", ".", "Expression", ":", "return", "~", "child" ]
[ 144, 0 ]
[ 157, 17 ]
python
en
['en', 'error', 'th']
False
build_model
(output_dir, hub_handle)
Compiles keras model for image classification.
Compiles keras model for image classification.
def build_model(output_dir, hub_handle): """Compiles keras model for image classification.""" model = models.Sequential([ hub.KerasLayer(hub_handle, trainable=False), layers.Dropout(rate=DROPOUT), layers.Dense( NCLASSES, activation='softmax', kernel_re...
[ "def", "build_model", "(", "output_dir", ",", "hub_handle", ")", ":", "model", "=", "models", ".", "Sequential", "(", "[", "hub", ".", "KerasLayer", "(", "hub_handle", ",", "trainable", "=", "False", ")", ",", "layers", ".", "Dropout", "(", "rate", "=", ...
[ 17, 0 ]
[ 32, 16 ]
python
en
['es', 'en', 'en']
True
train_and_evaluate
( model, num_epochs, steps_per_epoch, train_data, eval_data, output_dir)
Compiles keras model and loads data into it for training.
Compiles keras model and loads data into it for training.
def train_and_evaluate( model, num_epochs, steps_per_epoch, train_data, eval_data, output_dir): """Compiles keras model and loads data into it for training.""" model_callbacks = [] if output_dir: tensorboard_callback = callbacks.TensorBoard(log_dir=output_dir) model_callbacks = [tensorbo...
[ "def", "train_and_evaluate", "(", "model", ",", "num_epochs", ",", "steps_per_epoch", ",", "train_data", ",", "eval_data", ",", "output_dir", ")", ":", "model_callbacks", "=", "[", "]", "if", "output_dir", ":", "tensorboard_callback", "=", "callbacks", ".", "Ten...
[ 35, 0 ]
[ 55, 18 ]
python
en
['en', 'en', 'en']
True
get_keyring_auth
(url: Optional[str], username: Optional[str])
Return the tuple auth for a given url from keyring.
Return the tuple auth for a given url from keyring.
def get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]: """Return the tuple auth for a given url from keyring.""" global keyring if not url or not keyring: return None try: try: get_credential = keyring.get_credential except Attribute...
[ "def", "get_keyring_auth", "(", "url", ":", "Optional", "[", "str", "]", ",", "username", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "AuthInfo", "]", ":", "global", "keyring", "if", "not", "url", "or", "not", "keyring", ":", "return"...
[ 39, 0 ]
[ 69, 15 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_index_url
(self, url: str)
Return the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentia...
Return the original index URL matching the requested URL.
def _get_index_url(self, url: str) -> Optional[str]: """Return the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password ...
[ "def", "_get_index_url", "(", "self", ",", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "if", "not", "url", "or", "not", "self", ".", "index_urls", ":", "return", "None", "for", "u", "in", "self", ".", "index_urls", ":", "prefix", ...
[ 86, 4 ]
[ 106, 19 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_new_credentials
( self, original_url: str, allow_netrc: bool = True, allow_keyring: bool = False, )
Find and return credentials for the specified URL.
Find and return credentials for the specified URL.
def _get_new_credentials( self, original_url: str, allow_netrc: bool = True, allow_keyring: bool = False, ) -> AuthInfo: """Find and return credentials for the specified URL.""" # Split the credentials and netloc from the url. url, netloc, url_user_password = ...
[ "def", "_get_new_credentials", "(", "self", ",", "original_url", ":", "str", ",", "allow_netrc", ":", "bool", "=", "True", ",", "allow_keyring", ":", "bool", "=", "False", ",", ")", "->", "AuthInfo", ":", "# Split the credentials and netloc from the url.", "url", ...
[ 108, 4 ]
[ 162, 33 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_url_and_credentials
( self, original_url: str )
Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different ...
Return the credentials to use for the provided URL.
def _get_url_and_credentials( self, original_url: str ) -> Tuple[str, Optional[str], Optional[str]]: """Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, usernam...
[ "def", "_get_url_and_credentials", "(", "self", ",", "original_url", ":", "str", ")", "->", "Tuple", "[", "str", ",", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", "]", ":", "url", ",", "netloc", ",", "_", "=", "split_auth_netloc_from_ur...
[ 164, 4 ]
[ 203, 38 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth.warn_on_401
(self, resp: Response, **kwargs: Any)
Response callback to warn about incorrect credentials.
Response callback to warn about incorrect credentials.
def warn_on_401(self, resp: Response, **kwargs: Any) -> None: """Response callback to warn about incorrect credentials.""" if resp.status_code == 401: logger.warning( "401 Error, Credentials not correct for %s", resp.request.url, )
[ "def", "warn_on_401", "(", "self", ",", "resp", ":", "Response", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "resp", ".", "status_code", "==", "401", ":", "logger", ".", "warning", "(", "\"401 Error, Credentials not correct for %s\"", ...
[ 294, 4 ]
[ 300, 13 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth.save_credentials
(self, resp: Response, **kwargs: Any)
Response callback to save credentials on success.
Response callback to save credentials on success.
def save_credentials(self, resp: Response, **kwargs: Any) -> None: """Response callback to save credentials on success.""" assert keyring is not None, "should never reach here without keyring" if not keyring: return creds = self._credentials_to_save self._credentials...
[ "def", "save_credentials", "(", "self", ",", "resp", ":", "Response", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "assert", "keyring", "is", "not", "None", ",", "\"should never reach here without keyring\"", "if", "not", "keyring", ":", "ret...
[ 302, 4 ]
[ 315, 62 ]
python
en
['en', 'en', 'en']
True
TimeMixIn.asDateTime
(self)
Create :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object
Create :py:class:`datetime.datetime` object from a |ASN.1| object.
def asDateTime(self): """Create :py:class:`datetime.datetime` object from a |ASN.1| object. Returns ------- : new instance of :py:class:`datetime.datetime` object """ text = str(self) if text.endswith('Z'): tzinfo = TimeMixIn.UTC ...
[ "def", "asDateTime", "(", "self", ")", ":", "text", "=", "str", "(", "self", ")", "if", "text", ".", "endswith", "(", "'Z'", ")", ":", "tzinfo", "=", "TimeMixIn", ".", "UTC", "text", "=", "text", "[", ":", "-", "1", "]", "elif", "'-'", "in", "t...
[ 61, 4 ]
[ 125, 56 ]
python
en
['en', 'en', 'en']
True
TimeMixIn.fromDateTime
(cls, dt)
Create |ASN.1| object from a :py:class:`datetime.datetime` object. Parameters ---------- dt: :py:class:`datetime.datetime` object The `datetime.datetime` object to initialize the |ASN.1| object from Returns ------- : new instance of |...
Create |ASN.1| object from a :py:class:`datetime.datetime` object.
def fromDateTime(cls, dt): """Create |ASN.1| object from a :py:class:`datetime.datetime` object. Parameters ---------- dt: :py:class:`datetime.datetime` object The `datetime.datetime` object to initialize the |ASN.1| object from Returns ------- ...
[ "def", "fromDateTime", "(", "cls", ",", "dt", ")", ":", "text", "=", "dt", ".", "strftime", "(", "cls", ".", "_yearsDigits", "==", "4", "and", "'%Y%m%d%H%M%S'", "or", "'%y%m%d%H%M%S'", ")", "if", "cls", ".", "_hasSubsecond", ":", "text", "+=", "'.%d'", ...
[ 128, 4 ]
[ 156, 24 ]
python
en
['en', 'en', 'en']
True
ordinal
(value)
Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer.
Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer.
def ordinal(value): """ Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except (TypeError, ValueError): return value if value % 100 in (11, 12, 13): # Translators: Ordinal forma...
[ "def", "ordinal", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "value", "if", "value", "%", "100", "in", "(", "11", ",", "12", ",", "13", ")", ":", ...
[ 18, 0 ]
[ 55, 27 ]
python
en
['en', 'error', 'th']
False
intcomma
(value, use_l10n=True)
Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
def intcomma(value, use_l10n=True): """ Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ if use_l10n: try: if not isinstance(value, (float, Decimal)): value = int(value) ...
[ "def", "intcomma", "(", "value", ",", "use_l10n", "=", "True", ")", ":", "if", "use_l10n", ":", "try", ":", "if", "not", "isinstance", "(", "value", ",", "(", "float", ",", "Decimal", ")", ")", ":", "value", "=", "int", "(", "value", ")", "except",...
[ 59, 0 ]
[ 77, 38 ]
python
en
['en', 'error', 'th']
False
intword
(value)
Convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
Convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
def intword(value): """ Convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ try: value = int(value) except (TypeError, V...
[ "def", "intword", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "value", "abs_value", "=", "abs", "(", "value", ")", "if", "abs_value", "<", "1000000", "...
[ 97, 0 ]
[ 120, 16 ]
python
en
['en', 'error', 'th']
False
apnumber
(value)
For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style.
For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style.
def apnumber(value): """ For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 < value < 10: return value return (_('one'...
[ "def", "apnumber", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "value", "if", "not", "0", "<", "value", "<", "10", ":", "return", "value", "return", ...
[ 124, 0 ]
[ 136, 67 ]
python
en
['en', 'error', 'th']
False
naturalday
(value, arg=None)
For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to settings.DATE_FORMAT.
For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to settings.DATE_FORMAT.
def naturalday(value, arg=None): """ For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to settings.DATE_FORMAT. """ tzinfo = getattr(value, 'tzinfo', None) try: value = date(value.y...
[ "def", "naturalday", "(", "value", ",", "arg", "=", "None", ")", ":", "tzinfo", "=", "getattr", "(", "value", ",", "'tzinfo'", ",", "None", ")", "try", ":", "value", "=", "date", "(", "value", ".", "year", ",", "value", ".", "month", ",", "value", ...
[ 142, 0 ]
[ 162, 42 ]
python
en
['en', 'error', 'th']
False
naturaltime
(value)
For date and time values show how many seconds, minutes, or hours ago compared to current timestamp return representing string.
For date and time values show how many seconds, minutes, or hours ago compared to current timestamp return representing string.
def naturaltime(value): """ For date and time values show how many seconds, minutes, or hours ago compared to current timestamp return representing string. """ return NaturalTimeFormatter.string_for(value)
[ "def", "naturaltime", "(", "value", ")", ":", "return", "NaturalTimeFormatter", ".", "string_for", "(", "value", ")" ]
[ 168, 0 ]
[ 173, 49 ]
python
en
['en', 'error', 'th']
False
gaussian_kernel
(d, scale=0.05, use_mp=False, return_mp=False)
Gaussian kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
Gaussian kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
def gaussian_kernel(d, scale=0.05, use_mp=False, return_mp=False): """ Gaussian kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kerne...
[ "def", "gaussian_kernel", "(", "d", ",", "scale", "=", "0.05", ",", "use_mp", "=", "False", ",", "return_mp", "=", "False", ")", ":", "if", "not", "use_mp", ":", "if", "return_mp", ":", "print", "(", "\"To return an mpf object, set use_mp=True, returning numpy o...
[ 11, 0 ]
[ 51, 41 ]
python
en
['en', 'error', 'th']
False
logistic_kernel
(d, scale=0.05, use_mp=False, return_mp=False)
logistic kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
logistic kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
def logistic_kernel(d, scale=0.05, use_mp=False, return_mp=False): """ logistic kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kerne...
[ "def", "logistic_kernel", "(", "d", ",", "scale", "=", "0.05", ",", "use_mp", "=", "False", ",", "return_mp", "=", "False", ")", ":", "if", "not", "use_mp", ":", "if", "return_mp", ":", "print", "(", "\"To return an mpf object, set use_mp=True, returning numpy o...
[ 57, 0 ]
[ 97, 41 ]
python
en
['en', 'error', 'th']
False
sigmoid_kernel
(d, scale=0.05, use_mp=False, return_mp=False)
Sigmoid kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
Sigmoid kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel evaluated at d and scale
def sigmoid_kernel(d, scale=0.05, use_mp=False, return_mp=False): """ Sigmoid kernel with scale :param d: the input of the kernel, might be numpy array but not mp matrix :param scale: the scale :param use_mp: if True use mpmath :param return_mp: if True return mpf object :return: the kernel ...
[ "def", "sigmoid_kernel", "(", "d", ",", "scale", "=", "0.05", ",", "use_mp", "=", "False", ",", "return_mp", "=", "False", ")", ":", "if", "not", "use_mp", ":", "if", "return_mp", ":", "print", "(", "\"To return an mpf object, set use_mp=True, returning numpy ob...
[ 101, 0 ]
[ 141, 41 ]
python
en
['en', 'error', 'th']
False
mp_mean
(arr)
Calculates the mean of the array of mpf values :param arr: array of mp.mpf floats :return: the mean as mpf
Calculates the mean of the array of mpf values :param arr: array of mp.mpf floats :return: the mean as mpf
def mp_mean(arr): """ Calculates the mean of the array of mpf values :param arr: array of mp.mpf floats :return: the mean as mpf """ arr = arr.ravel() N = arr.size res = mp.mpf(0.0) for a in arr: res = res + a return res/N
[ "def", "mp_mean", "(", "arr", ")", ":", "arr", "=", "arr", ".", "ravel", "(", ")", "N", "=", "arr", ".", "size", "res", "=", "mp", ".", "mpf", "(", "0.0", ")", "for", "a", "in", "arr", ":", "res", "=", "res", "+", "a", "return", "res", "/",...
[ 146, 0 ]
[ 159, 16 ]
python
en
['en', 'error', 'th']
False
mp_std
(arr, ddof=0)
Calculates the standard deviation of the array of mpf values :param arr: array of mp.mpf floats :param ddof: Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. (np.std convention) :return: the mean as mpf...
Calculates the standard deviation of the array of mpf values :param arr: array of mp.mpf floats :param ddof: Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. (np.std convention) :return: the mean as mpf...
def mp_std(arr, ddof=0): """ Calculates the standard deviation of the array of mpf values :param arr: array of mp.mpf floats :param ddof: Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. (np.std conventi...
[ "def", "mp_std", "(", "arr", ",", "ddof", "=", "0", ")", ":", "arr", "=", "arr", ".", "ravel", "(", ")", "N", "=", "arr", ".", "size", "# get the mean", "mean", "=", "mp_mean", "(", "arr", ")", "res", "=", "mp", ".", "mpf", "(", "0.0", ")", "...
[ 163, 0 ]
[ 181, 36 ]
python
en
['en', 'error', 'th']
False
format_command_result
( command_args, # type: List[str] command_output, # type: str )
Format command information for logging.
Format command information for logging.
def format_command_result( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """Format command information for logging.""" command_desc = format_command_args(command_args) text = f'Command arguments: {command_desc}\n' if not command_output: text +...
[ "def", "format_command_result", "(", "command_args", ",", "# type: List[str]", "command_output", ",", "# type: str", ")", ":", "# type: (...) -> str", "command_desc", "=", "format_command_args", "(", "command_args", ")", "text", "=", "f'Command arguments: {command_desc}\\n'",...
[ 15, 0 ]
[ 33, 15 ]
python
en
['en', 'da', 'en']
True
get_legacy_build_wheel_path
( names, # type: List[str] temp_dir, # type: str name, # type: str command_args, # type: List[str] command_output, # type: str )
Return the path to the wheel in the temporary build directory.
Return the path to the wheel in the temporary build directory.
def get_legacy_build_wheel_path( names, # type: List[str] temp_dir, # type: str name, # type: str command_args, # type: List[str] command_output, # type: str ): # type: (...) -> Optional[str] """Return the path to the wheel in the temporary build directory.""" # Sort for determinism...
[ "def", "get_legacy_build_wheel_path", "(", "names", ",", "# type: List[str]", "temp_dir", ",", "# type: str", "name", ",", "# type: str", "command_args", ",", "# type: List[str]", "command_output", ",", "# type: str", ")", ":", "# type: (...) -> Optional[str]", "# Sort for ...
[ 36, 0 ]
[ 63, 43 ]
python
en
['en', 'en', 'en']
True
build_wheel_legacy
( name, # type: str setup_py_path, # type: str source_dir, # type: str global_options, # type: List[str] build_options, # type: List[str] tempd, # type: str )
Build one unpacked package using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None.
Build one unpacked package using the "legacy" build process.
def build_wheel_legacy( name, # type: str setup_py_path, # type: str source_dir, # type: str global_options, # type: List[str] build_options, # type: List[str] tempd, # type: str ): # type: (...) -> Optional[str] """Build one unpacked package using the "legacy" build process. ...
[ "def", "build_wheel_legacy", "(", "name", ",", "# type: str", "setup_py_path", ",", "# type: str", "source_dir", ",", "# type: str", "global_options", ",", "# type: List[str]", "build_options", ",", "# type: List[str]", "tempd", ",", "# type: str", ")", ":", "# type: (....
[ 66, 0 ]
[ 109, 25 ]
python
en
['en', 'en', 'en']
True
to_native_string
(string, encoding='ascii')
Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise.
Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise.
def to_native_string(string, encoding='ascii'): """Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, builtin_str): out = stri...
[ "def", "to_native_string", "(", "string", ",", "encoding", "=", "'ascii'", ")", ":", "if", "isinstance", "(", "string", ",", "builtin_str", ")", ":", "out", "=", "string", "else", ":", "if", "is_py2", ":", "out", "=", "string", ".", "encode", "(", "enc...
[ 13, 0 ]
[ 26, 14 ]
python
en
['en', 'en', 'en']
True
unicode_is_ascii
(u_string)
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool
Determine if unicode string only contains ASCII characters.
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return Tru...
[ "def", "unicode_is_ascii", "(", "u_string", ")", ":", "assert", "isinstance", "(", "u_string", ",", "str", ")", "try", ":", "u_string", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
[ 29, 0 ]
[ 41, 20 ]
python
en
['en', 'en', 'en']
True
precision_at_k
(ranking, k)
Score is precision @ k Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :param k: length of ranking :type k: int :return: Precision @ k :rtype: float
Score is precision @ k Relevance is binary (nonzero is relevant).
def precision_at_k(ranking, k): """ Score is precision @ k Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :param k: length of ranking :type k: int :return: Precis...
[ "def", "precision_at_k", "(", "ranking", ",", "k", ")", ":", "assert", "k", ">=", "1", "ranking", "=", "np", ".", "asarray", "(", "ranking", ")", "[", ":", "k", "]", "!=", "0", "if", "ranking", ".", "size", "!=", "k", ":", "raise", "ValueError", ...
[ 15, 0 ]
[ 35, 27 ]
python
en
['en', 'error', 'th']
False
average_precision
(ranking)
Score is average precision (area under PR curve). Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :return: Average precision :rtype: float
Score is average precision (area under PR curve). Relevance is binary (nonzero is relevant).
def average_precision(ranking): """ Score is average precision (area under PR curve). Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :return: Average precision :rtype: flo...
[ "def", "average_precision", "(", "ranking", ")", ":", "ranking", "=", "np", ".", "asarray", "(", "ranking", ")", "!=", "0", "out", "=", "[", "precision_at_k", "(", "ranking", ",", "k", "+", "1", ")", "for", "k", "in", "range", "(", "ranking", ".", ...
[ 38, 0 ]
[ 54, 23 ]
python
en
['en', 'error', 'th']
False
mean_average_precision
(ranking)
Score is mean average precision. Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :return: Mean average precision :rtype: float
Score is mean average precision. Relevance is binary (nonzero is relevant).
def mean_average_precision(ranking): """ Score is mean average precision. Relevance is binary (nonzero is relevant). :param ranking: Relevance scores (list or numpy) in rank order (first element is the first item) :type ranking: list, np.array :return: Mean average precision :rtype: float ...
[ "def", "mean_average_precision", "(", "ranking", ")", ":", "return", "np", ".", "mean", "(", "[", "average_precision", "(", "r", ")", "for", "r", "in", "ranking", "]", ")" ]
[ 57, 0 ]
[ 68, 59 ]
python
en
['en', 'error', 'th']
False
ndcg_at_k
(ranking)
Score is normalized discounted cumulative gain (ndcg). Relevance is positive real values. Can use binary as the previous methods. :param ranking: ranking to evaluate in dcg format [0, 0, 1], where 1 is correct info :type ranking: list :return: Normalized discounted cumulative gain :rtype: fl...
Score is normalized discounted cumulative gain (ndcg). Relevance is positive real values. Can use binary as the previous methods.
def ndcg_at_k(ranking): """ Score is normalized discounted cumulative gain (ndcg). Relevance is positive real values. Can use binary as the previous methods. :param ranking: ranking to evaluate in dcg format [0, 0, 1], where 1 is correct info :type ranking: list :return: Normalized discounted...
[ "def", "ndcg_at_k", "(", "ranking", ")", ":", "ranking", "=", "np", ".", "asfarray", "(", "ranking", ")", "r_ideal", "=", "np", ".", "asfarray", "(", "sorted", "(", "ranking", ",", "reverse", "=", "True", ")", ")", "dcg_ideal", "=", "r_ideal", "[", "...
[ 71, 0 ]
[ 89, 34 ]
python
en
['en', 'error', 'th']
False
unet_weight_map
(batch, wo=10, sigma=5, max_background_ratio=0, set_contours_to_zero=False, dtype=np.float32)
Implementation of Unet weight map as in Ronneberger, O., Fischer, P., & Brox, T. (2015, October). U-net: Convolutional networks for biomedical image segmentation. Parameters ---------- batch : type ND array of shape (batch, Y, X, nchan) of labeld images if nchan>1 function is applied separately on each channe...
Implementation of Unet weight map as in Ronneberger, O., Fischer, P., & Brox, T. (2015, October). U-net: Convolutional networks for biomedical image segmentation.
def unet_weight_map(batch, wo=10, sigma=5, max_background_ratio=0, set_contours_to_zero=False, dtype=np.float32): """Implementation of Unet weight map as in Ronneberger, O., Fischer, P., & Brox, T. (2015, October). U-net: Convolutional networks for biomedical image segmentation. Parameters ---------- batch : type...
[ "def", "unet_weight_map", "(", "batch", ",", "wo", "=", "10", ",", "sigma", "=", "5", ",", "max_background_ratio", "=", "0", ",", "set_contours_to_zero", "=", "False", ",", "dtype", "=", "np", ".", "float32", ")", ":", "if", "batch", ".", "shape", "[",...
[ 47, 0 ]
[ 95, 11 ]
python
en
['en', 'en', 'en']
True
multilabel_edt
(label_img, closed_end=True)
multilabel edt requires edt package. along y-axis (1st axis) : out-of-bound is considered as foreground of upper and lower ends if closed_end=False else only for lower end
multilabel edt requires edt package. along y-axis (1st axis) : out-of-bound is considered as foreground of upper and lower ends if closed_end=False else only for lower end
def multilabel_edt(label_img, closed_end=True): ''' multilabel edt requires edt package. along y-axis (1st axis) : out-of-bound is considered as foreground of upper and lower ends if closed_end=False else only for lower end ''' y_up = 1 if closed_end else 0 if len(label_img.shape)==3: ...
[ "def", "multilabel_edt", "(", "label_img", ",", "closed_end", "=", "True", ")", ":", "y_up", "=", "1", "if", "closed_end", "else", "0", "if", "len", "(", "label_img", ".", "shape", ")", "==", "3", ":", "squeeze", "=", "True", "label_img", "=", "np", ...
[ 115, 0 ]
[ 129, 20 ]
python
en
['en', 'error', 'th']
False
binary_erode_labelwise
(label_img)
in-place erosion of square 8-connectivity, label by label, with border value = 1
in-place erosion of square 8-connectivity, label by label, with border value = 1
def binary_erode_labelwise(label_img): ''' in-place erosion of square 8-connectivity, label by label, with border value = 1 ''' # todo: set structure as argument, but adapt region dilatation to this parameter regDilSize = 1 regions = find_objects(label_img) shape = label_img.shape fo...
[ "def", "binary_erode_labelwise", "(", "label_img", ")", ":", "# todo: set structure as argument, but adapt region dilatation to this parameter", "regDilSize", "=", "1", "regions", "=", "find_objects", "(", "label_img", ")", "shape", "=", "label_img", ".", "shape", "for", ...
[ 134, 0 ]
[ 151, 69 ]
python
en
['en', 'error', 'th']
False
random_rotate90_fun
(axes=(0, 1), other_fun=None)
Augmentation function that applied randomly a 90° rotation with a probability of 50% Parameters ---------- axes : type defines the rotation plane. If input is a batch, set (1, 2) other_fun : type other function applied to the input Returns ------- type a function th...
Augmentation function that applied randomly a 90° rotation with a probability of 50%
def random_rotate90_fun(axes=(0, 1), other_fun=None): """Augmentation function that applied randomly a 90° rotation with a probability of 50% Parameters ---------- axes : type defines the rotation plane. If input is a batch, set (1, 2) other_fun : type other function applied to the...
[ "def", "random_rotate90_fun", "(", "axes", "=", "(", "0", ",", "1", ")", ",", "other_fun", "=", "None", ")", ":", "def", "func", "(", "img", ")", ":", "if", "not", "not", "getrandbits", "(", "1", ")", ":", "img", "=", "np", ".", "rot90", "(", "...
[ 213, 0 ]
[ 236, 15 ]
python
en
['en', 'en', 'en']
True
random_scaling
(img, center=None, scale=None, alpha_range=[-0.3, 0.17], beta_range=0.07)
Scales the image by this formlua: I' = ( I - ( μ + ( β * std ) ) ) / (std * 10**α). α, β randomly chosen Parameters ---------- img : numpy array center : float default center value, if center, mean is computed on the array scale : float default standard deviation value, if none, std...
Scales the image by this formlua: I' = ( I - ( μ + ( β * std ) ) ) / (std * 10**α). α, β randomly chosen
def random_scaling(img, center=None, scale=None, alpha_range=[-0.3, 0.17], beta_range=0.07): """Scales the image by this formlua: I' = ( I - ( μ + ( β * std ) ) ) / (std * 10**α). α, β randomly chosen Parameters ---------- img : numpy array center : float default center value, if center, me...
[ "def", "random_scaling", "(", "img", ",", "center", "=", "None", ",", "scale", "=", "None", ",", "alpha_range", "=", "[", "-", "0.3", ",", "0.17", "]", ",", "beta_range", "=", "0.07", ")", ":", "if", "center", "is", "None", ":", "center", "=", "img...
[ 264, 0 ]
[ 295, 34 ]
python
en
['en', 'ja', 'en']
True
histogram_voodoo
(image, num_control_points=5, intensity=0.5, target_points = None, return_mapping = False)
Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It performs an elastic deformation on the image histogram to simulate changes in illumination
Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It performs an elastic deformation on the image histogram to simulate changes in illumination
def histogram_voodoo(image, num_control_points=5, intensity=0.5, target_points = None, return_mapping = False): ''' Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It performs an elastic deformation on the image histogram to simulate changes in illumination ''' ...
[ "def", "histogram_voodoo", "(", "image", ",", "num_control_points", "=", "5", ",", "intensity", "=", "0.5", ",", "target_points", "=", "None", ",", "return_mapping", "=", "False", ")", ":", "if", "target_points", "is", "not", "None", "and", "len", "(", "ta...
[ 374, 0 ]
[ 400, 23 ]
python
en
['en', 'error', 'th']
False
illumination_voodoo
(image, num_control_points=5, intensity=0.8, target_points = None)
Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It simulates a variation in illumination along the length of the chamber
Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It simulates a variation in illumination along the length of the chamber
def illumination_voodoo(image, num_control_points=5, intensity=0.8, target_points = None): ''' Adapted from delta software: https://gitlab.com/dunloplab/delta/blob/master/data.py It simulates a variation in illumination along the length of the chamber ''' if intensity>=1 or intensity<=0: rai...
[ "def", "illumination_voodoo", "(", "image", ",", "num_control_points", "=", "5", ",", "intensity", "=", "0.8", ",", "target_points", "=", "None", ")", ":", "if", "intensity", ">=", "1", "or", "intensity", "<=", "0", ":", "raise", "ValueError", "(", "\"Inte...
[ 413, 0 ]
[ 436, 19 ]
python
en
['en', 'error', 'th']
False
_detect_gce_environment
()
Determine if the current environment is Compute Engine. Returns: Boolean indicating whether or not the current environment is Google Compute Engine.
Determine if the current environment is Compute Engine.
def _detect_gce_environment(): """Determine if the current environment is Compute Engine. Returns: Boolean indicating whether or not the current environment is Google Compute Engine. """ # NOTE: The explicit ``timeout`` is a workaround. The underlying # issue is that resolving...
[ "def", "_detect_gce_environment", "(", ")", ":", "# NOTE: The explicit ``timeout`` is a workaround. The underlying", "# issue is that resolving an unknown host on some networks will take", "# 20-30 seconds; making this timeout short fixes the issue, but", "# could lead to false neg...
[ 982, 0 ]
[ 1004, 20 ]
python
en
['en', 'en', 'en']
True
_in_gae_environment
()
Detects if the code is running in the App Engine environment. Returns: True if running in the GAE environment, False otherwise.
Detects if the code is running in the App Engine environment.
def _in_gae_environment(): """Detects if the code is running in the App Engine environment. Returns: True if running in the GAE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL') try: import google...
[ "def", "_in_gae_environment", "(", ")", ":", "if", "SETTINGS", ".", "env_name", "is", "not", "None", ":", "return", "SETTINGS", ".", "env_name", "in", "(", "'GAE_PRODUCTION'", ",", "'GAE_LOCAL'", ")", "try", ":", "import", "google", ".", "appengine", "# noqa...
[ 1007, 0 ]
[ 1029, 16 ]
python
en
['en', 'en', 'en']
True
_in_gce_environment
()
Detect if the code is running in the Compute Engine environment. Returns: True if running in the GCE environment, False otherwise.
Detect if the code is running in the Compute Engine environment.
def _in_gce_environment(): """Detect if the code is running in the Compute Engine environment. Returns: True if running in the GCE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name == 'GCE_PRODUCTION' if NO_GCE_CHECK != 'True' and _detect_...
[ "def", "_in_gce_environment", "(", ")", ":", "if", "SETTINGS", ".", "env_name", "is", "not", "None", ":", "return", "SETTINGS", ".", "env_name", "==", "'GCE_PRODUCTION'", "if", "NO_GCE_CHECK", "!=", "'True'", "and", "_detect_gce_environment", "(", ")", ":", "S...
[ 1032, 0 ]
[ 1044, 16 ]
python
en
['en', 'en', 'en']
True
_save_private_file
(filename, json_contents)
Saves a file with read-write permissions on for the owner. Args: filename: String. Absolute path to file. json_contents: JSON serializable object to be saved.
Saves a file with read-write permissions on for the owner.
def _save_private_file(filename, json_contents): """Saves a file with read-write permissions on for the owner. Args: filename: String. Absolute path to file. json_contents: JSON serializable object to be saved. """ temp_filename = tempfile.mktemp() file_desc = os.open(temp_filename,...
[ "def", "_save_private_file", "(", "filename", ",", "json_contents", ")", ":", "temp_filename", "=", "tempfile", ".", "mktemp", "(", ")", "file_desc", "=", "os", ".", "open", "(", "temp_filename", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", ",", ...
[ 1302, 0 ]
[ 1314, 40 ]
python
en
['en', 'en', 'en']
True
save_to_well_known_file
(credentials, well_known_file=None)
Save the provided GoogleCredentials to the well known file. Args: credentials: the credentials to be saved to the well known file; it should be an instance of GoogleCredentials well_known_file: the name of the file where the credentials are to be saved;...
Save the provided GoogleCredentials to the well known file.
def save_to_well_known_file(credentials, well_known_file=None): """Save the provided GoogleCredentials to the well known file. Args: credentials: the credentials to be saved to the well known file; it should be an instance of GoogleCredentials well_known_file: the name of t...
[ "def", "save_to_well_known_file", "(", "credentials", ",", "well_known_file", "=", "None", ")", ":", "# TODO(orestica): move this method to tools.py", "# once the argparse import gets fixed (it is not present in Python 2.6)", "if", "well_known_file", "is", "None", ":", "well_known_...
[ 1317, 0 ]
[ 1339, 57 ]
python
en
['en', 'en', 'en']
True
_get_well_known_file
()
Get the well known file produced by command 'gcloud auth login'.
Get the well known file produced by command 'gcloud auth login'.
def _get_well_known_file(): """Get the well known file produced by command 'gcloud auth login'.""" # TODO(orestica): Revisit this method once gcloud provides a better way # of pinpointing the exact location of the file. default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR) if default_config_dir i...
[ "def", "_get_well_known_file", "(", ")", ":", "# TODO(orestica): Revisit this method once gcloud provides a better way", "# of pinpointing the exact location of the file.", "default_config_dir", "=", "os", ".", "getenv", "(", "_CLOUDSDK_CONFIG_ENV_VAR", ")", "if", "default_config_dir...
[ 1357, 0 ]
[ 1378, 73 ]
python
en
['en', 'en', 'en']
True
_get_application_default_credential_from_file
(filename)
Build the Application Default Credentials from file.
Build the Application Default Credentials from file.
def _get_application_default_credential_from_file(filename): """Build the Application Default Credentials from file.""" # read the credentials from the file with open(filename) as file_obj: client_credentials = json.load(file_obj) credentials_type = client_credentials.get('type') if credent...
[ "def", "_get_application_default_credential_from_file", "(", "filename", ")", ":", "# read the credentials from the file", "with", "open", "(", "filename", ")", "as", "file_obj", ":", "client_credentials", "=", "json", ".", "load", "(", "file_obj", ")", "credentials_typ...
[ 1381, 0 ]
[ 1415, 31 ]
python
en
['en', 'en', 'en']
True
_require_crypto_or_die
()
Ensure we have a crypto library, or throw CryptoUnavailableError. The oauth2client.crypt module requires either PyCrypto or PyOpenSSL to be available in order to function, but these are optional dependencies.
Ensure we have a crypto library, or throw CryptoUnavailableError.
def _require_crypto_or_die(): """Ensure we have a crypto library, or throw CryptoUnavailableError. The oauth2client.crypt module requires either PyCrypto or PyOpenSSL to be available in order to function, but these are optional dependencies. """ if not HAS_CRYPTO: raise CryptoUnavailabl...
[ "def", "_require_crypto_or_die", "(", ")", ":", "if", "not", "HAS_CRYPTO", ":", "raise", "CryptoUnavailableError", "(", "'No crypto library available'", ")" ]
[ 1517, 0 ]
[ 1525, 67 ]
python
en
['en', 'en', 'en']
True
verify_id_token
(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS)
Verifies a signed JWT id_token. This function requires PyOpenSSL and because of that it does not work on App Engine. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP reques...
Verifies a signed JWT id_token.
def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): """Verifies a signed JWT id_token. This function requires PyOpenSSL and because of that it does not work on App Engine. Args: id_token: string, A Signed JWT. audience: string, ...
[ "def", "verify_id_token", "(", "id_token", ",", "audience", ",", "http", "=", "None", ",", "cert_uri", "=", "ID_TOKEN_VERIFICATION_CERTS", ")", ":", "_require_crypto_or_die", "(", ")", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_cached...
[ 1529, 0 ]
[ 1560, 73 ]
python
en
['en', 'en', 'en']
True
_extract_id_token
(id_token)
Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string or bytestring, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload.
Extract the JSON payload from a JWT.
def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string or bytestring, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ if type(id_token) == bytes: segments =...
[ "def", "_extract_id_token", "(", "id_token", ")", ":", "if", "type", "(", "id_token", ")", "==", "bytes", ":", "segments", "=", "id_token", ".", "split", "(", "b'.'", ")", "else", ":", "segments", "=", "id_token", ".", "split", "(", "u'.'", ")", "if", ...
[ 1563, 0 ]
[ 1584, 71 ]
python
en
['en', 'en', 'en']
True
_parse_exchange_token_response
(content)
Parses response of an exchange token request. Most providers return JSON but some (e.g. Facebook) return a url-encoded string. Args: content: The body of a response Returns: Content as a dictionary object. Note that the dict could be empty, i.e. {}. That basically indicates a ...
Parses response of an exchange token request.
def _parse_exchange_token_response(content): """Parses response of an exchange token request. Most providers return JSON but some (e.g. Facebook) return a url-encoded string. Args: content: The body of a response Returns: Content as a dictionary object. Note that the dict could be...
[ "def", "_parse_exchange_token_response", "(", "content", ")", ":", "resp", "=", "{", "}", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "try", ":", "resp", "=", "json", ".", "loads", "(", "content", ")", "except", "Exception", ":", ...
[ 1587, 0 ]
[ 1613, 15 ]
python
en
['en', 'en', 'en']
True
credentials_from_code
(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, revoke_uri=oau...
Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or iterable of strings, scope(s) to request. code: string, An authorization code, most likely passed down from ...
Exchanges an authorization code for an OAuth2Credentials object.
def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI, ...
[ "def", "credentials_from_code", "(", "client_id", ",", "client_secret", ",", "scope", ",", "code", ",", "redirect_uri", "=", "'postmessage'", ",", "http", "=", "None", ",", "user_agent", "=", "None", ",", "token_uri", "=", "oauth2client", ".", "GOOGLE_TOKEN_URI"...
[ 1617, 0 ]
[ 1679, 22 ]
python
en
['en', 'en', 'en']
True
credentials_from_clientsecrets_and_code
(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, device_uri=...
Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope: string...
Returns OAuth2Credentials from a clientsecrets file and an auth code.
def credentials_from_clientsecrets_and_code(filename, scope, code, message=None, redirect_uri='postmessage', http=None, cache=None, ...
[ "def", "credentials_from_clientsecrets_and_code", "(", "filename", ",", "scope", ",", "code", ",", "message", "=", "None", ",", "redirect_uri", "=", "'postmessage'", ",", "http", "=", "None", ",", "cache", "=", "None", ",", "device_uri", "=", "None", ")", ":...
[ 1683, 0 ]
[ 1736, 22 ]
python
en
['en', 'en', 'en']
True
_oauth2_web_server_flow_params
(kwargs)
Configures redirect URI parameters for OAuth2WebServerFlow.
Configures redirect URI parameters for OAuth2WebServerFlow.
def _oauth2_web_server_flow_params(kwargs): """Configures redirect URI parameters for OAuth2WebServerFlow.""" params = { 'access_type': 'offline', 'response_type': 'code', } params.update(kwargs) # Check for the presence of the deprecated approval_prompt param and # warn approp...
[ "def", "_oauth2_web_server_flow_params", "(", "kwargs", ")", ":", "params", "=", "{", "'access_type'", ":", "'offline'", ",", "'response_type'", ":", "'code'", ",", "}", "params", ".", "update", "(", "kwargs", ")", "# Check for the presence of the deprecated approval_...
[ 1777, 0 ]
[ 1801, 17 ]
python
en
['en', 'nl', 'en']
True
flow_from_clientsecrets
(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None, prompt=None)
Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or iterable of strings, sco...
Create a Flow from a clientsecrets file.
def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None, prompt=None): """Create a Flow from a clientsecrets file. Will create th...
[ "def", "flow_from_clientsecrets", "(", "filename", ",", "scope", ",", "redirect_uri", "=", "None", ",", "message", "=", "None", ",", "cache", "=", "None", ",", "login_hint", "=", "None", ",", "device_uri", "=", "None", ",", "pkce", "=", "None", ",", "cod...
[ 2092, 0 ]
[ 2169, 76 ]
python
en
['en', 'en', 'en']
True
Credentials.authorize
(self, http)
Take an httplib2.Http instance (or equivalent) and authorizes it. Authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. Args: http: httplib2....
Take an httplib2.Http instance (or equivalent) and authorizes it.
def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it. Authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. ...
[ "def", "authorize", "(", "self", ",", "http", ")", ":", "raise", "NotImplementedError" ]
[ 201, 4 ]
[ 212, 33 ]
python
en
['en', 'en', 'en']
True
Credentials.refresh
(self, http)
Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request.
Forces a refresh of the access_token.
def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ raise NotImplementedError
[ "def", "refresh", "(", "self", ",", "http", ")", ":", "raise", "NotImplementedError" ]
[ 214, 4 ]
[ 221, 33 ]
python
en
['en', 'en', 'en']
True
Credentials.revoke
(self, http)
Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request.
Revokes a refresh_token and makes the credentials void.
def revoke(self, http): """Revokes a refresh_token and makes the credentials void. Args: http: httplib2.Http, an http object to be used to make the revoke request. """ raise NotImplementedError
[ "def", "revoke", "(", "self", ",", "http", ")", ":", "raise", "NotImplementedError" ]
[ 223, 4 ]
[ 230, 33 ]
python
en
['en', 'en', 'en']
True
Credentials.apply
(self, headers)
Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to.
Add the authorization to the headers.
def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ raise NotImplementedError
[ "def", "apply", "(", "self", ",", "headers", ")", ":", "raise", "NotImplementedError" ]
[ 232, 4 ]
[ 238, 33 ]
python
en
['en', 'en', 'en']
True
Credentials._to_json
(self, strip, to_serialize=None)
Utility function that creates JSON repr. of a Credentials object. Args: strip: array, An array of names of members to exclude from the JSON. to_serialize: dict, (Optional) The properties for this object that will be serialized. This allows ca...
Utility function that creates JSON repr. of a Credentials object.
def _to_json(self, strip, to_serialize=None): """Utility function that creates JSON repr. of a Credentials object. Args: strip: array, An array of names of members to exclude from the JSON. to_serialize: dict, (Optional) The properties for this object ...
[ "def", "_to_json", "(", "self", ",", "strip", ",", "to_serialize", "=", "None", ")", ":", "curr_type", "=", "self", ".", "__class__", "if", "to_serialize", "is", "None", ":", "to_serialize", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", ...
[ 240, 4 ]
[ 273, 39 ]
python
en
['en', 'en', 'en']
True
Credentials.to_json
(self)
Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json().
Creating a JSON representation of an instance of Credentials.
def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(self.NON_SERIALIZED_MEMBERS)
[ "def", "to_json", "(", "self", ")", ":", "return", "self", ".", "_to_json", "(", "self", ".", "NON_SERIALIZED_MEMBERS", ")" ]
[ 275, 4 ]
[ 282, 57 ]
python
en
['en', 'en', 'en']
True
Credentials.new_from_json
(cls, json_data)
Utility class method to instantiate a Credentials subclass from JSON. Expects the JSON string to have been produced by to_json(). Args: json_data: string or bytes, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with ...
Utility class method to instantiate a Credentials subclass from JSON.
def new_from_json(cls, json_data): """Utility class method to instantiate a Credentials subclass from JSON. Expects the JSON string to have been produced by to_json(). Args: json_data: string or bytes, JSON from to_json(). Returns: An instance of the subclass o...
[ "def", "new_from_json", "(", "cls", ",", "json_data", ")", ":", "json_data_as_unicode", "=", "_helpers", ".", "_from_bytes", "(", "json_data", ")", "data", "=", "json", ".", "loads", "(", "json_data_as_unicode", ")", "# Find and call the right classmethod from_json() ...
[ 285, 4 ]
[ 313, 50 ]
python
en
['en', 'en', 'en']
True
Credentials.from_json
(cls, unused_data)
Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: unused_data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass.
Instantiate a Credentials object from a JSON description of it.
def from_json(cls, unused_data): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: unused_data: dict, A deserialized JSON object. Returns: An instance of a Credential...
[ "def", "from_json", "(", "cls", ",", "unused_data", ")", ":", "return", "Credentials", "(", ")" ]
[ 316, 4 ]
[ 327, 28 ]
python
en
['en', 'en', 'en']
True
Storage.__init__
(self, lock=None)
Create a Storage instance. Args: lock: An optional threading.Lock-like object. Must implement at least acquire() and release(). Does not need to be re-entrant.
Create a Storage instance.
def __init__(self, lock=None): """Create a Storage instance. Args: lock: An optional threading.Lock-like object. Must implement at least acquire() and release(). Does not need to be re-entrant. """ self._lock = lock
[ "def", "__init__", "(", "self", ",", "lock", "=", "None", ")", ":", "self", ".", "_lock", "=", "lock" ]
[ 342, 4 ]
[ 350, 25 ]
python
en
['en', 'de', 'en']
True
Storage.acquire_lock
(self)
Acquires any lock necessary to access this Storage. This lock is not reentrant.
Acquires any lock necessary to access this Storage.
def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ if self._lock is not None: self._lock.acquire()
[ "def", "acquire_lock", "(", "self", ")", ":", "if", "self", ".", "_lock", "is", "not", "None", ":", "self", ".", "_lock", ".", "acquire", "(", ")" ]
[ 352, 4 ]
[ 358, 32 ]
python
en
['en', 'en', 'en']
True
Storage.release_lock
(self)
Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError in the case of a threading.Lock or multiprocessing.Lock.
Release the Storage lock.
def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError in the case of a threading.Lock or multiprocessing.Lock. """ if self._lock is not None: self._lock.release()
[ "def", "release_lock", "(", "self", ")", ":", "if", "self", ".", "_lock", "is", "not", "None", ":", "self", ".", "_lock", ".", "release", "(", ")" ]
[ 360, 4 ]
[ 367, 32 ]
python
en
['en', 'de', 'en']
True
Storage.locked_get
(self)
Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials
Retrieve credential.
def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ raise NotImplementedError
[ "def", "locked_get", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 369, 4 ]
[ 377, 33 ]
python
en
['en', 'pt', 'en']
False
Storage.locked_put
(self, credentials)
Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store.
Write a credential.
def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ raise NotImplementedError
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "raise", "NotImplementedError" ]
[ 379, 4 ]
[ 387, 33 ]
python
en
['es', 'pt', 'en']
False
Storage.locked_delete
(self)
Delete a credential. The Storage lock must be held when this is called.
Delete a credential.
def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ raise NotImplementedError
[ "def", "locked_delete", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 389, 4 ]
[ 394, 33 ]
python
en
['en', 'it', 'en']
True