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
IndentingFormatter.get_message_start
(self, formatted, levelno)
Return the start of the formatted log message (not counting the prefix to add to each line).
Return the start of the formatted log message (not counting the prefix to add to each line).
def get_message_start(self, formatted, levelno): # type: (str, int) -> str """ Return the start of the formatted log message (not counting the prefix to add to each line). """ if levelno < logging.WARNING: return "" if formatted.startswith(DEPRECATION_...
[ "def", "get_message_start", "(", "self", ",", "formatted", ",", "levelno", ")", ":", "# type: (str, int) -> str", "if", "levelno", "<", "logging", ".", "WARNING", ":", "return", "\"\"", "if", "formatted", ".", "startswith", "(", "DEPRECATION_MSG_PREFIX", ")", ":...
[ 107, 4 ]
[ 122, 24 ]
python
en
['en', 'error', 'th']
False
IndentingFormatter.format
(self, record)
Calls the standard formatter, but will indent all of the log message lines by our current indentation level.
Calls the standard formatter, but will indent all of the log message lines by our current indentation level.
def format(self, record): # type: (logging.LogRecord) -> str """ Calls the standard formatter, but will indent all of the log message lines by our current indentation level. """ formatted = super().format(record) message_start = self.get_message_start(formatted, r...
[ "def", "format", "(", "self", ",", "record", ")", ":", "# type: (logging.LogRecord) -> str", "formatted", "=", "super", "(", ")", ".", "format", "(", "record", ")", "message_start", "=", "self", ".", "get_message_start", "(", "formatted", ",", "record", ".", ...
[ 124, 4 ]
[ 139, 24 ]
python
en
['en', 'error', 'th']
False
ColorizedStreamHandler._using_stdout
(self)
Return whether the handler is using sys.stdout.
Return whether the handler is using sys.stdout.
def _using_stdout(self): # type: () -> bool """ Return whether the handler is using sys.stdout. """ if WINDOWS and colorama: # Then self.stream is an AnsiToWin32 object. stream = cast(colorama.AnsiToWin32, self.stream) return stream.wrapped is ...
[ "def", "_using_stdout", "(", "self", ")", ":", "# type: () -> bool", "if", "WINDOWS", "and", "colorama", ":", "# Then self.stream is an AnsiToWin32 object.", "stream", "=", "cast", "(", "colorama", ".", "AnsiToWin32", ",", "self", ".", "stream", ")", "return", "st...
[ 171, 4 ]
[ 181, 40 ]
python
en
['en', 'error', 'th']
False
RequirementSet.__init__
(self, check_supported_wheels: bool = True)
Create a RequirementSet.
Create a RequirementSet.
def __init__(self, check_supported_wheels: bool = True) -> None: """Create a RequirementSet. """ self.requirements: Dict[str, InstallRequirement] = OrderedDict() self.check_supported_wheels = check_supported_wheels self.unnamed_requirements: List[InstallRequirement] = []
[ "def", "__init__", "(", "self", ",", "check_supported_wheels", ":", "bool", "=", "True", ")", "->", "None", ":", "self", ".", "requirements", ":", "Dict", "[", "str", ",", "InstallRequirement", "]", "=", "OrderedDict", "(", ")", "self", ".", "check_support...
[ 16, 4 ]
[ 23, 64 ]
python
en
['en', 'en', 'en']
True
RequirementSet.add_requirement
( self, install_req: InstallRequirement, parent_req_name: Optional[str] = None, extras_requested: Optional[Iterable[str]] = None )
Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside t...
Add install_req as a requirement to install.
def add_requirement( self, install_req: InstallRequirement, parent_req_name: Optional[str] = None, extras_requested: Optional[Iterable[str]] = None ) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]]: """Add install_req as a requirement to install. :pa...
[ "def", "add_requirement", "(", "self", ",", "install_req", ":", "InstallRequirement", ",", "parent_req_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "extras_requested", ":", "Optional", "[", "Iterable", "[", "str", "]", "]", "=", "None", ")", ...
[ 55, 4 ]
[ 169, 43 ]
python
en
['en', 'en', 'en']
True
MailHandler.get_opt
(self, option, optiontype=str)
Parse an option from config.ini
Parse an option from config.ini
def get_opt(self, option, optiontype=str): "Parse an option from config.ini" log.debug("Querying option: {}.".format(option)) section = self.account if not self.config.has_section(section): section = "DEFAULT" log.debug("Section {} not found. Using DEFAULT".format...
[ "def", "get_opt", "(", "self", ",", "option", ",", "optiontype", "=", "str", ")", ":", "log", ".", "debug", "(", "\"Querying option: {}.\"", ".", "format", "(", "option", ")", ")", "section", "=", "self", ".", "account", "if", "not", "self", ".", "conf...
[ 67, 4 ]
[ 84, 73 ]
python
en
['en', 'en', 'en']
True
MailHandler.print_options
(self)
Print all available options. For debugging purposes.
Print all available options. For debugging purposes.
def print_options(self): "Print all available options. For debugging purposes." for i in self.config.options(self.account): print i + ":", self.config.get(self.account, i)
[ "def", "print_options", "(", "self", ")", ":", "for", "i", "in", "self", ".", "config", ".", "options", "(", "self", ".", "account", ")", ":", "print", "i", "+", "\":\"", ",", "self", ".", "config", ".", "get", "(", "self", ".", "account", ",", "...
[ 86, 4 ]
[ 89, 59 ]
python
en
['en', 'en', 'en']
True
MailHandler.get_mail
(self)
Get the mail. Uses poplib as GMX Freemail does not allow imap.
Get the mail. Uses poplib as GMX Freemail does not allow imap.
def get_mail(self): "Get the mail. Uses poplib as GMX Freemail does not allow imap." log.info("Getting mail for {}".format(self.account)) if not self.username: self.username = self.account password = getpass("Password for {}: ".format(self.username)) server = self.g...
[ "def", "get_mail", "(", "self", ")", ":", "log", ".", "info", "(", "\"Getting mail for {}\"", ".", "format", "(", "self", ".", "account", ")", ")", "if", "not", "self", ".", "username", ":", "self", ".", "username", "=", "self", ".", "account", "passwo...
[ 91, 4 ]
[ 129, 22 ]
python
en
['en', 'en', 'en']
True
MailHandler.send_mail
(self, recipient, header, message, sign, encrypt, attachkey, dryrun)
Sends a mail via SMTP.
Sends a mail via SMTP.
def send_mail(self, recipient, header, message, sign, encrypt, attachkey, dryrun): "Sends a mail via SMTP." log.info("Sending mail to {} ({}). Sign/Encrypt/AttachKey: {}/{}/{}." .format(recipient, header, sign, encrypt, attachkey)) recipients = {i for i in rec...
[ "def", "send_mail", "(", "self", ",", "recipient", ",", "header", ",", "message", ",", "sign", ",", "encrypt", ",", "attachkey", ",", "dryrun", ")", ":", "log", ".", "info", "(", "\"Sending mail to {} ({}). Sign/Encrypt/AttachKey: {}/{}/{}.\"", ".", "format", "(...
[ 132, 4 ]
[ 289, 22 ]
python
en
['en', 'pt', 'en']
True
FallbackStorage._get
(self, *args, **kwargs)
Get a single list of messages from all storage backends.
Get a single list of messages from all storage backends.
def _get(self, *args, **kwargs): """ Get a single list of messages from all storage backends. """ all_messages = [] for storage in self.storages: messages, all_retrieved = storage._get() # If the backend hasn't been used, no more retrieval is necessary. ...
[ "def", "_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_messages", "=", "[", "]", "for", "storage", "in", "self", ".", "storages", ":", "messages", ",", "all_retrieved", "=", "storage", ".", "_get", "(", ")", "# If the b...
[ 18, 4 ]
[ 35, 42 ]
python
en
['en', 'error', 'th']
False
FallbackStorage._store
(self, messages, response, *args, **kwargs)
Store the messages and return any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend.
Store the messages and return any unstored messages after trying all backends.
def _store(self, messages, response, *args, **kwargs): """ Store the messages and return any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend. """ for storage in self.storages: ...
[ "def", "_store", "(", "self", ",", "messages", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "storage", "in", "self", ".", "storages", ":", "if", "messages", ":", "messages", "=", "storage", ".", "_store", "(", "message...
[ 37, 4 ]
[ 53, 23 ]
python
en
['en', 'error', 'th']
False
check_for_occlusions
(task, user_input, keep_space_around_bodies=True)
Returns true if user_input occludes scene objects.
Returns true if user_input occludes scene objects.
def check_for_occlusions(task, user_input, keep_space_around_bodies=True): """Returns true if user_input occludes scene objects.""" if not isinstance(task, bytes): task = serialize(task) if isinstance(user_input, scene_if.UserInput): return simulator_bindings.check_for_occlusions_general( ...
[ "def", "check_for_occlusions", "(", "task", ",", "user_input", ",", "keep_space_around_bodies", "=", "True", ")", ":", "if", "not", "isinstance", "(", "task", ",", "bytes", ")", ":", "task", "=", "serialize", "(", "task", ")", "if", "isinstance", "(", "use...
[ 80, 0 ]
[ 90, 72 ]
python
en
['it', 'fy', 'en']
False
add_user_input_to_scene
(scene, user_input, keep_space_around_bodies=True, allow_occlusions=False)
Converts user input to objects in the scene. Args: scene: scene_if.Scene. user_input: scene_if.UserInput or a triple (points, rectangulars, balls). keep_space_around_bodies: bool, if True extra empty space will be enforced around scene bodies. Returns: task_simulati...
Converts user input to objects in the scene.
def add_user_input_to_scene(scene, user_input, keep_space_around_bodies=True, allow_occlusions=False): """Converts user input to objects in the scene. Args: scene: scene_if.Scene. user_input: scene_if.UserInput ...
[ "def", "add_user_input_to_scene", "(", "scene", ",", "user_input", ",", "keep_space_around_bodies", "=", "True", ",", "allow_occlusions", "=", "False", ")", ":", "if", "not", "isinstance", "(", "user_input", ",", "scene_if", ".", "UserInput", ")", ":", "user_inp...
[ 93, 0 ]
[ 116, 69 ]
python
en
['en', 'en', 'en']
True
simulate_task_with_input
(task, user_input, steps=DEFAULT_MAX_STEPS, stride=DEFAULT_STRIDE, keep_space_around_bodies=True)
Check a solution for a task and return SimulationResult. This is un-optimized version of magic_ponies that should be used for debugging or vizualization purposes only.
Check a solution for a task and return SimulationResult.
def simulate_task_with_input(task, user_input, steps=DEFAULT_MAX_STEPS, stride=DEFAULT_STRIDE, keep_space_around_bodies=True): """Check a solution for a task and return SimulationResult. This is ...
[ "def", "simulate_task_with_input", "(", "task", ",", "user_input", ",", "steps", "=", "DEFAULT_MAX_STEPS", ",", "stride", "=", "DEFAULT_STRIDE", ",", "keep_space_around_bodies", "=", "True", ")", ":", "if", "not", "isinstance", "(", "user_input", ",", "scene_if", ...
[ 119, 0 ]
[ 136, 45 ]
python
en
['en', 'en', 'en']
True
scene_to_raster
(scene)
Convert scene to a integer array height x width containing color codes.
Convert scene to a integer array height x width containing color codes.
def scene_to_raster(scene): """Convert scene to a integer array height x width containing color codes. """ pixels = simulator_bindings.render(serialize(scene)) return np.array(pixels).reshape((scene.height, scene.width))
[ "def", "scene_to_raster", "(", "scene", ")", ":", "pixels", "=", "simulator_bindings", ".", "render", "(", "serialize", "(", "scene", ")", ")", "return", "np", ".", "array", "(", "pixels", ")", ".", "reshape", "(", "(", "scene", ".", "height", ",", "sc...
[ 139, 0 ]
[ 143, 64 ]
python
en
['en', 'en', 'en']
True
scene_to_featurized_objects
(scene)
Convert scene to a FeaturizedObjects containing featurs of size num_objects x OBJECT_FEATURE_SIZE.
Convert scene to a FeaturizedObjects containing featurs of size num_objects x OBJECT_FEATURE_SIZE.
def scene_to_featurized_objects(scene): """Convert scene to a FeaturizedObjects containing featurs of size num_objects x OBJECT_FEATURE_SIZE.""" object_vector = simulator_bindings.featurize_scene(serialize(scene)) object_vector = np.array(object_vector, dtype=np.float32).reshape( (-1, OBJECT_FE...
[ "def", "scene_to_featurized_objects", "(", "scene", ")", ":", "object_vector", "=", "simulator_bindings", ".", "featurize_scene", "(", "serialize", "(", "scene", ")", ")", "object_vector", "=", "np", ".", "array", "(", "object_vector", ",", "dtype", "=", "np", ...
[ 146, 0 ]
[ 154, 51 ]
python
en
['en', 'en', 'en']
True
magic_ponies
(task, user_input, steps=DEFAULT_MAX_STEPS, stride=DEFAULT_STRIDE, keep_space_around_bodies=True, with_times=False, need_images=False, need_featurized_objects=False, perturb_step=-1, ...
Check a solution for a task and return intermidiate images. Args: task: task_if.Task or bytes, in the latter case a serialzed task is expected. user_input: scene_if.UserInput or a triple(points, rectangulars, balls) points: None or a list or an array of points. Should be of ...
Check a solution for a task and return intermidiate images.
def magic_ponies(task, user_input, steps=DEFAULT_MAX_STEPS, stride=DEFAULT_STRIDE, keep_space_around_bodies=True, with_times=False, need_images=False, need_featurized_objects=False, pe...
[ "def", "magic_ponies", "(", "task", ",", "user_input", ",", "steps", "=", "DEFAULT_MAX_STEPS", ",", "stride", "=", "DEFAULT_STRIDE", ",", "keep_space_around_bodies", "=", "True", ",", "with_times", "=", "False", ",", "need_images", "=", "False", ",", "need_featu...
[ 187, 0 ]
[ 273, 75 ]
python
en
['en', 'en', 'en']
True
_default_key_normalizer
(key_class, request_context)
Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn...
Create a pool key out of a request context dictionary.
def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to ch...
[ "def", "_default_key_normalizer", "(", "key_class", ",", "request_context", ")", ":", "# Since we mutate the dictionary, make a copy first", "context", "=", "request_context", ".", "copy", "(", ")", "context", "[", "\"scheme\"", "]", "=", "context", "[", "\"scheme\"", ...
[ 77, 0 ]
[ 123, 31 ]
python
en
['en', 'error', 'th']
False
PoolManager._new_pool
(self, scheme, host, port, request_context=None)
Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connect...
Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments.
def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the p...
[ "def", "_new_pool", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "request_context", "=", "None", ")", ":", "pool_cls", "=", "self", ".", "pool_classes_by_scheme", "[", "scheme", "]", "if", "request_context", "is", "None", ":", "request_context"...
[ 187, 4 ]
[ 212, 54 ]
python
en
['en', 'error', 'th']
False
PoolManager.clear
(self)
Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion.
Empty our store of pools and direct them all to close.
def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "pools", ".", "clear", "(", ")" ]
[ 214, 4 ]
[ 221, 26 ]
python
en
['en', 'error', 'th']
False
PoolManager.connection_from_host
(self, host, port=None, scheme="http", pool_kwargs=None)
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_...
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.
def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``...
[ "def", "connection_from_host", "(", "self", ",", "host", ",", "port", "=", "None", ",", "scheme", "=", "\"http\"", ",", "pool_kwargs", "=", "None", ")", ":", "if", "not", "host", ":", "raise", "LocationValueError", "(", "\"No host specified.\"", ")", "reques...
[ 223, 4 ]
[ 244, 60 ]
python
en
['en', 'error', 'th']
False
PoolManager.connection_from_context
(self, request_context)
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable.
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.
def connection_from_context(self, request_context): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ ...
[ "def", "connection_from_context", "(", "self", ",", "request_context", ")", ":", "scheme", "=", "request_context", "[", "\"scheme\"", "]", ".", "lower", "(", ")", "pool_key_constructor", "=", "self", ".", "key_fn_by_scheme", ".", "get", "(", "scheme", ")", "if...
[ 246, 4 ]
[ 259, 87 ]
python
en
['en', 'error', 'th']
False
PoolManager.connection_from_pool_key
(self, pool_key, request_context=None)
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields.
Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.
def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ...
[ "def", "connection_from_pool_key", "(", "self", ",", "pool_key", ",", "request_context", "=", "None", ")", ":", "with", "self", ".", "pools", ".", "lock", ":", "# If the scheme, host, or port doesn't match existing open", "# connections, open a new ConnectionPool.", "pool",...
[ 261, 4 ]
[ 283, 19 ]
python
en
['en', 'error', 'th']
False
PoolManager.connection_from_url
(self, url, pool_kwargs=None)
Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is ...
Similar to :func:`urllib3.connectionpool.connection_from_url`.
def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpoo...
[ "def", "connection_from_url", "(", "self", ",", "url", ",", "pool_kwargs", "=", "None", ")", ":", "u", "=", "parse_url", "(", "url", ")", "return", "self", ".", "connection_from_host", "(", "u", ".", "host", ",", "port", "=", "u", ".", "port", ",", "...
[ 285, 4 ]
[ 299, 9 ]
python
en
['en', 'error', 'th']
False
PoolManager._merge_pool_kwargs
(self, override)
Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary.
Merge a dictionary of override values for self.connection_pool_kw.
def _merge_pool_kwargs(self, override): """ Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary...
[ "def", "_merge_pool_kwargs", "(", "self", ",", "override", ")", ":", "base_pool_kwargs", "=", "self", ".", "connection_pool_kw", ".", "copy", "(", ")", "if", "override", ":", "for", "key", ",", "value", "in", "override", ".", "items", "(", ")", ":", "if"...
[ 301, 4 ]
[ 319, 31 ]
python
en
['en', 'error', 'th']
False
PoolManager._proxy_requires_url_absolute_form
(self, parsed_url)
Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel.
Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel.
def _proxy_requires_url_absolute_form(self, parsed_url): """ Indicates if the proxy requires the complete destination URL in the request. Normally this is only needed when not using an HTTP CONNECT tunnel. """ if self.proxy is None: return False retu...
[ "def", "_proxy_requires_url_absolute_form", "(", "self", ",", "parsed_url", ")", ":", "if", "self", ".", "proxy", "is", "None", ":", "return", "False", "return", "not", "connection_requires_http_tunnel", "(", "self", ".", "proxy", ",", "self", ".", "proxy_config...
[ 321, 4 ]
[ 332, 9 ]
python
en
['en', 'error', 'th']
False
PoolManager._validate_proxy_scheme_url_selection
(self, url_scheme)
Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations.
Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations.
def _validate_proxy_scheme_url_selection(self, url_scheme): """ Validates that were not attempting to do TLS in TLS connections on Python2 or with unsupported SSL implementations. """ if self.proxy is None or url_scheme != "https": return if self.proxy.scheme...
[ "def", "_validate_proxy_scheme_url_selection", "(", "self", ",", "url_scheme", ")", ":", "if", "self", ".", "proxy", "is", "None", "or", "url_scheme", "!=", "\"https\"", ":", "return", "if", "self", ".", "proxy", ".", "scheme", "!=", "\"https\"", ":", "retur...
[ 334, 4 ]
[ 349, 13 ]
python
en
['en', 'error', 'th']
False
PoolManager.urlopen
(self, method, url, redirect=True, **kw)
Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen fo...
Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``.
def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate ...
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "redirect", "=", "True", ",", "*", "*", "kw", ")", ":", "u", "=", "parse_url", "(", "url", ")", "self", ".", "_validate_proxy_scheme_url_selection", "(", "u", ".", "scheme", ")", "conn", ...
[ 351, 4 ]
[ 416, 60 ]
python
en
['en', 'error', 'th']
False
ProxyManager._set_proxy_headers
(self, url, headers=None)
Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user.
Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user.
def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. """ headers_ = {"Accept": "*/*"} netloc = parse_url(url).netloc if netloc: head...
[ "def", "_set_proxy_headers", "(", "self", ",", "url", ",", "headers", "=", "None", ")", ":", "headers_", "=", "{", "\"Accept\"", ":", "\"*/*\"", "}", "netloc", "=", "parse_url", "(", "url", ")", ".", "netloc", "if", "netloc", ":", "headers_", "[", "\"H...
[ 506, 4 ]
[ 519, 23 ]
python
en
['en', 'error', 'th']
False
ProxyManager.urlopen
(self, method, url, redirect=True, **kw)
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.
Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.
def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme): # For connections using HTTP CONNECT, httplib sets the necessary...
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "redirect", "=", "True", ",", "*", "*", "kw", ")", ":", "u", "=", "parse_url", "(", "url", ")", "if", "not", "connection_requires_http_tunnel", "(", "self", ".", "proxy", ",", "self", "."...
[ 521, 4 ]
[ 531, 86 ]
python
en
['en', 'en', 'nl']
True
BaseUserManager.normalize_email
(cls, email)
Normalize the email address by lowercasing the domain part of it.
Normalize the email address by lowercasing the domain part of it.
def normalize_email(cls, email): """ Normalize the email address by lowercasing the domain part of it. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = ema...
[ "def", "normalize_email", "(", "cls", ",", "email", ")", ":", "email", "=", "email", "or", "''", "try", ":", "email_name", ",", "domain_part", "=", "email", ".", "strip", "(", ")", ".", "rsplit", "(", "'@'", ",", "1", ")", "except", "ValueError", ":"...
[ 19, 4 ]
[ 30, 20 ]
python
en
['en', 'error', 'th']
False
BaseUserManager.make_random_password
(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789')
Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion.
Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion.
def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789'): """ Generate a random password with the given length and given ...
[ "def", "make_random_password", "(", "self", ",", "length", "=", "10", ",", "allowed_chars", "=", "'abcdefghjkmnpqrstuvwxyz'", "'ABCDEFGHJKLMNPQRSTUVWXYZ'", "'23456789'", ")", ":", "return", "get_random_string", "(", "length", ",", "allowed_chars", ")" ]
[ 32, 4 ]
[ 41, 55 ]
python
en
['en', 'error', 'th']
False
AbstractBaseUser.get_username
(self)
Return the username for this User.
Return the username for this User.
def get_username(self): """Return the username for this User.""" return getattr(self, self.USERNAME_FIELD)
[ "def", "get_username", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "self", ".", "USERNAME_FIELD", ")" ]
[ 71, 4 ]
[ 73, 49 ]
python
en
['en', 'en', 'en']
True
AbstractBaseUser.is_anonymous
(self)
Always return False. This is a way of comparing User objects to anonymous users.
Always return False. This is a way of comparing User objects to anonymous users.
def is_anonymous(self): """ Always return False. This is a way of comparing User objects to anonymous users. """ return False
[ "def", "is_anonymous", "(", "self", ")", ":", "return", "False" ]
[ 82, 4 ]
[ 87, 20 ]
python
en
['en', 'error', 'th']
False
AbstractBaseUser.is_authenticated
(self)
Always return True. This is a way to tell if the user has been authenticated in templates.
Always return True. This is a way to tell if the user has been authenticated in templates.
def is_authenticated(self): """ Always return True. This is a way to tell if the user has been authenticated in templates. """ return True
[ "def", "is_authenticated", "(", "self", ")", ":", "return", "True" ]
[ 90, 4 ]
[ 95, 19 ]
python
en
['en', 'error', 'th']
False
AbstractBaseUser.check_password
(self, raw_password)
Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes.
Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes.
def check_password(self, raw_password): """ Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) # Password hash upgrades shouldn't be considered ...
[ "def", "check_password", "(", "self", ",", "raw_password", ")", ":", "def", "setter", "(", "raw_password", ")", ":", "self", ".", "set_password", "(", "raw_password", ")", "# Password hash upgrades shouldn't be considered password changes.", "self", ".", "_password", ...
[ 101, 4 ]
[ 111, 66 ]
python
en
['en', 'error', 'th']
False
AbstractBaseUser.has_usable_password
(self)
Return False if set_unusable_password() has been called for this user.
Return False if set_unusable_password() has been called for this user.
def has_usable_password(self): """ Return False if set_unusable_password() has been called for this user. """ return is_password_usable(self.password)
[ "def", "has_usable_password", "(", "self", ")", ":", "return", "is_password_usable", "(", "self", ".", "password", ")" ]
[ 117, 4 ]
[ 121, 48 ]
python
en
['en', 'error', 'th']
False
AbstractBaseUser.get_session_auth_hash
(self)
Return an HMAC of the password field.
Return an HMAC of the password field.
def get_session_auth_hash(self): """ Return an HMAC of the password field. """ key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" return salted_hmac( key_salt, self.password, # RemovedInDjango40Warning: when the depr...
[ "def", "get_session_auth_hash", "(", "self", ")", ":", "key_salt", "=", "\"django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash\"", "return", "salted_hmac", "(", "key_salt", ",", "self", ".", "password", ",", "# RemovedInDjango40Warning: when the deprecation ends, re...
[ 128, 4 ]
[ 140, 21 ]
python
en
['en', 'error', 'th']
False
gen_ccl_spectra
(cosmo, n_of_zs, l_max=1001)
Generates the theoretical weak lensing power spectra for a given cosmology. :param cosmo: 1D array of cosmological parameters ordered as (Om, Ob, h, ns, sigma8, w0) :param n_of_zs: 3D array of redshift distributions. The first axis enumerates the different distributions, the second the ...
Generates the theoretical weak lensing power spectra for a given cosmology. :param cosmo: 1D array of cosmological parameters ordered as (Om, Ob, h, ns, sigma8, w0) :param n_of_zs: 3D array of redshift distributions. The first axis enumerates the different distributions, the second the ...
def gen_ccl_spectra(cosmo, n_of_zs, l_max=1001): """ Generates the theoretical weak lensing power spectra for a given cosmology. :param cosmo: 1D array of cosmological parameters ordered as (Om, Ob, h, ns, sigma8, w0) :param n_of_zs: 3D array of redshift distributions. The first axis enumerates the diff...
[ "def", "gen_ccl_spectra", "(", "cosmo", ",", "n_of_zs", ",", "l_max", "=", "1001", ")", ":", "# cosmo needs to be double", "cosmo", "=", "cosmo", ".", "astype", "(", "np", ".", "float64", ")", "# get the ccl", "cosmo", "=", "ccl", ".", "Cosmology", "(", "O...
[ 6, 0 ]
[ 49, 13 ]
python
en
['en', 'error', 'th']
False
create_GRF_samples
(spectra, data_mask, data_mask_pad, seed, pixwin=False, fwhm=0.0, lmax=1000, return_fidu_spec=False, verbose=0)
Creates a sample of GRF maps of given spectra that can be saved for later training. :param spectra: A list of power spectra used to generate the GRF samples, if the shape of the spectra is [n_bins, N] a tomographic sample is generated and the returned samples have the shape [N_pix, n_bins] ...
Creates a sample of GRF maps of given spectra that can be saved for later training. :param spectra: A list of power spectra used to generate the GRF samples, if the shape of the spectra is [n_bins, N] a tomographic sample is generated and the returned samples have the shape [N_pix, n_bins] ...
def create_GRF_samples(spectra, data_mask, data_mask_pad, seed, pixwin=False, fwhm=0.0, lmax=1000, return_fidu_spec=False, verbose=0): """ Creates a sample of GRF maps of given spectra that can be saved for later training. :param spectra: A list of power spectra used to generate the G...
[ "def", "create_GRF_samples", "(", "spectra", ",", "data_mask", ",", "data_mask_pad", ",", "seed", ",", "pixwin", "=", "False", ",", "fwhm", "=", "0.0", ",", "lmax", "=", "1000", ",", "return_fidu_spec", "=", "False", ",", "verbose", "=", "0", ")", ":", ...
[ 51, 0 ]
[ 193, 23 ]
python
en
['en', 'error', 'th']
False
anti_fleet
(log)
logs will print multi-times when calling Fleet API. Only display single log and ignore the others.
logs will print multi-times when calling Fleet API. Only display single log and ignore the others.
def anti_fleet(log): """ logs will print multi-times when calling Fleet API. Only display single log and ignore the others. """ def wrapper(fmt, *args): if int(os.getenv("PADDLE_TRAINER_ID", 0)) == 0: log(fmt, *args) return wrapper
[ "def", "anti_fleet", "(", "log", ")", ":", "def", "wrapper", "(", "fmt", ",", "*", "args", ")", ":", "if", "int", "(", "os", ".", "getenv", "(", "\"PADDLE_TRAINER_ID\"", ",", "0", ")", ")", "==", "0", ":", "log", "(", "fmt", ",", "*", "args", "...
[ 52, 0 ]
[ 62, 18 ]
python
en
['en', 'error', 'th']
False
scaler
(name, value, step, writer)
This function will draw a scalar curve generated by the visualdl. Usage: Install visualdl: pip3 install visualdl==2.0.0b4 and then: visualdl --logdir ./scalar --host 0.0.0.0 --port 8830 to preview loss corve in real time.
This function will draw a scalar curve generated by the visualdl. Usage: Install visualdl: pip3 install visualdl==2.0.0b4 and then: visualdl --logdir ./scalar --host 0.0.0.0 --port 8830 to preview loss corve in real time.
def scaler(name, value, step, writer): """ This function will draw a scalar curve generated by the visualdl. Usage: Install visualdl: pip3 install visualdl==2.0.0b4 and then: visualdl --logdir ./scalar --host 0.0.0.0 --port 8830 to preview loss corve in real time. """ ...
[ "def", "scaler", "(", "name", ",", "value", ",", "step", ",", "writer", ")", ":", "writer", ".", "add_scalar", "(", "name", ",", "value", ",", "step", ")" ]
[ 80, 0 ]
[ 88, 40 ]
python
en
['en', 'error', 'th']
False
advertise
()
Show the advertising message like the following: =========================================================== == PaddleClas is powered by PaddlePaddle ! == =========================================================== == == == ...
Show the advertising message like the following:
def advertise(): """ Show the advertising message like the following: =========================================================== == PaddleClas is powered by PaddlePaddle ! == =========================================================== == ...
[ "def", "advertise", "(", ")", ":", "copyright", "=", "\"PaddleClas is powered by PaddlePaddle !\"", "ad", "=", "\"For more info please go to the following website.\"", "website", "=", "\"https://github.com/PaddlePaddle/PaddleClas\"", "AD_LEN", "=", "6", "+", "len", "(", "max"...
[ 91, 0 ]
[ 119, 42 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.__init__
(self, objective=None, space=None, N_init=20, X_init=None, Y_init=None, normalize_Y=True, mean_only=False, alpha=0.01, kern="matern52", num_restarts=10, verbosity=0, max_opt_iter=1000, full_restart=False, ARD=False, learning_rate=1e-4, parameter_noise_scale=0.1, minimum_variance=1e-3)
An class that fits a Gaussian process to a given objective function :param objective: function used for the fitting (needs to estimate the noise as well!) :param space: a GPy space for the prior :param N_init: number of initial points :param X_init: initial points in space (if s...
An class that fits a Gaussian process to a given objective function :param objective: function used for the fitting (needs to estimate the noise as well!) :param space: a GPy space for the prior :param N_init: number of initial points :param X_init: initial points in space (if s...
def __init__(self, objective=None, space=None, N_init=20, X_init=None, Y_init=None, normalize_Y=True, mean_only=False, alpha=0.01, kern="matern52", num_restarts=10, verbosity=0, max_opt_iter=1000, full_restart=False, ARD=False, learning_rate=1e-4, parameter_noise_scale=0.1, minimum_var...
[ "def", "__init__", "(", "self", ",", "objective", "=", "None", ",", "space", "=", "None", ",", "N_init", "=", "20", ",", "X_init", "=", "None", ",", "Y_init", "=", "None", ",", "normalize_Y", "=", "True", ",", "mean_only", "=", "False", ",", "alpha",...
[ 68, 4 ]
[ 188, 26 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.acquisition_function
(self, x)
Raul's acquisition function
Raul's acquisition function
def acquisition_function(self, x): """ Raul's acquisition function """ if self.current_transform is not None: x = self.current_transform(x) mean, var = self.model.predict_f(x) if self.normalize_Y: mean = mean * self.Y_std + self.Y_mean ...
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "if", "self", ".", "current_transform", "is", "not", "None", ":", "x", "=", "self", ".", "current_transform", "(", "x", ")", "mean", ",", "var", "=", "self", ".", "model", ".", "predict_f"...
[ 190, 4 ]
[ 203, 90 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.train_model
(self, n_iters)
Optimizes the model for n_iters :param n_iters: number of iterations for optimization :return: a list of losses of each step with length n_iters
Optimizes the model for n_iters :param n_iters: number of iterations for optimization :return: a list of losses of each step with length n_iters
def train_model(self, n_iters): """ Optimizes the model for n_iters :param n_iters: number of iterations for optimization :return: a list of losses of each step with length n_iters """ @tf.function def objective_closure(): return self.model.training_l...
[ "def", "train_model", "(", "self", ",", "n_iters", ")", ":", "@", "tf", ".", "function", "def", "objective_closure", "(", ")", ":", "return", "self", ".", "model", ".", "training_loss", "(", ")", "natgrad", "=", "NaturalGradient", "(", "gamma", "=", "1.0...
[ 205, 4 ]
[ 229, 21 ]
python
en
['en', 'error', 'th']
False
VGP_Emu._readout_params
(self)
Reads out the params of the model and returns them as tupel of arrays :return: tupel of params
Reads out the params of the model and returns them as tupel of arrays :return: tupel of params
def _readout_params(self): """ Reads out the params of the model and returns them as tupel of arrays :return: tupel of params """ params = (self.model.kernel.variance.numpy(), self.model.kernel.lengthscales.numpy(), self.model.q_mu.numpy(), self.model.q_sqrt.nu...
[ "def", "_readout_params", "(", "self", ")", ":", "params", "=", "(", "self", ".", "model", ".", "kernel", ".", "variance", ".", "numpy", "(", ")", ",", "self", ".", "model", ".", "kernel", ".", "lengthscales", ".", "numpy", "(", ")", ",", "self", "...
[ 231, 4 ]
[ 240, 21 ]
python
en
['en', 'error', 'th']
False
VGP_Emu._set_params
(self, params)
Sets the model params to a given tupel of array :param params: params (tupel of arrays)
Sets the model params to a given tupel of array :param params: params (tupel of arrays)
def _set_params(self, params): """ Sets the model params to a given tupel of array :param params: params (tupel of arrays) """ self.model.kernel.variance.assign(params[0]) self.model.kernel.lengthscales.assign(params[1]) self.model.q_mu.assign(params[2]) s...
[ "def", "_set_params", "(", "self", ",", "params", ")", ":", "self", ".", "model", ".", "kernel", ".", "variance", ".", "assign", "(", "params", "[", "0", "]", ")", "self", ".", "model", ".", "kernel", ".", "lengthscales", ".", "assign", "(", "params"...
[ 242, 4 ]
[ 250, 43 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.optimize_model
(self, scale=1.0)
Optimizes the model for a given number of restarts and chooses the best result :param scale: std of the normal distribution used to draw new params
Optimizes the model for a given number of restarts and chooses the best result :param scale: std of the normal distribution used to draw new params
def optimize_model(self, scale=1.0): """ Optimizes the model for a given number of restarts and chooses the best result :param scale: std of the normal distribution used to draw new params """ func_vals = [] model_params = [] # read out the original params ...
[ "def", "optimize_model", "(", "self", ",", "scale", "=", "1.0", ")", ":", "func_vals", "=", "[", "]", "model_params", "=", "[", "]", "# read out the original params", "original_params", "=", "self", ".", "_readout_params", "(", ")", "for", "i", "in", "range"...
[ 252, 4 ]
[ 312, 49 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.optimize
(self, n_draw=5, max_iters=100, rel_tol=0.5, n_convergence=1000, sampler_burn_in=1000, save_path=None, save_iter=5, **kwargs)
Optimizes the initiated GP emulator for at most max_iters iterations :param n_draw: number of draws in each step :param max_iters: maximum number of iterations :param rel_tol: relative tolarance of the Bhattacharyya distance, the optimization will stop if the relative ...
Optimizes the initiated GP emulator for at most max_iters iterations :param n_draw: number of draws in each step :param max_iters: maximum number of iterations :param rel_tol: relative tolarance of the Bhattacharyya distance, the optimization will stop if the relative ...
def optimize(self, n_draw=5, max_iters=100, rel_tol=0.5, n_convergence=1000, sampler_burn_in=1000, save_path=None, save_iter=5, **kwargs): """ Optimizes the initiated GP emulator for at most max_iters iterations :param n_draw: number of draws in each step :param max_iter...
[ "def", "optimize", "(", "self", ",", "n_draw", "=", "5", ",", "max_iters", "=", "100", ",", "rel_tol", "=", "0.5", ",", "n_convergence", "=", "1000", ",", "sampler_burn_in", "=", "1000", ",", "save_path", "=", "None", ",", "save_iter", "=", "5", ",", ...
[ 314, 4 ]
[ 420, 24 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.sample_new
(self, n_draw, burn_in=1000, n_leap=10, step_size=0.05, MCMC_type="Hasting", parallel_iterations=10, start_type="prior", num_results=250, n_chains=None, replace_post=False, min_dist=1e-3, hasting_scale=0.05)
Draws new samples from the aquisition function :param n_draw: number of samples to draw :param burn_in: number of burn in steps :param n_leap: number of leap frog steps if MCMC_type==HMC :param step_size: step size for the HMC algorithm :param MCMC_type: type of MCMC (ei...
Draws new samples from the aquisition function :param n_draw: number of samples to draw :param burn_in: number of burn in steps :param n_leap: number of leap frog steps if MCMC_type==HMC :param step_size: step size for the HMC algorithm :param MCMC_type: type of MCMC (ei...
def sample_new(self, n_draw, burn_in=1000, n_leap=10, step_size=0.05, MCMC_type="Hasting", parallel_iterations=10, start_type="prior", num_results=250, n_chains=None, replace_post=False, min_dist=1e-3, hasting_scale=0.05): """ Draws new samples from the aquisition f...
[ "def", "sample_new", "(", "self", ",", "n_draw", ",", "burn_in", "=", "1000", ",", "n_leap", "=", "10", ",", "step_size", "=", "0.05", ",", "MCMC_type", "=", "\"Hasting\"", ",", "parallel_iterations", "=", "10", ",", "start_type", "=", "\"prior\"", ",", ...
[ 422, 4 ]
[ 561, 26 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.normalize_params
(self, params)
normalizes params to unit variance
normalizes params to unit variance
def normalize_params(self, params): """ normalizes params to unit variance """ # make the params linearly uncorrelated cov = np.cov(params, rowvar=False) # eigenvals and vecs w, v = np.linalg.eig(cov) # rot mat is v.T rot_mat = v.T # dot pr...
[ "def", "normalize_params", "(", "self", ",", "params", ")", ":", "# make the params linearly uncorrelated", "cov", "=", "np", ".", "cov", "(", "params", ",", "rowvar", "=", "False", ")", "# eigenvals and vecs", "w", ",", "v", "=", "np", ".", "linalg", ".", ...
[ 564, 4 ]
[ 583, 53 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.transform_params
(self, params, rot_mat, rot_mean, rot_std)
Normalizes params given the rot, shift and scale
Normalizes params given the rot, shift and scale
def transform_params(self, params, rot_mat, rot_mean, rot_std): """ Normalizes params given the rot, shift and scale """ rot_params = np.einsum("ij,aj->ai", rot_mat, params) new_params = (rot_params - rot_mean) / rot_std return new_params
[ "def", "transform_params", "(", "self", ",", "params", ",", "rot_mat", ",", "rot_mean", ",", "rot_std", ")", ":", "rot_params", "=", "np", ".", "einsum", "(", "\"ij,aj->ai\"", ",", "rot_mat", ",", "params", ")", "new_params", "=", "(", "rot_params", "-", ...
[ 586, 4 ]
[ 592, 25 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.reverse_transform_params
(self, params, rot_mat, rot_mean, rot_std)
Makes the transformation in reverse
Makes the transformation in reverse
def reverse_transform_params(self, params, rot_mat, rot_mean, rot_std): """ Makes the transformation in reverse """ new_params = params * rot_std + rot_mean new_params = np.einsum("ij,aj->ai", rot_mat.T, new_params) return new_params
[ "def", "reverse_transform_params", "(", "self", ",", "params", ",", "rot_mat", ",", "rot_mean", ",", "rot_std", ")", ":", "new_params", "=", "params", "*", "rot_std", "+", "rot_mean", "new_params", "=", "np", ".", "einsum", "(", "\"ij,aj->ai\"", ",", "rot_ma...
[ 595, 4 ]
[ 602, 25 ]
python
en
['en', 'error', 'th']
False
VGP_Emu.unnormalize_params
(self, params, rot_mat, rot_mean, rot_std)
Removes normalization
Removes normalization
def unnormalize_params(self, params, rot_mat, rot_mean, rot_std): """ Removes normalization """ new_params = params * rot_std + rot_mean # inverse rotation new_params = np.einsum("ij,aj->ai", rot_mat.T, new_params) return new_params
[ "def", "unnormalize_params", "(", "self", ",", "params", ",", "rot_mat", ",", "rot_mean", ",", "rot_std", ")", ":", "new_params", "=", "params", "*", "rot_std", "+", "rot_mean", "# inverse rotation", "new_params", "=", "np", ".", "einsum", "(", "\"ij,aj->ai\""...
[ 605, 4 ]
[ 612, 25 ]
python
en
['en', 'error', 'th']
False
L_star_fun
(L_star)
This calcualtes the zero of the optimal well spacing, L_star.
This calcualtes the zero of the optimal well spacing, L_star.
def L_star_fun(L_star): """ This calcualtes the zero of the optimal well spacing, L_star. """ import numpy as np return L_star**2.0*np.log(L_star/D) - \ 2.0*np.pi*rho_w*permeability_/viscosity * \ ((alphaII*rho_r-rho_w)*gravity*reservoir_depth) * \ Cpw*t_inj/((rho_w*...
[ "def", "L_star_fun", "(", "L_star", ")", ":", "import", "numpy", "as", "np", "return", "L_star", "**", "2.0", "*", "np", ".", "log", "(", "L_star", "/", "D", ")", "-", "2.0", "*", "np", ".", "pi", "*", "rho_w", "*", "permeability_", "/", "viscosity...
[ 19, 0 ]
[ 27, 68 ]
python
en
['en', 'error', 'th']
False
L_star_fun2
(L_star)
This calcualtes the optimal well spacing, L_star, if the reservoir constraints imply a flow rate that is higher than the flow rate that would minimize the LCOH. define capital_costs and CRF externally
This calcualtes the optimal well spacing, L_star, if the reservoir constraints imply a flow rate that is higher than the flow rate that would minimize the LCOH.
def L_star_fun2(L_star): """ This calcualtes the optimal well spacing, L_star, if the reservoir constraints imply a flow rate that is higher than the flow rate that would minimize the LCOH. define capital_costs and CRF externally """ import numpy as np return (capital_cost_internal*CRF...
[ "def", "L_star_fun2", "(", "L_star", ")", ":", "import", "numpy", "as", "np", "return", "(", "capital_cost_internal", "*", "CRF", "*", "rho_w", "*", "rho_w", "*", "np", ".", "pi", "*", "permeability_", "*", "b_", "/", "(", "2.0", "*", "dollars_per_kWhth"...
[ 29, 0 ]
[ 43, 40 ]
python
en
['en', 'error', 'th']
False
Serializer.prepare_response
(self, request, cached)
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
def prepare_response(self, request, cached): """Verify our vary headers match and construct a real urllib3 HTTPResponse object. """ # Special case the '*' Vary value as it means we cannot actually # determine if the cached response is suitable for this request. # This cas...
[ "def", "prepare_response", "(", "self", ",", "request", ",", "cached", ")", ":", "# Special case the '*' Vary value as it means we cannot actually", "# determine if the cached response is suitable for this request.", "# This case is also handled in the controller code when creating", "# a ...
[ 103, 4 ]
[ 139, 83 ]
python
en
['en', 'en', 'en']
True
validate_system
(system)
Ensure build system has the requisite fields.
Ensure build system has the requisite fields.
def validate_system(system): """ Ensure build system has the requisite fields. """ required = {'requires', 'build-backend'} if not (required <= set(system)): message = "Missing required fields: {missing}".format( missing=required-set(system), ) raise ValueError(me...
[ "def", "validate_system", "(", "system", ")", ":", "required", "=", "{", "'requires'", ",", "'build-backend'", "}", "if", "not", "(", "required", "<=", "set", "(", "system", ")", ")", ":", "message", "=", "\"Missing required fields: {missing}\"", ".", "format"...
[ 16, 0 ]
[ 25, 33 ]
python
en
['en', 'error', 'th']
False
load_system
(source_dir)
Load the build system from a source dir (pyproject.toml).
Load the build system from a source dir (pyproject.toml).
def load_system(source_dir): """ Load the build system from a source dir (pyproject.toml). """ pyproject = os.path.join(source_dir, 'pyproject.toml') with io.open(pyproject, encoding="utf-8") as f: pyproject_data = toml_load(f) return pyproject_data['build-system']
[ "def", "load_system", "(", "source_dir", ")", ":", "pyproject", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "'pyproject.toml'", ")", "with", "io", ".", "open", "(", "pyproject", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "...
[ 28, 0 ]
[ 35, 41 ]
python
en
['en', 'error', 'th']
False
compat_system
(source_dir)
Given a source dir, attempt to get a build system backend and requirements from pyproject.toml. Fallback to setuptools but only if the file was not found or a build system was not indicated.
Given a source dir, attempt to get a build system backend and requirements from pyproject.toml. Fallback to setuptools but only if the file was not found or a build system was not indicated.
def compat_system(source_dir): """ Given a source dir, attempt to get a build system backend and requirements from pyproject.toml. Fallback to setuptools but only if the file was not found or a build system was not indicated. """ try: system = load_system(source_dir) except (File...
[ "def", "compat_system", "(", "source_dir", ")", ":", "try", ":", "system", "=", "load_system", "(", "source_dir", ")", "except", "(", "FileNotFoundError", ",", "KeyError", ")", ":", "system", "=", "{", "}", "system", ".", "setdefault", "(", "'build-backend'"...
[ 38, 0 ]
[ 54, 17 ]
python
en
['en', 'error', 'th']
False
_Enhance.enhance
(self, factor)
Returns an enhanced image. :param factor: A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, etc), and higher values more. ...
Returns an enhanced image.
def enhance(self, factor): """ Returns an enhanced image. :param factor: A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, ...
[ "def", "enhance", "(", "self", ",", "factor", ")", ":", "return", "Image", ".", "blend", "(", "self", ".", "degenerate", ",", "self", ".", "image", ",", "factor", ")" ]
[ 24, 4 ]
[ 35, 63 ]
python
en
['en', 'error', 'th']
False
Ghostscript
(tile, size, fp, scale=1)
Render an image using Ghostscript
Render an image using Ghostscript
def Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data # Hack to support hi-res rendering scale = int(scale) or 1 # orig_size = size # orig_bbox = bbox size = (size[0] * scale...
[ "def", "Ghostscript", "(", "tile", ",", "size", ",", "fp", ",", "scale", "=", "1", ")", ":", "# Unpack decoder tile", "decoder", ",", "tile", ",", "offset", ",", "data", "=", "tile", "[", "0", "]", "length", ",", "bbox", "=", "data", "# Hack to support...
[ 63, 0 ]
[ 155, 13 ]
python
af
['de', 'af', 'en']
False
_save
(im, fp, filename, eps=1)
EPS Writer for the Python Imaging Library.
EPS Writer for the Python Imaging Library.
def _save(im, fp, filename, eps=1): """EPS Writer for the Python Imaging Library.""" # # make sure image data is available im.load() # # determine PostScript image mode if im.mode == "L": operator = (8, 1, b"image") elif im.mode == "RGB": operator = (8, 3, b"false 3 col...
[ "def", "_save", "(", "im", ",", "fp", ",", "filename", ",", "eps", "=", "1", ")", ":", "#", "# make sure image data is available", "im", ".", "load", "(", ")", "#", "# determine PostScript image mode", "if", "im", ".", "mode", "==", "\"L\"", ":", "operator...
[ 346, 0 ]
[ 395, 18 ]
python
en
['en', 'en', 'en']
True
escape
(text)
Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead.
Return the given text with ampersands, quotes and angle brackets encoded for use in HTML.
def escape(text): """ Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return ma...
[ "def", "escape", "(", "text", ")", ":", "return", "mark_safe", "(", "html", ".", "escape", "(", "str", "(", "text", ")", ")", ")" ]
[ 33, 0 ]
[ 42, 44 ]
python
en
['en', 'error', 'th']
False
escapejs
(value)
Hex encode characters for use in JavaScript strings.
Hex encode characters for use in JavaScript strings.
def escapejs(value): """Hex encode characters for use in JavaScript strings.""" return mark_safe(str(value).translate(_js_escapes))
[ "def", "escapejs", "(", "value", ")", ":", "return", "mark_safe", "(", "str", "(", "value", ")", ".", "translate", "(", "_js_escapes", ")", ")" ]
[ 65, 0 ]
[ 67, 55 ]
python
en
['en', 'en', 'en']
True
json_script
(value, element_id)
Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag.
Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag.
def json_script(value, element_id): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag. """ from django.core.serializers.json import DjangoJSONEncoder json_...
[ "def", "json_script", "(", "value", ",", "element_id", ")", ":", "from", "django", ".", "core", ".", "serializers", ".", "json", "import", "DjangoJSONEncoder", "json_str", "=", "json", ".", "dumps", "(", "value", ",", "cls", "=", "DjangoJSONEncoder", ")", ...
[ 77, 0 ]
[ 88, 5 ]
python
en
['en', 'error', 'th']
False
conditional_escape
(text)
Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe.
Similar to escape(), except that it doesn't operate on pre-escaped strings.
def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if isinstance(text, Promise): text = str(t...
[ "def", "conditional_escape", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "Promise", ")", ":", "text", "=", "str", "(", "text", ")", "if", "hasattr", "(", "text", ",", "'__html__'", ")", ":", "return", "text", ".", "__html__", "(", ")...
[ 91, 0 ]
[ 103, 27 ]
python
en
['en', 'error', 'th']
False
format_html
(format_string, *args, **kwargs)
Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments.
Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments.
def format_html(format_string, *args, **kwargs): """ Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditi...
[ "def", "format_html", "(", "format_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args_safe", "=", "map", "(", "conditional_escape", ",", "args", ")", "kwargs_safe", "=", "{", "k", ":", "conditional_escape", "(", "v", ")", "for", "(", "...
[ 106, 0 ]
[ 114, 69 ]
python
en
['en', 'error', 'th']
False
format_html_join
(sep, format_string, args_generator)
A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed...
A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape.
def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an ite...
[ "def", "format_html_join", "(", "sep", ",", "format_string", ",", "args_generator", ")", ":", "return", "mark_safe", "(", "conditional_escape", "(", "sep", ")", ".", "join", "(", "format_html", "(", "format_string", ",", "*", "args", ")", "for", "args", "in"...
[ 117, 0 ]
[ 134, 6 ]
python
en
['en', 'error', 'th']
False
linebreaks
(value, autoescape=False)
Convert newlines into <p> and <br>s.
Convert newlines into <p> and <br>s.
def linebreaks(value, autoescape=False): """Convert newlines into <p> and <br>s.""" value = normalize_newlines(value) paras = re.split('\n{2,}', str(value)) if autoescape: paras = ['<p>%s</p>' % escape(p).replace('\n', '<br>') for p in paras] else: paras = ['<p>%s</p>' % p.replace('\...
[ "def", "linebreaks", "(", "value", ",", "autoescape", "=", "False", ")", ":", "value", "=", "normalize_newlines", "(", "value", ")", "paras", "=", "re", ".", "split", "(", "'\\n{2,}'", ",", "str", "(", "value", ")", ")", "if", "autoescape", ":", "paras...
[ 138, 0 ]
[ 146, 29 ]
python
en
['en', 'en', 'en']
True
_strip_once
(value)
Internal tag stripping utility used by strip_tags.
Internal tag stripping utility used by strip_tags.
def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() s.feed(value) s.close() return s.get_data()
[ "def", "_strip_once", "(", "value", ")", ":", "s", "=", "MLStripper", "(", ")", "s", ".", "feed", "(", "value", ")", "s", ".", "close", "(", ")", "return", "s", ".", "get_data", "(", ")" ]
[ 168, 0 ]
[ 175, 23 ]
python
en
['en', 'error', 'th']
False
strip_tags
(value)
Return the given HTML with all tags stripped.
Return the given HTML with all tags stripped.
def strip_tags(value): """Return the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. value = str(value) while '<' in value and '>' in value: new_value = ...
[ "def", "strip_tags", "(", "value", ")", ":", "# Note: in typical case this loop executes _strip_once once. Loop condition", "# is redundant, but helps to reduce number of executions of _strip_once.", "value", "=", "str", "(", "value", ")", "while", "'<'", "in", "value", "and", ...
[ 179, 0 ]
[ 190, 16 ]
python
en
['en', 'en', 'en']
True
strip_spaces_between_tags
(value)
Return the given HTML with spaces between tags removed.
Return the given HTML with spaces between tags removed.
def strip_spaces_between_tags(value): """Return the given HTML with spaces between tags removed.""" return re.sub(r'>\s+<', '><', str(value))
[ "def", "strip_spaces_between_tags", "(", "value", ")", ":", "return", "re", ".", "sub", "(", "r'>\\s+<'", ",", "'><'", ",", "str", "(", "value", ")", ")" ]
[ 194, 0 ]
[ 196, 45 ]
python
en
['en', 'en', 'en']
True
smart_urlquote
(url)
Quote a URL if it isn't already quoted.
Quote a URL if it isn't already quoted.
def smart_urlquote(url): """Quote a URL if it isn't already quoted.""" def unquote_quote(segment): segment = unquote(segment) # Tilde is part of RFC3986 Unreserved Characters # https://tools.ietf.org/html/rfc3986#section-2.3 # See also https://bugs.python.org/issue16285 r...
[ "def", "smart_urlquote", "(", "url", ")", ":", "def", "unquote_quote", "(", "segment", ")", ":", "segment", "=", "unquote", "(", "segment", ")", "# Tilde is part of RFC3986 Unreserved Characters", "# https://tools.ietf.org/html/rfc3986#section-2.3", "# See also https://bugs.p...
[ 199, 0 ]
[ 231, 62 ]
python
en
['en', 'en', 'en']
True
urlize
(text, trim_url_limit=None, nofollow=False, autoescape=False)
Convert any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening pa...
Convert any URLs in text into clickable links.
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Convert any URLs in text into clickable links. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing pun...
[ "def", "urlize", "(", "text", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "autoescape", "=", "False", ")", ":", "safe_input", "=", "isinstance", "(", "text", ",", "SafeData", ")", "def", "trim_url", "(", "x", ",", "limit", "...
[ 235, 0 ]
[ 348, 25 ]
python
en
['en', 'error', 'th']
False
avoid_wrapping
(value)
Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces.
Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces.
def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0")
[ "def", "avoid_wrapping", "(", "value", ")", ":", "return", "value", ".", "replace", "(", "\" \"", ",", "\"\\xa0\"", ")" ]
[ 351, 0 ]
[ 356, 37 ]
python
en
['en', 'error', 'th']
False
html_safe
(klass)
A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString.
A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString.
def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString. """ if '__html__' in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " ...
[ "def", "html_safe", "(", "klass", ")", ":", "if", "'__html__'", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"can't apply @html_safe to %s because it defines \"", "\"__html__().\"", "%", "klass", ".", "__name__", ")", "if", "'__str__'", "not", ...
[ 359, 0 ]
[ 377, 16 ]
python
en
['en', 'error', 'th']
False
parse_config
(cfg_file)
Load a config file into AttrDict
Load a config file into AttrDict
def parse_config(cfg_file): """Load a config file into AttrDict""" with open(cfg_file, 'r') as fopen: yaml_config = AttrDict(yaml.load(fopen, Loader=yaml.SafeLoader)) create_attr_dict(yaml_config) return yaml_config
[ "def", "parse_config", "(", "cfg_file", ")", ":", "with", "open", "(", "cfg_file", ",", "'r'", ")", "as", "fopen", ":", "yaml_config", "=", "AttrDict", "(", "yaml", ".", "load", "(", "fopen", ",", "Loader", "=", "yaml", ".", "SafeLoader", ")", ")", "...
[ 50, 0 ]
[ 55, 22 ]
python
en
['en', 'es', 'en']
True
print_dict
(d, delimiter=0)
Recursively visualize a dict and indenting acrrording by the relationship of keys.
Recursively visualize a dict and indenting acrrording by the relationship of keys.
def print_dict(d, delimiter=0): """ Recursively visualize a dict and indenting acrrording by the relationship of keys. """ placeholder = "-" * 60 for k, v in sorted(d.items()): if isinstance(v, dict): logger.info("{}{} : ".format(delimiter * " ", ...
[ "def", "print_dict", "(", "d", ",", "delimiter", "=", "0", ")", ":", "placeholder", "=", "\"-\"", "*", "60", "for", "k", ",", "v", "in", "sorted", "(", "d", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", ...
[ 58, 0 ]
[ 80, 36 ]
python
en
['en', 'error', 'th']
False
print_config
(config)
visualize configs Arguments: config: configs
visualize configs
def print_config(config): """ visualize configs Arguments: config: configs """ logger.advertise() print_dict(config)
[ "def", "print_config", "(", "config", ")", ":", "logger", ".", "advertise", "(", ")", "print_dict", "(", "config", ")" ]
[ 83, 0 ]
[ 91, 22 ]
python
en
['en', 'error', 'th']
False
check_config
(config)
Check config
Check config
def check_config(config): """ Check config """ check.check_version() use_gpu = config.get('use_gpu', True) if use_gpu: check.check_gpu() architecture = config.get('ARCHITECTURE') check.check_architecture(architecture) use_mix = config.get('use_mix', False) check.check_...
[ "def", "check_config", "(", "config", ")", ":", "check", ".", "check_version", "(", ")", "use_gpu", "=", "config", ".", "get", "(", "'use_gpu'", ",", "True", ")", "if", "use_gpu", ":", "check", ".", "check_gpu", "(", ")", "architecture", "=", "config", ...
[ 94, 0 ]
[ 116, 56 ]
python
en
['en', 'error', 'th']
False
override
(dl, ks, v)
Recursively replace dict of list Args: dl(dict or list): dict or list to be replaced ks(list): list of keys v(str): value to be replaced
Recursively replace dict of list
def override(dl, ks, v): """ Recursively replace dict of list Args: dl(dict or list): dict or list to be replaced ks(list): list of keys v(str): value to be replaced """ def str2num(v): try: return eval(v) except Exception: return v ...
[ "def", "override", "(", "dl", ",", "ks", ",", "v", ")", ":", "def", "str2num", "(", "v", ")", ":", "try", ":", "return", "eval", "(", "v", ")", "except", "Exception", ":", "return", "v", "assert", "isinstance", "(", "dl", ",", "(", "list", ",", ...
[ 119, 0 ]
[ 151, 42 ]
python
en
['en', 'error', 'th']
False
override_config
(config, options=None)
Recursively override the config Args: config(dict): dict to be replaced options(list): list of pairs(key0.key1.idx.key2=value) such as: [ 'topk=2', 'VALID.transforms.1.ResizeImage.resize_short=300' ] Returns: config(dict): re...
Recursively override the config
def override_config(config, options=None): """ Recursively override the config Args: config(dict): dict to be replaced options(list): list of pairs(key0.key1.idx.key2=value) such as: [ 'topk=2', 'VALID.transforms.1.ResizeImage.resize_short=300' ...
[ "def", "override_config", "(", "config", ",", "options", "=", "None", ")", ":", "if", "options", "is", "not", "None", ":", "for", "opt", "in", "options", ":", "assert", "isinstance", "(", "opt", ",", "str", ")", ",", "(", "\"option({}) should be a str\"", ...
[ 154, 0 ]
[ 182, 17 ]
python
en
['en', 'error', 'th']
False
get_config
(fname, overrides=None, show=True)
Read config from file
Read config from file
def get_config(fname, overrides=None, show=True): """ Read config from file """ assert os.path.exists(fname), ( 'config file({}) is not exist'.format(fname)) config = parse_config(fname) override_config(config, overrides) if show: print_config(config) check_config(config)...
[ "def", "get_config", "(", "fname", ",", "overrides", "=", "None", ",", "show", "=", "True", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "fname", ")", ",", "(", "'config file({}) is not exist'", ".", "format", "(", "fname", ")", ")", "con...
[ 185, 0 ]
[ 196, 17 ]
python
en
['en', 'error', 'th']
False
format
(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False, use_l10n=None)
Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-unifo...
Get a number (as a number or string), and return it as a string, using formats defined as arguments:
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False, use_l10n=None): """ Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decima...
[ "def", "format", "(", "number", ",", "decimal_sep", ",", "decimal_pos", "=", "None", ",", "grouping", "=", "0", ",", "thousand_sep", "=", "''", ",", "force_grouping", "=", "False", ",", "use_l10n", "=", "None", ")", ":", "use_grouping", "=", "(", "use_l1...
[ 6, 0 ]
[ 89, 37 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._maindb_connection
(self)
This is analogous to other backends' `_nodb_connection` property, which allows access to an "administrative" connection which can be used to manage the test databases. For Oracle, the only connection that can be used for that purpose is the main (non-test) connection.
This is analogous to other backends' `_nodb_connection` property, which allows access to an "administrative" connection which can be used to manage the test databases. For Oracle, the only connection that can be used for that purpose is the main (non-test) connection.
def _maindb_connection(self): """ This is analogous to other backends' `_nodb_connection` property, which allows access to an "administrative" connection which can be used to manage the test databases. For Oracle, the only connection that can be used for that purpose is t...
[ "def", "_maindb_connection", "(", "self", ")", ":", "settings_dict", "=", "settings", ".", "DATABASES", "[", "self", ".", "connection", ".", "alias", "]", "user", "=", "settings_dict", ".", "get", "(", "'SAVED_USER'", ")", "or", "settings_dict", "[", "'USER'...
[ 14, 4 ]
[ 27, 74 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._switch_to_test_user
(self, parameters)
Switch to the user that's used for creating the test database. Oracle doesn't have the concept of separate databases under the same user, so a separate user is used; see _create_test_db(). The main user is also needed for cleanup when testing is completed, so save its credentia...
Switch to the user that's used for creating the test database.
def _switch_to_test_user(self, parameters): """ Switch to the user that's used for creating the test database. Oracle doesn't have the concept of separate databases under the same user, so a separate user is used; see _create_test_db(). The main user is also needed for cleanup w...
[ "def", "_switch_to_test_user", "(", "self", ",", "parameters", ")", ":", "real_settings", "=", "settings", ".", "DATABASES", "[", "self", ".", "connection", ".", "alias", "]", "real_settings", "[", "'SAVED_USER'", "]", "=", "self", ".", "connection", ".", "s...
[ 101, 4 ]
[ 119, 102 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation.set_as_test_mirror
(self, primary_settings_dict)
Set this database up to be used in testing as a mirror of a primary database whose settings are given.
Set this database up to be used in testing as a mirror of a primary database whose settings are given.
def set_as_test_mirror(self, primary_settings_dict): """ Set this database up to be used in testing as a mirror of a primary database whose settings are given. """ self.connection.settings_dict['USER'] = primary_settings_dict['USER'] self.connection.settings_dict['PASSWOR...
[ "def", "set_as_test_mirror", "(", "self", ",", "primary_settings_dict", ")", ":", "self", ".", "connection", ".", "settings_dict", "[", "'USER'", "]", "=", "primary_settings_dict", "[", "'USER'", "]", "self", ".", "connection", ".", "settings_dict", "[", "'PASSW...
[ 121, 4 ]
[ 127, 85 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._destroy_test_db
(self, test_database_name, verbosity=1)
Destroy a test database, prompting the user for confirmation if the database already exists. Return the name of the test database created.
Destroy a test database, prompting the user for confirmation if the database already exists. Return the name of the test database created.
def _destroy_test_db(self, test_database_name, verbosity=1): """ Destroy a test database, prompting the user for confirmation if the database already exists. Return the name of the test database created. """ self.connection.settings_dict['USER'] = self.connection.settings_dict['S...
[ "def", "_destroy_test_db", "(", "self", ",", "test_database_name", ",", "verbosity", "=", "1", ")", ":", "self", ".", "connection", ".", "settings_dict", "[", "'USER'", "]", "=", "self", ".", "connection", ".", "settings_dict", "[", "'SAVED_USER'", "]", "sel...
[ 166, 4 ]
[ 184, 39 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._execute_allow_fail_statements
(self, cursor, statements, parameters, verbosity, acceptable_ora_err)
Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise.
Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise.
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err): """ Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception,...
[ "def", "_execute_allow_fail_statements", "(", "self", ",", "cursor", ",", "statements", ",", "parameters", ",", "verbosity", ",", "acceptable_ora_err", ")", ":", "try", ":", "# Statement can fail when acceptable_ora_err is not None", "allow_quiet_fail", "=", "acceptable_ora...
[ 282, 4 ]
[ 297, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._test_settings_get
(self, key, default=None, prefixed=None)
Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict.
Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict.
def _test_settings_get(self, key, default=None, prefixed=None): """ Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict. """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, defa...
[ "def", "_test_settings_get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "prefixed", "=", "None", ")", ":", "settings_dict", "=", "self", ".", "connection", ".", "settings_dict", "val", "=", "settings_dict", "[", "'TEST'", "]", ".", "get", ...
[ 316, 4 ]
[ 325, 18 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._get_test_db_name
(self)
Return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django don't have real counterparts in Oracle.
Return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django don't have real counterparts in Oracle.
def _get_test_db_name(self): """ Return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django don't have real counterparts in Oracle. """ return self.connection.settings_dict['NAM...
[ "def", "_get_test_db_name", "(", "self", ")", ":", "return", "self", ".", "connection", ".", "settings_dict", "[", "'NAME'", "]" ]
[ 383, 4 ]
[ 389, 52 ]
python
en
['en', 'error', 'th']
False
autocomplete
()
Entry Point for completion of main and subcommand options.
Entry Point for completion of main and subcommand options.
def autocomplete() -> None: """Entry Point for completion of main and subcommand options.""" # Don't complete if user hasn't sourced bash_completion file. if "PIP_AUTO_COMPLETE" not in os.environ: return cwords = os.environ["COMP_WORDS"].split()[1:] cword = int(os.environ["COMP_CWORD"]) ...
[ "def", "autocomplete", "(", ")", "->", "None", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "\"PIP_AUTO_COMPLETE\"", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "\"COMP_WORDS\"", "]", "."...
[ 14, 0 ]
[ 107, 15 ]
python
en
['en', 'en', 'en']
True
get_path_completion_type
( cwords: List[str], cword: int, opts: Iterable[Any] )
Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` o...
Get the type of path completion (``file``, ``dir``, ``path`` or None)
def get_path_completion_type( cwords: List[str], cword: int, opts: Iterable[Any] ) -> Optional[str]: """Get the type of path completion (``file``, ``dir``, ``path`` or None) :param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` ...
[ "def", "get_path_completion_type", "(", "cwords", ":", "List", "[", "str", "]", ",", "cword", ":", "int", ",", "opts", ":", "Iterable", "[", "Any", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "cword", "<", "2", "or", "not", "cwords", "[...
[ 110, 0 ]
[ 131, 15 ]
python
en
['en', 'en', 'en']
True
auto_complete_paths
(current: str, completion_type: str)
If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :param completion_type: path completion type(`file`, `path` or `dir`)i :return: A gen...
If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``.
def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]: """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``. :param current: The word to be completed :par...
[ "def", "auto_complete_paths", "(", "current", ":", "str", ",", "completion_type", ":", "str", ")", "->", "Iterable", "[", "str", "]", ":", "directory", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "current", ")", "current_path", "=", "os",...
[ 134, 0 ]
[ 162, 45 ]
python
en
['en', 'en', 'en']
True
move_to_completion_bucket
(target_bucket, target_infix, **kwargs)
A utility method to move an object to a target location in GCS.
A utility method to move an object to a target location in GCS.
def move_to_completion_bucket(target_bucket, target_infix, **kwargs): """A utility method to move an object to a target location in GCS.""" # Here we establish a connection hook to GoogleCloudStorage. # Google Cloud Composer automatically provides a google_cloud_storage_default # connection id that is u...
[ "def", "move_to_completion_bucket", "(", "target_bucket", ",", "target_infix", ",", "*", "*", "kwargs", ")", ":", "# Here we establish a connection hook to GoogleCloudStorage.", "# Google Cloud Composer automatically provides a google_cloud_storage_default", "# connection id that is used...
[ 77, 0 ]
[ 101, 45 ]
python
en
['en', 'en', 'en']
True
train_and_deploy
( project='cloud-training-demos', bucket='cloud-training-demos-ml', startYear='2000' )
Pipeline to train babyweight model
Pipeline to train babyweight model
def train_and_deploy( project='cloud-training-demos', bucket='cloud-training-demos-ml', startYear='2000' ): """Pipeline to train babyweight model""" start_step = 1 # Step 1: create training dataset using Apache Beam on Cloud Dataflow if start_step <= 1: preprocess = dsl.ContainerOp( name=...
[ "def", "train_and_deploy", "(", "project", "=", "'cloud-training-demos'", ",", "bucket", "=", "'cloud-training-demos-ml'", ",", "startYear", "=", "'2000'", ")", ":", "start_step", "=", "1", "# Step 1: create training dataset using Apache Beam on Cloud Dataflow", "if", "star...
[ 30, 0 ]
[ 143, 6 ]
python
en
['en', 'en', 'en']
True
xclProbe
()
xclProbe() - Enumerate devices found in the system :return: count of devices found
xclProbe() - Enumerate devices found in the system :return: count of devices found
def xclProbe(): """ xclProbe() - Enumerate devices found in the system :return: count of devices found """ return libc.xclProbe()
[ "def", "xclProbe", "(", ")", ":", "return", "libc", ".", "xclProbe", "(", ")" ]
[ 157, 0 ]
[ 162, 26 ]
python
en
['en', 'error', 'th']
False
xclVersion
()
:return: the version number. 1 => Hal1 ; 2 => Hal2
:return: the version number. 1 => Hal1 ; 2 => Hal2
def xclVersion(): """ :return: the version number. 1 => Hal1 ; 2 => Hal2 """ return libc.xclVersion()
[ "def", "xclVersion", "(", ")", ":", "return", "libc", ".", "xclVersion", "(", ")" ]
[ 164, 0 ]
[ 168, 28 ]
python
en
['en', 'error', 'th']
False