Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def redirect(
to, headers=None, status=302, content_type="text/html; charset=utf-8"
):
headers = headers or {}
# URL Quote the URL before redirecting
safe_to = quote_plus(to, safe=":/%#?&=@[]!$&'()*+,;")
# According to RFC 7231, a relative URI is now permitted.
headers["Location"] = safe_to
return HTTPResponse(
status=status, headers=headers, content_type=content_type
)
|
[
"Abort execution and cause a 302 redirect (by default).\n\n :param to: path or fully qualified URL to redirect to\n :param headers: optional dict of headers to include in the new request\n :param status: status code (int) of the new request, defaults to 302\n :param content_type: the content type (string) of the response\n :returns: the redirecting Response\n "
] |
Please provide a description of the function:async def write(self, data):
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.protocol.drain()
|
[
"Writes a chunk of data to the streaming response.\n\n :param data: bytes-ish data to be written.\n "
] |
Please provide a description of the function:async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
headers = self.get_headers(
version,
keep_alive=keep_alive,
keep_alive_timeout=keep_alive_timeout,
)
self.protocol.push_data(headers)
await self.protocol.drain()
await self.streaming_fn(self)
self.protocol.push_data(b"0\r\n\r\n")
|
[
"Streams headers, runs the `streaming_fn` callback that writes\n content to the response body, then finalizes the response body.\n "
] |
Please provide a description of the function:def insert(self, index: int, item: object) -> None:
self._blueprints.insert(index, item)
|
[
"\n The Abstract class `MutableSequence` leverages this insert method to\n perform the `BlueprintGroup.append` operation.\n\n :param index: Index to use for removing a new Blueprint item\n :param item: New `Blueprint` object.\n :return: None\n "
] |
Please provide a description of the function:def middleware(self, *args, **kwargs):
kwargs["bp_group"] = True
def register_middleware_for_blueprints(fn):
for blueprint in self.blueprints:
blueprint.middleware(fn, *args, **kwargs)
return register_middleware_for_blueprints
|
[
"\n A decorator that can be used to implement a Middleware plugin to\n all of the Blueprints that belongs to this specific Blueprint Group.\n\n In case of nested Blueprint Groups, the same middleware is applied\n across each of the Blueprints recursively.\n\n :param args: Optional positional Parameters to be use middleware\n :param kwargs: Optional Keyword arg to use with Middleware\n :return: Partial function to apply the middleware\n "
] |
Please provide a description of the function:def response(self, request, exception):
handler = self.lookup(exception)
response = None
try:
if handler:
response = handler(request, exception)
if response is None:
response = self.default(request, exception)
except Exception:
self.log(format_exc())
try:
url = repr(request.url)
except AttributeError:
url = "unknown"
response_message = (
"Exception raised in exception handler " '"%s" for uri: %s'
)
logger.exception(response_message, handler.__name__, url)
if self.debug:
return text(response_message % (handler.__name__, url), 500)
else:
return text("An error occurred while handling an error", 500)
return response
|
[
"Fetches and executes an exception handler and returns a response\n object\n\n :param request: Instance of :class:`sanic.request.Request`\n :param exception: Exception to handle\n\n :type request: :class:`sanic.request.Request`\n :type exception: :class:`sanic.exceptions.SanicException` or\n :class:`Exception`\n\n :return: Wrap the return value obtained from :func:`default`\n or registered handler for that type of exception.\n "
] |
Please provide a description of the function:def default(self, request, exception):
self.log(format_exc())
try:
url = repr(request.url)
except AttributeError:
url = "unknown"
response_message = "Exception occurred while handling uri: %s"
logger.exception(response_message, url)
if issubclass(type(exception), SanicException):
return text(
"Error: {}".format(exception),
status=getattr(exception, "status_code", 500),
headers=getattr(exception, "headers", dict()),
)
elif self.debug:
html_output = self._render_traceback_html(exception, request)
return html(html_output, status=500)
else:
return html(INTERNAL_SERVER_ERROR_HTML, status=500)
|
[
"\n Provide a default behavior for the objects of :class:`ErrorHandler`.\n If a developer chooses to extent the :class:`ErrorHandler` they can\n provide a custom implementation for this method to behave in a way\n they see fit.\n\n :param request: Incoming request\n :param exception: Exception object\n\n :type request: :class:`sanic.request.Request`\n :type exception: :class:`sanic.exceptions.SanicException` or\n :class:`Exception`\n :return:\n "
] |
Please provide a description of the function:def _create_ssl_context(cfg):
ctx = ssl.SSLContext(cfg.ssl_version)
ctx.load_cert_chain(cfg.certfile, cfg.keyfile)
ctx.verify_mode = cfg.cert_reqs
if cfg.ca_certs:
ctx.load_verify_locations(cfg.ca_certs)
if cfg.ciphers:
ctx.set_ciphers(cfg.ciphers)
return ctx
|
[
" Creates SSLContext instance for usage in asyncio.create_server.\n See ssl.SSLSocket.__init__ for more details.\n "
] |
Please provide a description of the function:def trigger_events(events, loop):
for event in events:
result = event(loop)
if isawaitable(result):
loop.run_until_complete(result)
|
[
"Trigger event callbacks (functions or async)\n\n :param events: one or more sync or async functions to execute\n :param loop: event loop\n "
] |
Please provide a description of the function:def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
request_buffer_queue_size=100,
reuse_port=False,
loop=None,
protocol=HttpProtocol,
backlog=100,
register_sys_signals=True,
run_multiple=False,
run_async=False,
connections=None,
signal=Signal(),
request_class=None,
access_log=True,
keep_alive=True,
is_request_stream=False,
router=None,
websocket_max_size=None,
websocket_max_queue=None,
websocket_read_limit=2 ** 16,
websocket_write_limit=2 ** 16,
state=None,
graceful_shutdown_timeout=15.0,
asyncio_server_kwargs=None,
):
if not run_async:
# create new event_loop after fork
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if debug:
loop.set_debug(debug)
connections = connections if connections is not None else set()
server = partial(
protocol,
loop=loop,
connections=connections,
signal=signal,
app=app,
request_handler=request_handler,
error_handler=error_handler,
request_timeout=request_timeout,
response_timeout=response_timeout,
keep_alive_timeout=keep_alive_timeout,
request_max_size=request_max_size,
request_class=request_class,
access_log=access_log,
keep_alive=keep_alive,
is_request_stream=is_request_stream,
router=router,
websocket_max_size=websocket_max_size,
websocket_max_queue=websocket_max_queue,
websocket_read_limit=websocket_read_limit,
websocket_write_limit=websocket_write_limit,
state=state,
debug=debug,
)
asyncio_server_kwargs = (
asyncio_server_kwargs if asyncio_server_kwargs else {}
)
server_coroutine = loop.create_server(
server,
host,
port,
ssl=ssl,
reuse_port=reuse_port,
sock=sock,
backlog=backlog,
**asyncio_server_kwargs
)
if run_async:
return server_coroutine
trigger_events(before_start, loop)
try:
http_server = loop.run_until_complete(server_coroutine)
except BaseException:
logger.exception("Unable to start server")
return
trigger_events(after_start, loop)
# Ignore SIGINT when run_multiple
if run_multiple:
signal_func(SIGINT, SIG_IGN)
# Register signals for graceful termination
if register_sys_signals:
_singals = (SIGTERM,) if run_multiple else (SIGINT, SIGTERM)
for _signal in _singals:
try:
loop.add_signal_handler(_signal, loop.stop)
except NotImplementedError:
logger.warning(
"Sanic tried to use loop.add_signal_handler "
"but it is not implemented on this platform."
)
pid = os.getpid()
try:
logger.info("Starting worker [%s]", pid)
loop.run_forever()
finally:
logger.info("Stopping worker [%s]", pid)
# Run the on_stop function if provided
trigger_events(before_stop, loop)
# Wait for event loop to finish and all connections to drain
http_server.close()
loop.run_until_complete(http_server.wait_closed())
# Complete all tasks on the loop
signal.stopped = True
for connection in connections:
connection.close_if_idle()
# Gracefully shutdown timeout.
# We should provide graceful_shutdown_timeout,
# instead of letting connection hangs forever.
# Let's roughly calcucate time.
start_shutdown = 0
while connections and (start_shutdown < graceful_shutdown_timeout):
loop.run_until_complete(asyncio.sleep(0.1))
start_shutdown = start_shutdown + 0.1
# Force close non-idle connection after waiting for
# graceful_shutdown_timeout
coros = []
for conn in connections:
if hasattr(conn, "websocket") and conn.websocket:
coros.append(conn.websocket.close_connection())
else:
conn.close()
_shutdown = asyncio.gather(*coros, loop=loop)
loop.run_until_complete(_shutdown)
trigger_events(after_stop, loop)
loop.close()
|
[
"Start asynchronous HTTP Server on an individual process.\n\n :param host: Address to host on\n :param port: Port to host on\n :param request_handler: Sanic request handler with middleware\n :param error_handler: Sanic error handler with middleware\n :param before_start: function to be executed before the server starts\n listening. Takes arguments `app` instance and `loop`\n :param after_start: function to be executed after the server starts\n listening. Takes arguments `app` instance and `loop`\n :param before_stop: function to be executed when a stop signal is\n received before it is respected. Takes arguments\n `app` instance and `loop`\n :param after_stop: function to be executed when a stop signal is\n received after it is respected. Takes arguments\n `app` instance and `loop`\n :param debug: enables debug output (slows server)\n :param request_timeout: time in seconds\n :param response_timeout: time in seconds\n :param keep_alive_timeout: time in seconds\n :param ssl: SSLContext\n :param sock: Socket for the server to accept connections from\n :param request_max_size: size in bytes, `None` for no limit\n :param reuse_port: `True` for multiple workers\n :param loop: asyncio compatible event loop\n :param protocol: subclass of asyncio protocol class\n :param request_class: Request class to use\n :param access_log: disable/enable access log\n :param websocket_max_size: enforces the maximum size for\n incoming messages in bytes.\n :param websocket_max_queue: sets the maximum length of the queue\n that holds incoming messages.\n :param websocket_read_limit: sets the high-water limit of the buffer for\n incoming bytes, the low-water limit is half\n the high-water limit.\n :param websocket_write_limit: sets the high-water limit of the buffer for\n outgoing bytes, the low-water limit is a\n quarter of the high-water limit.\n :param is_request_stream: disable/enable Request.stream\n :param request_buffer_queue_size: streaming request buffer queue size\n :param router: Router object\n :param graceful_shutdown_timeout: How long take to Force close non-idle\n connection\n :param asyncio_server_kwargs: key-value args for asyncio/uvloop\n create_server method\n :return: Nothing\n "
] |
Please provide a description of the function:def keep_alive(self):
return (
self._keep_alive
and not self.signal.stopped
and self.parser.should_keep_alive()
)
|
[
"\n Check if the connection needs to be kept alive based on the params\n attached to the `_keep_alive` attribute, :attr:`Signal.stopped`\n and :func:`HttpProtocol.parser.should_keep_alive`\n\n :return: ``True`` if connection is to be kept alive ``False`` else\n "
] |
Please provide a description of the function:def keep_alive_timeout_callback(self):
time_elapsed = time() - self._last_response_time
if time_elapsed < self.keep_alive_timeout:
time_left = self.keep_alive_timeout - time_elapsed
self._keep_alive_timeout_handler = self.loop.call_later(
time_left, self.keep_alive_timeout_callback
)
else:
logger.debug("KeepAlive Timeout. Closing connection.")
self.transport.close()
self.transport = None
|
[
"\n Check if elapsed time since last response exceeds our configured\n maximum keep alive timeout value and if so, close the transport\n pipe and let the response writer handle the error.\n\n :return: None\n "
] |
Please provide a description of the function:def execute_request_handler(self):
self._response_timeout_handler = self.loop.call_later(
self.response_timeout, self.response_timeout_callback
)
self._last_request_time = time()
self._request_handler_task = self.loop.create_task(
self.request_handler(
self.request, self.write_response, self.stream_response
)
)
|
[
"\n Invoke the request handler defined by the\n :func:`sanic.app.Sanic.handle_request` method\n\n :return: None\n "
] |
Please provide a description of the function:def log_response(self, response):
if self.access_log:
extra = {"status": getattr(response, "status", 0)}
if isinstance(response, HTTPResponse):
extra["byte"] = len(response.body)
else:
extra["byte"] = -1
extra["host"] = "UNKNOWN"
if self.request is not None:
if self.request.ip:
extra["host"] = "{0}:{1}".format(
self.request.ip, self.request.port
)
extra["request"] = "{0} {1}".format(
self.request.method, self.request.url
)
else:
extra["request"] = "nil"
access_logger.info("", extra=extra)
|
[
"\n Helper method provided to enable the logging of responses in case if\n the :attr:`HttpProtocol.access_log` is enabled.\n\n :param response: Response generated for the current request\n\n :type response: :class:`sanic.response.HTTPResponse` or\n :class:`sanic.response.StreamingHTTPResponse`\n\n :return: None\n "
] |
Please provide a description of the function:def write_response(self, response):
if self._response_timeout_handler:
self._response_timeout_handler.cancel()
self._response_timeout_handler = None
try:
keep_alive = self.keep_alive
self.transport.write(
response.output(
self.request.version, keep_alive, self.keep_alive_timeout
)
)
self.log_response(response)
except AttributeError:
logger.error(
"Invalid response object for url %s, "
"Expected Type: HTTPResponse, Actual Type: %s",
self.url,
type(response),
)
self.write_error(ServerError("Invalid response type"))
except RuntimeError:
if self._debug:
logger.error(
"Connection lost before response written @ %s",
self.request.ip,
)
keep_alive = False
except Exception as e:
self.bail_out(
"Writing response failed, connection closed {}".format(repr(e))
)
finally:
if not keep_alive:
self.transport.close()
self.transport = None
else:
self._keep_alive_timeout_handler = self.loop.call_later(
self.keep_alive_timeout, self.keep_alive_timeout_callback
)
self._last_response_time = time()
self.cleanup()
|
[
"\n Writes response content synchronously to the transport.\n "
] |
Please provide a description of the function:def bail_out(self, message, from_error=False):
if from_error or self.transport is None or self.transport.is_closing():
logger.error(
"Transport closed @ %s and exception "
"experienced during error handling",
(
self.transport.get_extra_info("peername")
if self.transport is not None
else "N/A"
),
)
logger.debug("Exception:", exc_info=True)
else:
self.write_error(ServerError(message))
logger.error(message)
|
[
"\n In case if the transport pipes are closed and the sanic app encounters\n an error while writing data to the transport pipe, we log the error\n with proper details.\n\n :param message: Error message to display\n :param from_error: If the bail out was invoked while handling an\n exception scenario.\n\n :type message: str\n :type from_error: bool\n\n :return: None\n "
] |
Please provide a description of the function:def cleanup(self):
self.parser = None
self.request = None
self.url = None
self.headers = None
self._request_handler_task = None
self._request_stream_task = None
self._total_request_size = 0
self._is_stream_handler = False
|
[
"This is called when KeepAlive feature is used,\n it resets the connection in order for it to be able\n to handle receiving another request on the same connection."
] |
Please provide a description of the function:def parse_multipart_form(body, boundary):
files = RequestParameters()
fields = RequestParameters()
form_parts = body.split(boundary)
for form_part in form_parts[1:-1]:
file_name = None
content_type = "text/plain"
content_charset = "utf-8"
field_name = None
line_index = 2
line_end_index = 0
while not line_end_index == -1:
line_end_index = form_part.find(b"\r\n", line_index)
form_line = form_part[line_index:line_end_index].decode("utf-8")
line_index = line_end_index + 2
if not form_line:
break
colon_index = form_line.index(":")
form_header_field = form_line[0:colon_index].lower()
form_header_value, form_parameters = parse_header(
form_line[colon_index + 2 :]
)
if form_header_field == "content-disposition":
field_name = form_parameters.get("name")
file_name = form_parameters.get("filename")
# non-ASCII filenames in RFC2231, "filename*" format
if file_name is None and form_parameters.get("filename*"):
encoding, _, value = email.utils.decode_rfc2231(
form_parameters["filename*"]
)
file_name = unquote(value, encoding=encoding)
elif form_header_field == "content-type":
content_type = form_header_value
content_charset = form_parameters.get("charset", "utf-8")
if field_name:
post_data = form_part[line_index:-4]
if file_name is None:
value = post_data.decode(content_charset)
if field_name in fields:
fields[field_name].append(value)
else:
fields[field_name] = [value]
else:
form_file = File(
type=content_type, name=file_name, body=post_data
)
if field_name in files:
files[field_name].append(form_file)
else:
files[field_name] = [form_file]
else:
logger.debug(
"Form-data field does not have a 'name' parameter "
"in the Content-Disposition header"
)
return fields, files
|
[
"Parse a request body and returns fields and files\n\n :param body: bytes request body\n :param boundary: bytes multipart boundary\n :return: fields (RequestParameters), files (RequestParameters)\n "
] |
Please provide a description of the function:async def read(self):
payload = await self._queue.get()
self._queue.task_done()
return payload
|
[
" Stop reading when gets None "
] |
Please provide a description of the function:def token(self):
prefixes = ("Bearer", "Token")
auth_header = self.headers.get("Authorization")
if auth_header is not None:
for prefix in prefixes:
if prefix in auth_header:
return auth_header.partition(prefix)[-1].strip()
return auth_header
|
[
"Attempt to return the auth header token.\n\n :return: token related to request\n "
] |
Please provide a description of the function:def get_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> RequestParameters:
if not self.parsed_args[
(keep_blank_values, strict_parsing, encoding, errors)
]:
if self.query_string:
self.parsed_args[
(keep_blank_values, strict_parsing, encoding, errors)
] = RequestParameters(
parse_qs(
qs=self.query_string,
keep_blank_values=keep_blank_values,
strict_parsing=strict_parsing,
encoding=encoding,
errors=errors,
)
)
return self.parsed_args[
(keep_blank_values, strict_parsing, encoding, errors)
]
|
[
"\n Method to parse `query_string` using `urllib.parse.parse_qs`.\n This methods is used by `args` property.\n Can be used directly if you need to change default parameters.\n :param keep_blank_values: flag indicating whether blank values in\n percent-encoded queries should be treated as blank strings.\n A true value indicates that blanks should be retained as blank\n strings. The default false value indicates that blank values\n are to be ignored and treated as if they were not included.\n :type keep_blank_values: bool\n :param strict_parsing: flag indicating what to do with parsing errors.\n If false (the default), errors are silently ignored. If true,\n errors raise a ValueError exception.\n :type strict_parsing: bool\n :param encoding: specify how to decode percent-encoded sequences\n into Unicode characters, as accepted by the bytes.decode() method.\n :type encoding: str\n :param errors: specify how to decode percent-encoded sequences\n into Unicode characters, as accepted by the bytes.decode() method.\n :type errors: str\n :return: RequestParameters\n "
] |
Please provide a description of the function:def get_query_args(
self,
keep_blank_values: bool = False,
strict_parsing: bool = False,
encoding: str = "utf-8",
errors: str = "replace",
) -> list:
if not self.parsed_not_grouped_args[
(keep_blank_values, strict_parsing, encoding, errors)
]:
if self.query_string:
self.parsed_not_grouped_args[
(keep_blank_values, strict_parsing, encoding, errors)
] = parse_qsl(
qs=self.query_string,
keep_blank_values=keep_blank_values,
strict_parsing=strict_parsing,
encoding=encoding,
errors=errors,
)
return self.parsed_not_grouped_args[
(keep_blank_values, strict_parsing, encoding, errors)
]
|
[
"\n Method to parse `query_string` using `urllib.parse.parse_qsl`.\n This methods is used by `query_args` property.\n Can be used directly if you need to change default parameters.\n :param keep_blank_values: flag indicating whether blank values in\n percent-encoded queries should be treated as blank strings.\n A true value indicates that blanks should be retained as blank\n strings. The default false value indicates that blank values\n are to be ignored and treated as if they were not included.\n :type keep_blank_values: bool\n :param strict_parsing: flag indicating what to do with parsing errors.\n If false (the default), errors are silently ignored. If true,\n errors raise a ValueError exception.\n :type strict_parsing: bool\n :param encoding: specify how to decode percent-encoded sequences\n into Unicode characters, as accepted by the bytes.decode() method.\n :type encoding: str\n :param errors: specify how to decode percent-encoded sequences\n into Unicode characters, as accepted by the bytes.decode() method.\n :type errors: str\n :return: list\n "
] |
Please provide a description of the function:def remote_addr(self):
if not hasattr(self, "_remote_addr"):
if self.app.config.PROXIES_COUNT == 0:
self._remote_addr = ""
elif self.app.config.REAL_IP_HEADER and self.headers.get(
self.app.config.REAL_IP_HEADER
):
self._remote_addr = self.headers[
self.app.config.REAL_IP_HEADER
]
elif self.app.config.FORWARDED_FOR_HEADER:
forwarded_for = self.headers.get(
self.app.config.FORWARDED_FOR_HEADER, ""
).split(",")
remote_addrs = [
addr
for addr in [addr.strip() for addr in forwarded_for]
if addr
]
if self.app.config.PROXIES_COUNT == -1:
self._remote_addr = remote_addrs[0]
elif len(remote_addrs) >= self.app.config.PROXIES_COUNT:
self._remote_addr = remote_addrs[
-self.app.config.PROXIES_COUNT
]
else:
self._remote_addr = ""
else:
self._remote_addr = ""
return self._remote_addr
|
[
"Attempt to return the original client ip based on X-Forwarded-For\n or X-Real-IP. If HTTP headers are unavailable or untrusted, returns\n an empty string.\n\n :return: original client ip.\n "
] |
Please provide a description of the function:def strtobool(val):
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return True
elif val in ("n", "no", "f", "false", "off", "0"):
return False
else:
raise ValueError("invalid truth value %r" % (val,))
|
[
"\n This function was borrowed from distutils.utils. While distutils\n is part of stdlib, it feels odd to use distutils in main application code.\n\n The function was modified to walk its talk and actually return bool\n and not int.\n "
] |
Please provide a description of the function:def from_envvar(self, variable_name):
config_file = os.environ.get(variable_name)
if not config_file:
raise RuntimeError(
"The environment variable %r is not set and "
"thus configuration could not be loaded." % variable_name
)
return self.from_pyfile(config_file)
|
[
"Load a configuration from an environment variable pointing to\n a configuration file.\n\n :param variable_name: name of the environment variable\n :return: bool. ``True`` if able to load config, ``False`` otherwise.\n "
] |
Please provide a description of the function:def from_object(self, obj):
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
|
[
"Update the values from the given object.\n Objects are usually either modules or classes.\n\n Just the uppercase variables in that object are stored in the config.\n Example usage::\n\n from yourapplication import default_config\n app.config.from_object(default_config)\n\n You should not use this function to load the actual configuration but\n rather configuration defaults. The actual config should be loaded\n with :meth:`from_pyfile` and ideally from a location not within the\n package because the package might be installed system wide.\n\n :param obj: an object holding the configuration\n "
] |
Please provide a description of the function:def load_environment_vars(self, prefix=SANIC_PREFIX):
for k, v in os.environ.items():
if k.startswith(prefix):
_, config_key = k.split(prefix, 1)
try:
self[config_key] = int(v)
except ValueError:
try:
self[config_key] = float(v)
except ValueError:
try:
self[config_key] = strtobool(v)
except ValueError:
self[config_key] = v
|
[
"\n Looks for prefixed environment variables and applies\n them to the configuration if present.\n "
] |
Please provide a description of the function:def parse_parameter_string(cls, parameter_string):
# We could receive NAME or NAME:PATTERN
name = parameter_string
pattern = "string"
if ":" in parameter_string:
name, pattern = parameter_string.split(":", 1)
if not name:
raise ValueError(
"Invalid parameter syntax: {}".format(parameter_string)
)
default = (str, pattern)
# Pull from pre-configured types
_type, pattern = REGEX_TYPES.get(pattern, default)
return name, _type, pattern
|
[
"Parse a parameter string into its constituent name, type, and\n pattern\n\n For example::\n\n parse_parameter_string('<param_one:[A-z]>')` ->\n ('param_one', str, '[A-z]')\n\n :param parameter_string: String to parse\n :return: tuple containing\n (parameter_name, parameter_type, parameter_pattern)\n "
] |
Please provide a description of the function:def add(
self,
uri,
methods,
handler,
host=None,
strict_slashes=False,
version=None,
name=None,
):
if version is not None:
version = re.escape(str(version).strip("/").lstrip("v"))
uri = "/".join(["/v{}".format(version), uri.lstrip("/")])
# add regular version
self._add(uri, methods, handler, host, name)
if strict_slashes:
return
if not isinstance(host, str) and host is not None:
# we have gotten back to the top of the recursion tree where the
# host was originally a list. By now, we've processed the strict
# slashes logic on the leaf nodes (the individual host strings in
# the list of host)
return
# Add versions with and without trailing /
slashed_methods = self.routes_all.get(uri + "/", frozenset({}))
unslashed_methods = self.routes_all.get(uri[:-1], frozenset({}))
if isinstance(methods, Iterable):
_slash_is_missing = all(
method in slashed_methods for method in methods
)
_without_slash_is_missing = all(
method in unslashed_methods for method in methods
)
else:
_slash_is_missing = methods in slashed_methods
_without_slash_is_missing = methods in unslashed_methods
slash_is_missing = not uri[-1] == "/" and not _slash_is_missing
without_slash_is_missing = (
uri[-1] == "/" and not _without_slash_is_missing and not uri == "/"
)
# add version with trailing slash
if slash_is_missing:
self._add(uri + "/", methods, handler, host, name)
# add version without trailing slash
elif without_slash_is_missing:
self._add(uri[:-1], methods, handler, host, name)
|
[
"Add a handler to the route list\n\n :param uri: path to match\n :param methods: sequence of accepted method names. If none are\n provided, any method is allowed\n :param handler: request handler function.\n When executed, it should provide a response object.\n :param strict_slashes: strict to trailing slash\n :param version: current version of the route or blueprint. See\n docs for further details.\n :return: Nothing\n "
] |
Please provide a description of the function:def _add(self, uri, methods, handler, host=None, name=None):
if host is not None:
if isinstance(host, str):
uri = host + uri
self.hosts.add(host)
else:
if not isinstance(host, Iterable):
raise ValueError(
"Expected either string or Iterable of "
"host strings, not {!r}".format(host)
)
for host_ in host:
self.add(uri, methods, handler, host_, name)
return
# Dict for faster lookups of if method allowed
if methods:
methods = frozenset(methods)
parameters = []
parameter_names = set()
properties = {"unhashable": None}
def add_parameter(match):
name = match.group(1)
name, _type, pattern = self.parse_parameter_string(name)
if name in parameter_names:
raise ParameterNameConflicts(
"Multiple parameter named <{name}> "
"in route uri {uri}".format(name=name, uri=uri)
)
parameter_names.add(name)
parameter = Parameter(name=name, cast=_type)
parameters.append(parameter)
# Mark the whole route as unhashable if it has the hash key in it
if re.search(r"(^|[^^]){1}/", pattern):
properties["unhashable"] = True
# Mark the route as unhashable if it matches the hash key
elif re.search(r"/", pattern):
properties["unhashable"] = True
return "({})".format(pattern)
pattern_string = re.sub(self.parameter_pattern, add_parameter, uri)
pattern = re.compile(r"^{}$".format(pattern_string))
def merge_route(route, methods, handler):
# merge to the existing route when possible.
if not route.methods or not methods:
# method-unspecified routes are not mergeable.
raise RouteExists("Route already registered: {}".format(uri))
elif route.methods.intersection(methods):
# already existing method is not overloadable.
duplicated = methods.intersection(route.methods)
raise RouteExists(
"Route already registered: {} [{}]".format(
uri, ",".join(list(duplicated))
)
)
if isinstance(route.handler, CompositionView):
view = route.handler
else:
view = CompositionView()
view.add(route.methods, route.handler)
view.add(methods, handler)
route = route._replace(
handler=view, methods=methods.union(route.methods)
)
return route
if parameters:
# TODO: This is too complex, we need to reduce the complexity
if properties["unhashable"]:
routes_to_check = self.routes_always_check
ndx, route = self.check_dynamic_route_exists(
pattern, routes_to_check, parameters
)
else:
routes_to_check = self.routes_dynamic[url_hash(uri)]
ndx, route = self.check_dynamic_route_exists(
pattern, routes_to_check, parameters
)
if ndx != -1:
# Pop the ndx of the route, no dups of the same route
routes_to_check.pop(ndx)
else:
route = self.routes_all.get(uri)
# prefix the handler name with the blueprint name
# if available
# special prefix for static files
is_static = False
if name and name.startswith("_static_"):
is_static = True
name = name.split("_static_", 1)[-1]
if hasattr(handler, "__blueprintname__"):
handler_name = "{}.{}".format(
handler.__blueprintname__, name or handler.__name__
)
else:
handler_name = name or getattr(handler, "__name__", None)
if route:
route = merge_route(route, methods, handler)
else:
route = Route(
handler=handler,
methods=methods,
pattern=pattern,
parameters=parameters,
name=handler_name,
uri=uri,
)
self.routes_all[uri] = route
if is_static:
pair = self.routes_static_files.get(handler_name)
if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])):
self.routes_static_files[handler_name] = (uri, route)
else:
pair = self.routes_names.get(handler_name)
if not (pair and (pair[0] + "/" == uri or uri + "/" == pair[0])):
self.routes_names[handler_name] = (uri, route)
if properties["unhashable"]:
self.routes_always_check.append(route)
elif parameters:
self.routes_dynamic[url_hash(uri)].append(route)
else:
self.routes_static[uri] = route
|
[
"Add a handler to the route list\n\n :param uri: path to match\n :param methods: sequence of accepted method names. If none are\n provided, any method is allowed\n :param handler: request handler function.\n When executed, it should provide a response object.\n :param name: user defined route name for url_for\n :return: Nothing\n "
] |
Please provide a description of the function:def check_dynamic_route_exists(pattern, routes_to_check, parameters):
for ndx, route in enumerate(routes_to_check):
if route.pattern == pattern and route.parameters == parameters:
return ndx, route
else:
return -1, None
|
[
"\n Check if a URL pattern exists in a list of routes provided based on\n the comparison of URL pattern and the parameters.\n\n :param pattern: URL parameter pattern\n :param routes_to_check: list of dynamic routes either hashable or\n unhashable routes.\n :param parameters: List of :class:`Parameter` items\n :return: Tuple of index and route if matching route exists else\n -1 for index and None for route\n "
] |
Please provide a description of the function:def find_route_by_view_name(self, view_name, name=None):
if not view_name:
return (None, None)
if view_name == "static" or view_name.endswith(".static"):
return self.routes_static_files.get(name, (None, None))
return self.routes_names.get(view_name, (None, None))
|
[
"Find a route in the router based on the specified view name.\n\n :param view_name: string of view name to search by\n :param kwargs: additional params, usually for static files\n :return: tuple containing (uri, Route)\n "
] |
Please provide a description of the function:def get(self, request):
# No virtual hosts specified; default behavior
if not self.hosts:
return self._get(request.path, request.method, "")
# virtual hosts specified; try to match route to the host header
try:
return self._get(
request.path, request.method, request.headers.get("Host", "")
)
# try default hosts
except NotFound:
return self._get(request.path, request.method, "")
|
[
"Get a request handler based on the URL of the request, or raises an\n error\n\n :param request: Request object\n :return: handler, arguments, keyword arguments\n "
] |
Please provide a description of the function:def get_supported_methods(self, url):
route = self.routes_all.get(url)
# if methods are None then this logic will prevent an error
return getattr(route, "methods", None) or frozenset()
|
[
"Get a list of supported methods for a url and optional host.\n\n :param url: URL string (including host)\n :return: frozenset of supported methods\n "
] |
Please provide a description of the function:def _get(self, url, method, host):
url = unquote(host + url)
# Check against known static routes
route = self.routes_static.get(url)
method_not_supported = MethodNotSupported(
"Method {} not allowed for URL {}".format(method, url),
method=method,
allowed_methods=self.get_supported_methods(url),
)
if route:
if route.methods and method not in route.methods:
raise method_not_supported
match = route.pattern.match(url)
else:
route_found = False
# Move on to testing all regex routes
for route in self.routes_dynamic[url_hash(url)]:
match = route.pattern.match(url)
route_found |= match is not None
# Do early method checking
if match and method in route.methods:
break
else:
# Lastly, check against all regex routes that cannot be hashed
for route in self.routes_always_check:
match = route.pattern.match(url)
route_found |= match is not None
# Do early method checking
if match and method in route.methods:
break
else:
# Route was found but the methods didn't match
if route_found:
raise method_not_supported
raise NotFound("Requested URL {} not found".format(url))
kwargs = {
p.name: p.cast(value)
for value, p in zip(match.groups(1), route.parameters)
}
route_handler = route.handler
if hasattr(route_handler, "handlers"):
route_handler = route_handler.handlers[method]
return route_handler, [], kwargs, route.uri
|
[
"Get a request handler based on the URL of the request, or raises an\n error. Internal method for caching.\n\n :param url: request URL\n :param method: request method\n :return: handler, arguments, keyword arguments\n "
] |
Please provide a description of the function:def is_stream_handler(self, request):
try:
handler = self.get(request)[0]
except (NotFound, MethodNotSupported):
return False
if hasattr(handler, "view_class") and hasattr(
handler.view_class, request.method.lower()
):
handler = getattr(handler.view_class, request.method.lower())
return hasattr(handler, "is_stream")
|
[
" Handler for request is stream or not.\n :param request: Request object\n :return: bool\n "
] |
Please provide a description of the function:def _get_args_for_reloading():
rv = [sys.executable]
main_module = sys.modules["__main__"]
mod_spec = getattr(main_module, "__spec__", None)
if mod_spec:
# Parent exe was launched as a module rather than a script
rv.extend(["-m", mod_spec.name])
if len(sys.argv) > 1:
rv.extend(sys.argv[1:])
else:
rv.extend(sys.argv)
return rv
|
[
"Returns the executable."
] |
Please provide a description of the function:def restart_with_reloader():
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = Process(
target=subprocess.call,
args=(cmd,),
kwargs={"cwd": cwd, "shell": True, "env": new_environ},
)
worker_process.start()
return worker_process
|
[
"Create a new process and a subprocess in it with the same arguments as\n this one.\n "
] |
Please provide a description of the function:def kill_process_children_unix(pid):
root_process_path = "/proc/{pid}/task/{pid}/children".format(pid=pid)
if not os.path.isfile(root_process_path):
return
with open(root_process_path) as children_list_file:
children_list_pid = children_list_file.read().split()
for child_pid in children_list_pid:
children_proc_path = "/proc/%s/task/%s/children" % (
child_pid,
child_pid,
)
if not os.path.isfile(children_proc_path):
continue
with open(children_proc_path) as children_list_file_2:
children_list_pid_2 = children_list_file_2.read().split()
for _pid in children_list_pid_2:
try:
os.kill(int(_pid), signal.SIGTERM)
except ProcessLookupError:
continue
try:
os.kill(int(child_pid), signal.SIGTERM)
except ProcessLookupError:
continue
|
[
"Find and kill child processes of a process (maximum two level).\n\n :param pid: PID of parent process (process ID)\n :return: Nothing\n "
] |
Please provide a description of the function:def kill_process_children(pid):
if sys.platform == "darwin":
kill_process_children_osx(pid)
elif sys.platform == "linux":
kill_process_children_unix(pid)
else:
pass
|
[
"Find and kill child processes of a process.\n\n :param pid: PID of parent process (process ID)\n :return: Nothing\n "
] |
Please provide a description of the function:def watchdog(sleep_interval):
mtimes = {}
worker_process = restart_with_reloader()
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
)
signal.signal(
signal.SIGINT, lambda *args: kill_program_completly(worker_process)
)
while True:
for filename in _iter_module_files():
try:
mtime = os.stat(filename).st_mtime
except OSError:
continue
old_time = mtimes.get(filename)
if old_time is None:
mtimes[filename] = mtime
continue
elif mtime > old_time:
kill_process_children(worker_process.pid)
worker_process.terminate()
worker_process = restart_with_reloader()
mtimes[filename] = mtime
break
sleep(sleep_interval)
|
[
"Watch project files, restart worker process if a change happened.\n\n :param sleep_interval: interval in second.\n :return: Nothing\n "
] |
Please provide a description of the function:def as_view(cls, *class_args, **class_kwargs):
def view(*args, **kwargs):
self = view.view_class(*class_args, **class_kwargs)
return self.dispatch_request(*args, **kwargs)
if cls.decorators:
view.__module__ = cls.__module__
for decorator in cls.decorators:
view = decorator(view)
view.view_class = cls
view.__doc__ = cls.__doc__
view.__module__ = cls.__module__
view.__name__ = cls.__name__
return view
|
[
"Return view function for use with the routing system, that\n dispatches request to appropriate handler method.\n "
] |
Please provide a description of the function:async def bounded_fetch(session, url):
async with sem, session.get(url) as response:
return await response.json()
|
[
"\n Use session object to perform 'get' request on url\n "
] |
Please provide a description of the function:def remove_entity_headers(headers, allowed=("content-location", "expires")):
allowed = set([h.lower() for h in allowed])
headers = {
header: value
for header, value in headers.items()
if not is_entity_header(header) or header.lower() in allowed
}
return headers
|
[
"\n Removes all the entity headers present in the headers given.\n According to RFC 2616 Section 10.3.5,\n Content-Location and Expires are allowed as for the\n \"strong cache validator\".\n https://tools.ietf.org/html/rfc2616#section-10.3.5\n\n returns the headers without the entity headers\n "
] |
Please provide a description of the function:def preserve_shape(func):
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
result = result.reshape(shape)
return result
return wrapped_function
|
[
"Preserve shape of the image."
] |
Please provide a description of the function:def preserve_channel_dim(func):
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(result, axis=-1)
return result
return wrapped_function
|
[
"Preserve dummy channel dim."
] |
Please provide a description of the function:def add_snow(img, snow_point, brightness_coeff):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
snow_point *= 127.5 # = 255 / 2
snow_point += 85 # = 255 / 3
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not in (np.uint8, np.float32):
raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype))
image_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
image_HLS = np.array(image_HLS, dtype=np.float32)
image_HLS[:, :, 1][image_HLS[:, :, 1] < snow_point] *= brightness_coeff
image_HLS[:, :, 1] = clip(image_HLS[:, :, 1], np.uint8, 255)
image_HLS = np.array(image_HLS, dtype=np.uint8)
image_RGB = cv2.cvtColor(image_HLS, cv2.COLOR_HLS2RGB)
if needs_float:
image_RGB = to_float(image_RGB, max_value=255)
return image_RGB
|
[
"Bleaches out pixels, mitation snow.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img:\n snow_point:\n brightness_coeff:\n\n Returns:\n\n "
] |
Please provide a description of the function:def add_fog(img, fog_coef, alpha_coef, haze_list):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not in (np.uint8, np.float32):
raise ValueError('Unexpected dtype {} for RandomFog augmentation'.format(input_dtype))
height, width = img.shape[:2]
hw = max(int(width // 3 * fog_coef), 10)
for haze_points in haze_list:
x, y = haze_points
overlay = img.copy()
output = img.copy()
alpha = alpha_coef * fog_coef
rad = hw // 2
point = (x + hw // 2, y + hw // 2)
cv2.circle(overlay, point, int(rad), (255, 255, 255), -1)
cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
img = output.copy()
image_rgb = cv2.blur(img, (hw // 10, hw // 10))
if needs_float:
image_rgb = to_float(image_rgb, max_value=255)
return image_rgb
|
[
"Add fog to the image.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n fog_coef (float):\n alpha_coef (float):\n haze_list (list):\n Returns:\n\n "
] |
Please provide a description of the function:def add_sun_flare(img, flare_center_x, flare_center_y, src_radius, src_color, circles):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not in (np.uint8, np.float32):
raise ValueError('Unexpected dtype {} for RandomSunFlareaugmentation'.format(input_dtype))
overlay = img.copy()
output = img.copy()
for (alpha, (x, y), rad3, (r_color, g_color, b_color)) in circles:
cv2.circle(overlay, (x, y), rad3, (r_color, g_color, b_color), -1)
cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
point = (int(flare_center_x), int(flare_center_y))
overlay = output.copy()
num_times = src_radius // 10
alpha = np.linspace(0.0, 1, num=num_times)
rad = np.linspace(1, src_radius, num=num_times)
for i in range(num_times):
cv2.circle(overlay, point, int(rad[i]), src_color, -1)
alp = alpha[num_times - i - 1] * alpha[num_times - i - 1] * alpha[num_times - i - 1]
cv2.addWeighted(overlay, alp, output, 1 - alp, 0, output)
image_rgb = output
if needs_float:
image_rgb = to_float(image_rgb, max_value=255)
return image_rgb
|
[
"Add sun flare.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n flare_center_x (float):\n flare_center_y (float):\n src_radius:\n src_color (int, int, int):\n circles (list):\n\n Returns:\n\n "
] |
Please provide a description of the function:def add_shadow(img, vertices_list):
non_rgb_warning(img)
input_dtype = img.dtype
needs_float = False
if input_dtype == np.float32:
img = from_float(img, dtype=np.dtype('uint8'))
needs_float = True
elif input_dtype not in (np.uint8, np.float32):
raise ValueError('Unexpected dtype {} for RandomSnow augmentation'.format(input_dtype))
image_hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
mask = np.zeros_like(img)
# adding all shadow polygons on empty mask, single 255 denotes only red channel
for vertices in vertices_list:
cv2.fillPoly(mask, vertices, 255)
# if red channel is hot, image's "Lightness" channel's brightness is lowered
red_max_value_ind = mask[:, :, 0] == 255
image_hls[:, :, 1][red_max_value_ind] = image_hls[:, :, 1][red_max_value_ind] * 0.5
image_rgb = cv2.cvtColor(image_hls, cv2.COLOR_HLS2RGB)
if needs_float:
image_rgb = to_float(image_rgb, max_value=255)
return image_rgb
|
[
"Add shadows to the image.\n\n From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library\n\n Args:\n img (np.array):\n vertices_list (list):\n\n Returns:\n\n "
] |
Please provide a description of the function:def optical_distortion(img, k=0, dx=0, dy=0, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101,
value=None):
height, width = img.shape[:2]
fx = width
fy = width
cx = width * 0.5 + dx
cy = height * 0.5 + dy
camera_matrix = np.array([[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]], dtype=np.float32)
distortion = np.array([k, k, 0, 0, 0], dtype=np.float32)
map1, map2 = cv2.initUndistortRectifyMap(camera_matrix, distortion, None, None, (width, height), cv2.CV_32FC1)
img = cv2.remap(img, map1, map2, interpolation=interpolation, borderMode=border_mode, borderValue=value)
return img
|
[
"Barrel / pincushion distortion. Unconventional augment.\n\n Reference:\n | https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion\n | https://stackoverflow.com/questions/10364201/image-transformation-in-opencv\n | https://stackoverflow.com/questions/2477774/correcting-fisheye-distortion-programmatically\n | http://www.coldvision.io/2017/03/02/advanced-lane-finding-using-opencv/\n "
] |
Please provide a description of the function:def grid_distortion(img, num_steps=10, xsteps=[], ysteps=[], interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None):
height, width = img.shape[:2]
x_step = width // num_steps
xx = np.zeros(width, np.float32)
prev = 0
for idx, x in enumerate(range(0, width, x_step)):
start = x
end = x + x_step
if end > width:
end = width
cur = width
else:
cur = prev + x_step * xsteps[idx]
xx[start:end] = np.linspace(prev, cur, end - start)
prev = cur
y_step = height // num_steps
yy = np.zeros(height, np.float32)
prev = 0
for idx, y in enumerate(range(0, height, y_step)):
start = y
end = y + y_step
if end > height:
end = height
cur = height
else:
cur = prev + y_step * ysteps[idx]
yy[start:end] = np.linspace(prev, cur, end - start)
prev = cur
map_x, map_y = np.meshgrid(xx, yy)
map_x = map_x.astype(np.float32)
map_y = map_y.astype(np.float32)
img = cv2.remap(img, map_x, map_y, interpolation=interpolation, borderMode=border_mode, borderValue=value)
return img
|
[
"\n Reference:\n http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html\n "
] |
Please provide a description of the function:def elastic_transform(image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, approximate=False):
if random_state is None:
random_state = np.random.RandomState(1234)
height, width = image.shape[:2]
# Random affine
center_square = np.float32((height, width)) // 2
square_size = min((height, width)) // 3
alpha = float(alpha)
sigma = float(sigma)
alpha_affine = float(alpha_affine)
pts1 = np.float32([center_square + square_size, [center_square[0] + square_size, center_square[1] - square_size],
center_square - square_size])
pts2 = pts1 + random_state.uniform(-alpha_affine, alpha_affine, size=pts1.shape).astype(np.float32)
matrix = cv2.getAffineTransform(pts1, pts2)
image = cv2.warpAffine(image, matrix, (width, height), flags=interpolation, borderMode=border_mode,
borderValue=value)
if approximate:
# Approximate computation smooth displacement map with a large enough kernel.
# On large images (512+) this is approximately 2X times faster
dx = (random_state.rand(height, width).astype(np.float32) * 2 - 1)
cv2.GaussianBlur(dx, (17, 17), sigma, dst=dx)
dx *= alpha
dy = (random_state.rand(height, width).astype(np.float32) * 2 - 1)
cv2.GaussianBlur(dy, (17, 17), sigma, dst=dy)
dy *= alpha
else:
dx = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha)
dy = np.float32(gaussian_filter((random_state.rand(height, width) * 2 - 1), sigma) * alpha)
x, y = np.meshgrid(np.arange(width), np.arange(height))
mapx = np.float32(x + dx)
mapy = np.float32(y + dy)
return cv2.remap(image, mapx, mapy, interpolation, borderMode=border_mode)
|
[
"Elastic deformation of images as described in [Simard2003]_ (with modifications).\n Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5\n\n .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\n Convolutional Neural Networks applied to Visual Document Analysis\", in\n Proc. of the International Conference on Document Analysis and\n Recognition, 2003.\n "
] |
Please provide a description of the function:def bbox_vflip(bbox, rows, cols):
x_min, y_min, x_max, y_max = bbox
return [x_min, 1 - y_max, x_max, 1 - y_min]
|
[
"Flip a bounding box vertically around the x-axis."
] |
Please provide a description of the function:def bbox_hflip(bbox, rows, cols):
x_min, y_min, x_max, y_max = bbox
return [1 - x_max, y_min, 1 - x_min, y_max]
|
[
"Flip a bounding box horizontally around the y-axis."
] |
Please provide a description of the function:def bbox_flip(bbox, d, rows, cols):
if d == 0:
bbox = bbox_vflip(bbox, rows, cols)
elif d == 1:
bbox = bbox_hflip(bbox, rows, cols)
elif d == -1:
bbox = bbox_hflip(bbox, rows, cols)
bbox = bbox_vflip(bbox, rows, cols)
else:
raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d))
return bbox
|
[
"Flip a bounding box either vertically, horizontally or both depending on the value of `d`.\n\n Raises:\n ValueError: if value of `d` is not -1, 0 or 1.\n\n "
] |
Please provide a description of the function:def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox
x1, y1, x2, y2 = crop_coords
cropped_bbox = [x_min - x1, y_min - y1, x_max - x1, y_max - y1]
return normalize_bbox(cropped_bbox, crop_height, crop_width)
|
[
"Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the\n required height and width of the crop.\n "
] |
Please provide a description of the function:def bbox_rot90(bbox, factor, rows, cols):
if factor < 0 or factor > 3:
raise ValueError('Parameter n must be in range [0;3]')
x_min, y_min, x_max, y_max = bbox
if factor == 1:
bbox = [y_min, 1 - x_max, y_max, 1 - x_min]
if factor == 2:
bbox = [1 - x_max, 1 - y_max, 1 - x_min, 1 - y_min]
if factor == 3:
bbox = [1 - y_max, x_min, 1 - y_min, x_max]
return bbox
|
[
"Rotates a bounding box by 90 degrees CCW (see np.rot90)\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def bbox_rotate(bbox, angle, rows, cols, interpolation):
scale = cols / float(rows)
x = np.array([bbox[0], bbox[2], bbox[2], bbox[0]])
y = np.array([bbox[1], bbox[1], bbox[3], bbox[3]])
x = x - 0.5
y = y - 0.5
angle = np.deg2rad(angle)
x_t = (np.cos(angle) * x * scale + np.sin(angle) * y) / scale
y_t = (-np.sin(angle) * x * scale + np.cos(angle) * y)
x_t = x_t + 0.5
y_t = y_t + 0.5
return [min(x_t), min(y_t), max(x_t), max(y_t)]
|
[
"Rotates a bounding box by angle degrees\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n angle (int): Angle of rotation in degrees\n rows (int): Image rows.\n cols (int): Image cols.\n interpolation (int): interpolation method.\n\n return a tuple (x_min, y_min, x_max, y_max)\n "
] |
Please provide a description of the function:def bbox_transpose(bbox, axis, rows, cols):
x_min, y_min, x_max, y_max = bbox
if axis != 0 and axis != 1:
raise ValueError('Axis must be either 0 or 1.')
if axis == 0:
bbox = [y_min, x_min, y_max, x_max]
if axis == 1:
bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min]
return bbox
|
[
"Transposes a bounding box along given axis.\n\n Args:\n bbox (tuple): A tuple (x_min, y_min, x_max, y_max).\n axis (int): 0 - main axis, 1 - secondary axis.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def keypoint_vflip(kp, rows, cols):
x, y, angle, scale = kp
c = math.cos(angle)
s = math.sin(angle)
angle = math.atan2(-s, c)
return [x, (rows - 1) - y, angle, scale]
|
[
"Flip a keypoint vertically around the x-axis."
] |
Please provide a description of the function:def keypoint_flip(bbox, d, rows, cols):
if d == 0:
bbox = keypoint_vflip(bbox, rows, cols)
elif d == 1:
bbox = keypoint_hflip(bbox, rows, cols)
elif d == -1:
bbox = keypoint_hflip(bbox, rows, cols)
bbox = keypoint_vflip(bbox, rows, cols)
else:
raise ValueError('Invalid d value {}. Valid values are -1, 0 and 1'.format(d))
return bbox
|
[
"Flip a keypoint either vertically, horizontally or both depending on the value of `d`.\n\n Raises:\n ValueError: if value of `d` is not -1, 0 or 1.\n\n "
] |
Please provide a description of the function:def keypoint_rot90(keypoint, factor, rows, cols, **params):
if factor < 0 or factor > 3:
raise ValueError('Parameter n must be in range [0;3]')
x, y, angle, scale = keypoint
if factor == 1:
keypoint = [y, (cols - 1) - x, angle - math.pi / 2, scale]
if factor == 2:
keypoint = [(cols - 1) - x, (rows - 1) - y, angle - math.pi, scale]
if factor == 3:
keypoint = [(rows - 1) - y, x, angle + math.pi / 2, scale]
return keypoint
|
[
"Rotates a keypoint by 90 degrees CCW (see np.rot90)\n\n Args:\n keypoint (tuple): A tuple (x, y, angle, scale).\n factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.\n rows (int): Image rows.\n cols (int): Image cols.\n "
] |
Please provide a description of the function:def keypoint_scale(keypoint, scale_x, scale_y, **params):
x, y, a, s = keypoint
return [x * scale_x, y * scale_y, a, s * max(scale_x, scale_y)]
|
[
"Scales a keypoint by scale_x and scale_y."
] |
Please provide a description of the function:def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols):
x, y, a, s = keypoint
x1, y1, x2, y2 = crop_coords
cropped_keypoint = [x - x1, y - y1, a, s]
return cropped_keypoint
|
[
"Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the\n required height and width of the crop.\n "
] |
Please provide a description of the function:def py3round(number):
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number))
|
[
"Unified rounding in all python versions."
] |
Please provide a description of the function:def apply(self, img, factor=0, **params):
return np.ascontiguousarray(np.rot90(img, factor))
|
[
"\n Args:\n factor (int): number of times the input will be rotated by 90 degrees.\n "
] |
Please provide a description of the function:def normalize_bbox(bbox, rows, cols):
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
x_min, y_min, x_max, y_max = bbox[:4]
normalized_bbox = [x_min / cols, y_min / rows, x_max / cols, y_max / rows]
return normalized_bbox + list(bbox[4:])
|
[
"Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates\n by image height.\n "
] |
Please provide a description of the function:def denormalize_bbox(bbox, rows, cols):
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
x_min, y_min, x_max, y_max = bbox[:4]
denormalized_bbox = [x_min * cols, y_min * rows, x_max * cols, y_max * rows]
return denormalized_bbox + list(bbox[4:])
|
[
"Denormalize coordinates of a bounding box. Multiply x-coordinates by image width and y-coordinates\n by image height. This is an inverse operation for :func:`~albumentations.augmentations.bbox.normalize_bbox`.\n "
] |
Please provide a description of the function:def normalize_bboxes(bboxes, rows, cols):
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes]
|
[
"Normalize a list of bounding boxes."
] |
Please provide a description of the function:def denormalize_bboxes(bboxes, rows, cols):
return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
|
[
"Denormalize a list of bounding boxes."
] |
Please provide a description of the function:def calculate_bbox_area(bbox, rows, cols):
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_max = bbox[:4]
area = (x_max - x_min) * (y_max - y_min)
return area
|
[
"Calculate the area of a bounding box in pixels."
] |
Please provide a description of the function:def filter_bboxes_by_visibility(original_shape, bboxes, transformed_shape, transformed_bboxes,
threshold=0., min_area=0.):
img_height, img_width = original_shape[:2]
transformed_img_height, transformed_img_width = transformed_shape[:2]
visible_bboxes = []
for bbox, transformed_bbox in zip(bboxes, transformed_bboxes):
if not all(0.0 <= value <= 1.0 for value in transformed_bbox[:4]):
continue
bbox_area = calculate_bbox_area(bbox, img_height, img_width)
transformed_bbox_area = calculate_bbox_area(transformed_bbox, transformed_img_height, transformed_img_width)
if transformed_bbox_area < min_area:
continue
visibility = transformed_bbox_area / bbox_area
if visibility >= threshold:
visible_bboxes.append(transformed_bbox)
return visible_bboxes
|
[
"Filter bounding boxes and return only those boxes whose visibility after transformation is above\n the threshold and minimal area of bounding box in pixels is more then min_area.\n\n Args:\n original_shape (tuple): original image shape\n bboxes (list): original bounding boxes\n transformed_shape(tuple): transformed image\n transformed_bboxes (list): transformed bounding boxes\n threshold (float): visibility threshold. Should be a value in the range [0.0, 1.0].\n min_area (float): Minimal area threshold.\n "
] |
Please provide a description of the function:def convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity=False):
if source_format not in {'coco', 'pascal_voc'}:
raise ValueError(
"Unknown source_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(source_format)
)
if source_format == 'coco':
x_min, y_min, width, height = bbox[:4]
x_max = x_min + width
y_max = y_min + height
else:
x_min, y_min, x_max, y_max = bbox[:4]
bbox = [x_min, y_min, x_max, y_max] + list(bbox[4:])
bbox = normalize_bbox(bbox, rows, cols)
if check_validity:
check_bbox(bbox)
return bbox
|
[
"Convert a bounding box from a format specified in `source_format` to the format used by albumentations:\n normalized coordinates of bottom-left and top-right corners of the bounding box in a form of\n `[x_min, y_min, x_max, y_max]` e.g. `[0.15, 0.27, 0.67, 0.5]`.\n\n Args:\n bbox (list): bounding box\n source_format (str): format of the bounding box. Should be 'coco' or 'pascal_voc'.\n check_validity (bool): check if all boxes are valid boxes\n rows (int): image height\n cols (int): image width\n\n Note:\n The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200].\n The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212].\n\n Raises:\n ValueError: if `target_format` is not equal to `coco` or `pascal_voc`.\n\n "
] |
Please provide a description of the function:def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
if target_format not in {'coco', 'pascal_voc'}:
raise ValueError(
"Unknown target_format {}. Supported formats are: 'coco' and 'pascal_voc'".format(target_format)
)
if check_validity:
check_bbox(bbox)
bbox = denormalize_bbox(bbox, rows, cols)
if target_format == 'coco':
x_min, y_min, x_max, y_max = bbox[:4]
width = x_max - x_min
height = y_max - y_min
bbox = [x_min, y_min, width, height] + list(bbox[4:])
return bbox
|
[
"Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.\n\n Args:\n bbox (list): bounding box with coordinates in the format used by albumentations\n target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.\n rows (int): image height\n cols (int): image width\n check_validity (bool): check if all boxes are valid boxes\n\n Note:\n The `coco` format of a bounding box looks like `[x_min, y_min, width, height]`, e.g. [97, 12, 150, 200].\n The `pascal_voc` format of a bounding box looks like `[x_min, y_min, x_max, y_max]`, e.g. [97, 12, 247, 212].\n\n Raises:\n ValueError: if `target_format` is not equal to `coco` or `pascal_voc`.\n\n "
] |
Please provide a description of the function:def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox in bboxes]
|
[
"Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations\n "
] |
Please provide a description of the function:def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):
return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
|
[
"Convert a list of bounding boxes from the format used by albumentations to a format, specified\n in `target_format`.\n\n Args:\n bboxes (list): List of bounding box with coordinates in the format used by albumentations\n target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.\n rows (int): image height\n cols (int): image width\n check_validity (bool): check if all boxes are valid boxes\n "
] |
Please provide a description of the function:def check_bbox(bbox):
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
'to be in the range [0.0, 1.0], got {value}.'.format(
bbox=bbox,
name=name,
value=value,
)
)
x_min, y_min, x_max, y_max = bbox[:4]
if x_max <= x_min:
raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format(
bbox=bbox,
))
if y_max <= y_min:
raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format(
bbox=bbox,
))
|
[
"Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums"
] |
Please provide a description of the function:def filter_bboxes(bboxes, rows, cols, min_area=0., min_visibility=0.):
resulting_boxes = []
for bbox in bboxes:
transformed_box_area = calculate_bbox_area(bbox, rows, cols)
bbox[:4] = np.clip(bbox[:4], 0, 1.)
clipped_box_area = calculate_bbox_area(bbox, rows, cols)
if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visibility:
continue
else:
bbox[:4] = np.clip(bbox[:4], 0, 1.)
if calculate_bbox_area(bbox, rows, cols) <= min_area:
continue
resulting_boxes.append(bbox)
return resulting_boxes
|
[
"Remove bounding boxes that either lie outside of the visible area by more then min_visibility\n or whose area in pixels is under the threshold set by `min_area`. Also it crops boxes to final image size.\n\n Args:\n bboxes (list): List of bounding box with coordinates in the format used by albumentations\n rows (int): Image rows.\n cols (int): Image cols.\n min_area (float): minimum area of a bounding box. All bounding boxes whose visible area in pixels\n is less than this value will be removed. Default: 0.0.\n min_visibility (float): minimum fraction of area for a bounding box to remain this box in list. Default: 0.0.\n "
] |
Please provide a description of the function:def union_of_bboxes(height, width, bboxes, erosion_rate=0.0, to_int=False):
x1, y1 = width, height
x2, y2 = 0, 0
for b in bboxes:
w, h = b[2] - b[0], b[3] - b[1]
lim_x1, lim_y1 = b[0] + erosion_rate * w, b[1] + erosion_rate * h
lim_x2, lim_y2 = b[2] - erosion_rate * w, b[3] - erosion_rate * h
x1, y1 = np.min([x1, lim_x1]), np.min([y1, lim_y1])
x2, y2 = np.max([x2, lim_x2]), np.max([y2, lim_y2])
return x1, y1, x2, y2
|
[
"Calculate union of bounding boxes.\n\n Args:\n height (float): Height of image or space.\n width (float): Width of image or space.\n bboxes (list): List like bounding boxes. Format is `[x_min, y_min, x_max, y_max]`.\n erosion_rate (float): How much each bounding box can be shrinked, useful for erosive cropping.\n Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox to lose its volume.\n "
] |
Please provide a description of the function:def to_tuple(param, low=None, bias=None):
if low is not None and bias is not None:
raise ValueError('Arguments low and bias are mutually exclusive')
if param is None:
return param
if isinstance(param, (int, float)):
if low is None:
param = - param, + param
else:
param = (low, param) if low < param else (param, low)
elif isinstance(param, (list, tuple)):
param = tuple(param)
else:
raise ValueError('Argument param must be either scalar (int,float) or tuple')
if bias is not None:
return tuple([bias + x for x in param])
return tuple(param)
|
[
"Convert input argument to min-max tuple\n Args:\n param (scalar, tuple or list of 2+ elements): Input value.\n If value is scalar, return value would be (offset - value, offset + value).\n If value is tuple, return value would be value + offset (broadcasted).\n low: Second element of tuple can be passed as optional argument\n bias: An offset factor added to each element\n "
] |
Please provide a description of the function:def check_keypoint(kp, rows, cols):
for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]):
if not 0 <= value < size:
raise ValueError(
'Expected {name} for keypoint {kp} '
'to be in the range [0.0, {size}], got {value}.'.format(
kp=kp,
name=name,
value=value,
size=size
)
)
|
[
"Check if keypoint coordinates are in range [0, 1)"
] |
Please provide a description of the function:def check_keypoints(keypoints, rows, cols):
for kp in keypoints:
check_keypoint(kp, rows, cols)
|
[
"Check if keypoints boundaries are in range [0, 1)"
] |
Please provide a description of the function:def start(check_time: int = 500) -> None:
io_loop = ioloop.IOLoop.current()
if io_loop in _io_loops:
return
_io_loops[io_loop] = True
if len(_io_loops) > 1:
gen_log.warning("tornado.autoreload started more than once in the same process")
modify_times = {} # type: Dict[str, float]
callback = functools.partial(_reload_on_update, modify_times)
scheduler = ioloop.PeriodicCallback(callback, check_time)
scheduler.start()
|
[
"Begins watching source files for changes.\n\n .. versionchanged:: 5.0\n The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n "
] |
Please provide a description of the function:def main() -> None:
# Remember that we were launched with autoreload as main.
# The main module can be tricky; set the variables both in our globals
# (which may be __main__) and the real importable version.
import tornado.autoreload
global _autoreload_is_main
global _original_argv, _original_spec
tornado.autoreload._autoreload_is_main = _autoreload_is_main = True
original_argv = sys.argv
tornado.autoreload._original_argv = _original_argv = original_argv
original_spec = getattr(sys.modules["__main__"], "__spec__", None)
tornado.autoreload._original_spec = _original_spec = original_spec
sys.argv = sys.argv[:]
if len(sys.argv) >= 3 and sys.argv[1] == "-m":
mode = "module"
module = sys.argv[2]
del sys.argv[1:3]
elif len(sys.argv) >= 2:
mode = "script"
script = sys.argv[1]
sys.argv = sys.argv[1:]
else:
print(_USAGE, file=sys.stderr)
sys.exit(1)
try:
if mode == "module":
import runpy
runpy.run_module(module, run_name="__main__", alter_sys=True)
elif mode == "script":
with open(script) as f:
# Execute the script in our namespace instead of creating
# a new one so that something that tries to import __main__
# (e.g. the unittest module) will see names defined in the
# script instead of just those defined in this module.
global __file__
__file__ = script
# If __package__ is defined, imports may be incorrectly
# interpreted as relative to this module.
global __package__
del __package__
exec_in(f.read(), globals(), globals())
except SystemExit as e:
logging.basicConfig()
gen_log.info("Script exited with status %s", e.code)
except Exception as e:
logging.basicConfig()
gen_log.warning("Script exited with uncaught exception", exc_info=True)
# If an exception occurred at import time, the file with the error
# never made it into sys.modules and so we won't know to watch it.
# Just to make sure we've covered everything, walk the stack trace
# from the exception and watch every file.
for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]):
watch(filename)
if isinstance(e, SyntaxError):
# SyntaxErrors are special: their innermost stack frame is fake
# so extract_tb won't see it and we have to get the filename
# from the exception object.
watch(e.filename)
else:
logging.basicConfig()
gen_log.info("Script exited normally")
# restore sys.argv so subsequent executions will include autoreload
sys.argv = original_argv
if mode == "module":
# runpy did a fake import of the module as __main__, but now it's
# no longer in sys.modules. Figure out where it is and watch it.
loader = pkgutil.get_loader(module)
if loader is not None:
watch(loader.get_filename()) # type: ignore
wait()
|
[
"Command-line wrapper to re-run a script whenever its source changes.\n\n Scripts may be specified by filename or module name::\n\n python -m tornado.autoreload -m tornado.test.runtests\n python -m tornado.autoreload tornado/test/runtests.py\n\n Running a script with this wrapper is similar to calling\n `tornado.autoreload.wait` at the end of the script, but this wrapper\n can catch import-time problems like syntax errors that would otherwise\n prevent the script from reaching its call to `wait`.\n "
] |
Please provide a description of the function:def split(
addrinfo: List[Tuple]
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr in addrinfo:
if af == primary_af:
primary.append((af, addr))
else:
secondary.append((af, addr))
return primary, secondary
|
[
"Partition the ``addrinfo`` list by address family.\n\n Returns two lists. The first list contains the first entry from\n ``addrinfo`` and all others with the same family, and the\n second list contains all other addresses (normally one list will\n be AF_INET and the other AF_INET6, although non-standard resolvers\n may return additional families).\n "
] |
Please provide a description of the function:async def connect(
self,
host: str,
port: int,
af: socket.AddressFamily = socket.AF_UNSPEC,
ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None,
max_buffer_size: int = None,
source_ip: str = None,
source_port: int = None,
timeout: Union[float, datetime.timedelta] = None,
) -> IOStream:
if timeout is not None:
if isinstance(timeout, numbers.Real):
timeout = IOLoop.current().time() + timeout
elif isinstance(timeout, datetime.timedelta):
timeout = IOLoop.current().time() + timeout.total_seconds()
else:
raise TypeError("Unsupported timeout %r" % timeout)
if timeout is not None:
addrinfo = await gen.with_timeout(
timeout, self.resolver.resolve(host, port, af)
)
else:
addrinfo = await self.resolver.resolve(host, port, af)
connector = _Connector(
addrinfo,
functools.partial(
self._create_stream,
max_buffer_size,
source_ip=source_ip,
source_port=source_port,
),
)
af, addr, stream = await connector.start(connect_timeout=timeout)
# TODO: For better performance we could cache the (af, addr)
# information here and re-use it on subsequent connections to
# the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
if ssl_options is not None:
if timeout is not None:
stream = await gen.with_timeout(
timeout,
stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
),
)
else:
stream = await stream.start_tls(
False, ssl_options=ssl_options, server_hostname=host
)
return stream
|
[
"Connect to the given host and port.\n\n Asynchronously returns an `.IOStream` (or `.SSLIOStream` if\n ``ssl_options`` is not None).\n\n Using the ``source_ip`` kwarg, one can specify the source\n IP address to use when establishing the connection.\n In case the user needs to resolve and\n use a specific interface, it has to be handled outside\n of Tornado as this depends very much on the platform.\n\n Raises `TimeoutError` if the input future does not complete before\n ``timeout``, which may be specified in any form allowed by\n `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time\n relative to `.IOLoop.time`)\n\n Similarly, when the user requires a certain source port, it can\n be specified using the ``source_port`` arg.\n\n .. versionchanged:: 4.5\n Added the ``source_ip`` and ``source_port`` arguments.\n\n .. versionchanged:: 5.0\n Added the ``timeout`` argument.\n "
] |
Please provide a description of the function:async def close_all_connections(self) -> None:
while self._connections:
# Peek at an arbitrary element of the set
conn = next(iter(self._connections))
await conn.close()
|
[
"Close all open connections and asynchronously wait for them to finish.\n\n This method is used in combination with `~.TCPServer.stop` to\n support clean shutdowns (especially for unittests). Typical\n usage would call ``stop()`` first to stop accepting new\n connections, then ``await close_all_connections()`` to wait for\n existing connections to finish.\n\n This method does not currently close open websocket connections.\n\n Note that this method is a coroutine and must be caled with ``await``.\n\n "
] |
Please provide a description of the function:def _apply_xheaders(self, headers: httputil.HTTPHeaders) -> None:
# Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
# Skip trusted downstream hosts in X-Forwarded-For list
for ip in (cand.strip() for cand in reversed(ip.split(","))):
if ip not in self.trusted_downstream:
break
ip = headers.get("X-Real-Ip", ip)
if netutil.is_valid_ip(ip):
self.remote_ip = ip
# AWS uses X-Forwarded-Proto
proto_header = headers.get(
"X-Scheme", headers.get("X-Forwarded-Proto", self.protocol)
)
if proto_header:
# use only the last proto entry if there is more than one
# TODO: support trusting mutiple layers of proxied protocol
proto_header = proto_header.split(",")[-1].strip()
if proto_header in ("http", "https"):
self.protocol = proto_header
|
[
"Rewrite the ``remote_ip`` and ``protocol`` fields."
] |
Please provide a description of the function:def _unapply_xheaders(self) -> None:
self.remote_ip = self._orig_remote_ip
self.protocol = self._orig_protocol
|
[
"Undo changes from `_apply_xheaders`.\n\n Xheaders are per-request so they should not leak to the next\n request on the same connection.\n "
] |
Please provide a description of the function:def set_default_locale(code: str) -> None:
global _default_locale
global _supported_locales
_default_locale = code
_supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
|
[
"Sets the default locale.\n\n The default locale is assumed to be the language used for all strings\n in the system. The translations loaded from disk are mappings from\n the default locale to the destination locale. Consequently, you don't\n need to create a translation file for the default locale.\n "
] |
Please provide a description of the function:def load_translations(directory: str, encoding: str = None) -> None:
global _translations
global _supported_locales
_translations = {}
for path in os.listdir(directory):
if not path.endswith(".csv"):
continue
locale, extension = path.split(".")
if not re.match("[a-z]+(_[A-Z]+)?$", locale):
gen_log.error(
"Unrecognized locale %r (path: %s)",
locale,
os.path.join(directory, path),
)
continue
full_path = os.path.join(directory, path)
if encoding is None:
# Try to autodetect encoding based on the BOM.
with open(full_path, "rb") as bf:
data = bf.read(len(codecs.BOM_UTF16_LE))
if data in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
encoding = "utf-16"
else:
# utf-8-sig is "utf-8 with optional BOM". It's discouraged
# in most cases but is common with CSV files because Excel
# cannot read utf-8 files without a BOM.
encoding = "utf-8-sig"
# python 3: csv.reader requires a file open in text mode.
# Specify an encoding to avoid dependence on $LANG environment variable.
with open(full_path, encoding=encoding) as f:
_translations[locale] = {}
for i, row in enumerate(csv.reader(f)):
if not row or len(row) < 2:
continue
row = [escape.to_unicode(c).strip() for c in row]
english, translation = row[:2]
if len(row) > 2:
plural = row[2] or "unknown"
else:
plural = "unknown"
if plural not in ("plural", "singular", "unknown"):
gen_log.error(
"Unrecognized plural indicator %r in %s line %d",
plural,
path,
i + 1,
)
continue
_translations[locale].setdefault(plural, {})[english] = translation
_supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
gen_log.debug("Supported locales: %s", sorted(_supported_locales))
|
[
"Loads translations from CSV files in a directory.\n\n Translations are strings with optional Python-style named placeholders\n (e.g., ``My name is %(name)s``) and their associated translations.\n\n The directory should have translation files of the form ``LOCALE.csv``,\n e.g. ``es_GT.csv``. The CSV files should have two or three columns: string,\n translation, and an optional plural indicator. Plural indicators should\n be one of \"plural\" or \"singular\". A given string can have both singular\n and plural forms. For example ``%(name)s liked this`` may have a\n different verb conjugation depending on whether %(name)s is one\n name or a list of names. There should be two rows in the CSV file for\n that string, one with plural indicator \"singular\", and one \"plural\".\n For strings with no verbs that would change on translation, simply\n use \"unknown\" or the empty string (or don't include the column at all).\n\n The file is read using the `csv` module in the default \"excel\" dialect.\n In this format there should not be spaces after the commas.\n\n If no ``encoding`` parameter is given, the encoding will be\n detected automatically (among UTF-8 and UTF-16) if the file\n contains a byte-order marker (BOM), defaulting to UTF-8 if no BOM\n is present.\n\n Example translation ``es_LA.csv``::\n\n \"I love you\",\"Te amo\"\n \"%(name)s liked this\",\"A %(name)s les gustó esto\",\"plural\"\n \"%(name)s liked this\",\"A %(name)s le gustó esto\",\"singular\"\n\n .. versionchanged:: 4.3\n Added ``encoding`` parameter. Added support for BOM-based encoding\n detection, UTF-16, and UTF-8-with-BOM.\n "
] |
Please provide a description of the function:def load_gettext_translations(directory: str, domain: str) -> None:
global _translations
global _supported_locales
global _use_gettext
_translations = {}
for lang in os.listdir(directory):
if lang.startswith("."):
continue # skip .svn, etc
if os.path.isfile(os.path.join(directory, lang)):
continue
try:
os.stat(os.path.join(directory, lang, "LC_MESSAGES", domain + ".mo"))
_translations[lang] = gettext.translation(
domain, directory, languages=[lang]
)
except Exception as e:
gen_log.error("Cannot load translation for '%s': %s", lang, str(e))
continue
_supported_locales = frozenset(list(_translations.keys()) + [_default_locale])
_use_gettext = True
gen_log.debug("Supported locales: %s", sorted(_supported_locales))
|
[
"Loads translations from `gettext`'s locale tree\n\n Locale tree is similar to system's ``/usr/share/locale``, like::\n\n {directory}/{lang}/LC_MESSAGES/{domain}.mo\n\n Three steps are required to have your app translated:\n\n 1. Generate POT translation file::\n\n xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html etc\n\n 2. Merge against existing POT file::\n\n msgmerge old.po mydomain.po > new.po\n\n 3. Compile::\n\n msgfmt mydomain.po -o {directory}/pt_BR/LC_MESSAGES/mydomain.mo\n "
] |
Please provide a description of the function:def get_closest(cls, *locale_codes: str) -> "Locale":
for code in locale_codes:
if not code:
continue
code = code.replace("-", "_")
parts = code.split("_")
if len(parts) > 2:
continue
elif len(parts) == 2:
code = parts[0].lower() + "_" + parts[1].upper()
if code in _supported_locales:
return cls.get(code)
if parts[0].lower() in _supported_locales:
return cls.get(parts[0].lower())
return cls.get(_default_locale)
|
[
"Returns the closest match for the given locale code."
] |
Please provide a description of the function:def get(cls, code: str) -> "Locale":
if code not in cls._cache:
assert code in _supported_locales
translations = _translations.get(code, None)
if translations is None:
locale = CSVLocale(code, {}) # type: Locale
elif _use_gettext:
locale = GettextLocale(code, translations)
else:
locale = CSVLocale(code, translations)
cls._cache[code] = locale
return cls._cache[code]
|
[
"Returns the Locale for the given locale code.\n\n If it is not supported, we raise an exception.\n "
] |
Please provide a description of the function:def translate(
self, message: str, plural_message: str = None, count: int = None
) -> str:
raise NotImplementedError()
|
[
"Returns the translation for the given message for this locale.\n\n If ``plural_message`` is given, you must also provide\n ``count``. We return ``plural_message`` when ``count != 1``,\n and we return the singular form for the given message when\n ``count == 1``.\n "
] |
Please provide a description of the function:def format_date(
self,
date: Union[int, float, datetime.datetime],
gmt_offset: int = 0,
relative: bool = True,
shorter: bool = False,
full_format: bool = False,
) -> str:
if isinstance(date, (int, float)):
date = datetime.datetime.utcfromtimestamp(date)
now = datetime.datetime.utcnow()
if date > now:
if relative and (date - now).seconds < 60:
# Due to click skew, things are some things slightly
# in the future. Round timestamps in the immediate
# future down to now in relative mode.
date = now
else:
# Otherwise, future dates always use the full format.
full_format = True
local_date = date - datetime.timedelta(minutes=gmt_offset)
local_now = now - datetime.timedelta(minutes=gmt_offset)
local_yesterday = local_now - datetime.timedelta(hours=24)
difference = now - date
seconds = difference.seconds
days = difference.days
_ = self.translate
format = None
if not full_format:
if relative and days == 0:
if seconds < 50:
return _("1 second ago", "%(seconds)d seconds ago", seconds) % {
"seconds": seconds
}
if seconds < 50 * 60:
minutes = round(seconds / 60.0)
return _("1 minute ago", "%(minutes)d minutes ago", minutes) % {
"minutes": minutes
}
hours = round(seconds / (60.0 * 60))
return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours}
if days == 0:
format = _("%(time)s")
elif days == 1 and local_date.day == local_yesterday.day and relative:
format = _("yesterday") if shorter else _("yesterday at %(time)s")
elif days < 5:
format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s")
elif days < 334: # 11mo, since confusing for same month last year
format = (
_("%(month_name)s %(day)s")
if shorter
else _("%(month_name)s %(day)s at %(time)s")
)
if format is None:
format = (
_("%(month_name)s %(day)s, %(year)s")
if shorter
else _("%(month_name)s %(day)s, %(year)s at %(time)s")
)
tfhour_clock = self.code not in ("en", "en_US", "zh_CN")
if tfhour_clock:
str_time = "%d:%02d" % (local_date.hour, local_date.minute)
elif self.code == "zh_CN":
str_time = "%s%d:%02d" % (
(u"\u4e0a\u5348", u"\u4e0b\u5348")[local_date.hour >= 12],
local_date.hour % 12 or 12,
local_date.minute,
)
else:
str_time = "%d:%02d %s" % (
local_date.hour % 12 or 12,
local_date.minute,
("am", "pm")[local_date.hour >= 12],
)
return format % {
"month_name": self._months[local_date.month - 1],
"weekday": self._weekdays[local_date.weekday()],
"day": str(local_date.day),
"year": str(local_date.year),
"time": str_time,
}
|
[
"Formats the given date (which should be GMT).\n\n By default, we return a relative time (e.g., \"2 minutes ago\"). You\n can return an absolute date string with ``relative=False``.\n\n You can force a full format date (\"July 10, 1980\") with\n ``full_format=True``.\n\n This method is primarily intended for dates in the past.\n For dates in the future, we fall back to full format.\n "
] |
Please provide a description of the function:def format_day(
self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True
) -> bool:
local_date = date - datetime.timedelta(minutes=gmt_offset)
_ = self.translate
if dow:
return _("%(weekday)s, %(month_name)s %(day)s") % {
"month_name": self._months[local_date.month - 1],
"weekday": self._weekdays[local_date.weekday()],
"day": str(local_date.day),
}
else:
return _("%(month_name)s %(day)s") % {
"month_name": self._months[local_date.month - 1],
"day": str(local_date.day),
}
|
[
"Formats the given date as a day of week.\n\n Example: \"Monday, January 22\". You can remove the day of week with\n ``dow=False``.\n "
] |
Please provide a description of the function:def list(self, parts: Any) -> str:
_ = self.translate
if len(parts) == 0:
return ""
if len(parts) == 1:
return parts[0]
comma = u" \u0648 " if self.code.startswith("fa") else u", "
return _("%(commas)s and %(last)s") % {
"commas": comma.join(parts[:-1]),
"last": parts[len(parts) - 1],
}
|
[
"Returns a comma-separated list for the given list of parts.\n\n The format is, e.g., \"A, B and C\", \"A and B\" or just \"A\" for lists\n of size 1.\n "
] |
Please provide a description of the function:def friendly_number(self, value: int) -> str:
if self.code not in ("en", "en_US"):
return str(value)
s = str(value)
parts = []
while s:
parts.append(s[-3:])
s = s[:-3]
return ",".join(reversed(parts))
|
[
"Returns a comma-separated number for the given integer."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.