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
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
get_level_tags
()
Return the message level tags.
Return the message level tags.
def get_level_tags(): """ Return the message level tags. """ return { **constants.DEFAULT_TAGS, **getattr(settings, 'MESSAGE_TAGS', {}), }
[ "def", "get_level_tags", "(", ")", ":", "return", "{", "*", "*", "constants", ".", "DEFAULT_TAGS", ",", "*", "*", "getattr", "(", "settings", ",", "'MESSAGE_TAGS'", ",", "{", "}", ")", ",", "}" ]
[ 4, 0 ]
[ 11, 5 ]
python
en
['en', 'error', 'th']
False
build_wheel_pep517
( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str tempd, # type: str )
Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None.
Build one InstallRequirement using the PEP 517 build process.
def build_wheel_pep517( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str tempd, # type: str ): # type: (...) -> Optional[str] """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. """ assert metadata_directory is not None try: logger.debug('Destination directory: %s', tempd) runner = runner_with_spinner_message( f'Building wheel for {name} (PEP 517)' ) with backend.subprocess_runner(runner): wheel_name = backend.build_wheel( tempd, metadata_directory=metadata_directory, ) except Exception: logger.error('Failed building wheel for %s', name) return None return os.path.join(tempd, wheel_name)
[ "def", "build_wheel_pep517", "(", "name", ",", "# type: str", "backend", ",", "# type: Pep517HookCaller", "metadata_directory", ",", "# type: str", "tempd", ",", "# type: str", ")", ":", "# type: (...) -> Optional[str]", "assert", "metadata_directory", "is", "not", "None", "try", ":", "logger", ".", "debug", "(", "'Destination directory: %s'", ",", "tempd", ")", "runner", "=", "runner_with_spinner_message", "(", "f'Building wheel for {name} (PEP 517)'", ")", "with", "backend", ".", "subprocess_runner", "(", "runner", ")", ":", "wheel_name", "=", "backend", ".", "build_wheel", "(", "tempd", ",", "metadata_directory", "=", "metadata_directory", ",", ")", "except", "Exception", ":", "logger", ".", "error", "(", "'Failed building wheel for %s'", ",", "name", ")", "return", "None", "return", "os", ".", "path", ".", "join", "(", "tempd", ",", "wheel_name", ")" ]
[ 11, 0 ]
[ 37, 42 ]
python
en
['en', 'en', 'en']
True
attach_enctype_error_multidict
(request)
Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed.
Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed.
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key): try: return oldcls.__getitem__(self, key) except KeyError: if key not in request.form: raise raise DebugFilesKeyError(request, key) newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls
[ "def", "attach_enctype_error_multidict", "(", "request", ")", ":", "oldcls", "=", "request", ".", "files", ".", "__class__", "class", "newcls", "(", "oldcls", ")", ":", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "try", ":", "return", "oldcls", ".", "__getitem__", "(", "self", ",", "key", ")", "except", "KeyError", ":", "if", "key", "not", "in", "request", ".", "form", ":", "raise", "raise", "DebugFilesKeyError", "(", "request", ",", "key", ")", "newcls", ".", "__name__", "=", "oldcls", ".", "__name__", "newcls", ".", "__module__", "=", "oldcls", ".", "__module__", "request", ".", "files", ".", "__class__", "=", "newcls" ]
[ 73, 0 ]
[ 89, 36 ]
python
en
['en', 'en', 'en']
True
explain_template_loading_attempts
(app, template, attempts)
This should help developers understand what failed
This should help developers understand what failed
def explain_template_loading_attempts(app, template, attempts): """This should help developers understand what failed""" info = ['Locating template "%s":' % template] total_found = 0 blueprint = None reqctx = _request_ctx_stack.top if reqctx is not None and reqctx.request.blueprint is not None: blueprint = reqctx.request.blueprint for idx, (loader, srcobj, triple) in enumerate(attempts): if isinstance(srcobj, Flask): src_info = 'application "%s"' % srcobj.import_name elif isinstance(srcobj, Blueprint): src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name) else: src_info = repr(srcobj) info.append('% 5d: trying loader of %s' % ( idx + 1, src_info)) for line in _dump_loader_info(loader): info.append(' %s' % line) if triple is None: detail = 'no match' else: detail = 'found (%r)' % (triple[1] or '<string>') total_found += 1 info.append(' -> %s' % detail) seems_fishy = False if total_found == 0: info.append('Error: the template could not be found.') seems_fishy = True elif total_found > 1: info.append('Warning: multiple loaders returned a match for the template.') seems_fishy = True if blueprint is not None and seems_fishy: info.append(' The template was looked up from an endpoint that ' 'belongs to the blueprint "%s".' % blueprint) info.append(' Maybe you did not place a template in the right folder?') info.append(' See http://flask.pocoo.org/docs/blueprints/#templates') app.logger.info('\n'.join(info))
[ "def", "explain_template_loading_attempts", "(", "app", ",", "template", ",", "attempts", ")", ":", "info", "=", "[", "'Locating template \"%s\":'", "%", "template", "]", "total_found", "=", "0", "blueprint", "=", "None", "reqctx", "=", "_request_ctx_stack", ".", "top", "if", "reqctx", "is", "not", "None", "and", "reqctx", ".", "request", ".", "blueprint", "is", "not", "None", ":", "blueprint", "=", "reqctx", ".", "request", ".", "blueprint", "for", "idx", ",", "(", "loader", ",", "srcobj", ",", "triple", ")", "in", "enumerate", "(", "attempts", ")", ":", "if", "isinstance", "(", "srcobj", ",", "Flask", ")", ":", "src_info", "=", "'application \"%s\"'", "%", "srcobj", ".", "import_name", "elif", "isinstance", "(", "srcobj", ",", "Blueprint", ")", ":", "src_info", "=", "'blueprint \"%s\" (%s)'", "%", "(", "srcobj", ".", "name", ",", "srcobj", ".", "import_name", ")", "else", ":", "src_info", "=", "repr", "(", "srcobj", ")", "info", ".", "append", "(", "'% 5d: trying loader of %s'", "%", "(", "idx", "+", "1", ",", "src_info", ")", ")", "for", "line", "in", "_dump_loader_info", "(", "loader", ")", ":", "info", ".", "append", "(", "' %s'", "%", "line", ")", "if", "triple", "is", "None", ":", "detail", "=", "'no match'", "else", ":", "detail", "=", "'found (%r)'", "%", "(", "triple", "[", "1", "]", "or", "'<string>'", ")", "total_found", "+=", "1", "info", ".", "append", "(", "' -> %s'", "%", "detail", ")", "seems_fishy", "=", "False", "if", "total_found", "==", "0", ":", "info", ".", "append", "(", "'Error: the template could not be found.'", ")", "seems_fishy", "=", "True", "elif", "total_found", ">", "1", ":", "info", ".", "append", "(", "'Warning: multiple loaders returned a match for the template.'", ")", "seems_fishy", "=", "True", "if", "blueprint", "is", "not", "None", "and", "seems_fishy", ":", "info", ".", "append", "(", "' The template was looked up from an endpoint that '", "'belongs to the blueprint \"%s\".'", "%", "blueprint", ")", "info", ".", "append", "(", "' Maybe you did not place a template in the right folder?'", ")", "info", ".", "append", "(", "' See http://flask.pocoo.org/docs/blueprints/#templates'", ")", "app", ".", "logger", ".", "info", "(", "'\\n'", ".", "join", "(", "info", ")", ")" ]
[ 109, 0 ]
[ 154, 36 ]
python
en
['en', 'en', 'en']
True
_has_level_handler
(logger)
Check if there is a handler in the logging chain that will handle the given logger's effective level.
Check if there is a handler in the logging chain that will handle the given logger's effective level.
def _has_level_handler(logger): """Check if there is a handler in the logging chain that will handle the given logger's effective level. """ level = logger.getEffectiveLevel() current = logger while current: if any(handler.level <= level for handler in current.handlers): return True if not current.propagate: break current = current.parent return False
[ "def", "_has_level_handler", "(", "logger", ")", ":", "level", "=", "logger", ".", "getEffectiveLevel", "(", ")", "current", "=", "logger", "while", "current", ":", "if", "any", "(", "handler", ".", "level", "<=", "level", "for", "handler", "in", "current", ".", "handlers", ")", ":", "return", "True", "if", "not", "current", ".", "propagate", ":", "break", "current", "=", "current", ".", "parent", "return", "False" ]
[ 83, 0 ]
[ 99, 16 ]
python
en
['en', 'en', 'en']
True
_log
(type, message, *args, **kwargs)
Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added.
Log a message to the 'werkzeug' logger.
def _log(type, message, *args, **kwargs): """Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added. """ global _logger if _logger is None: _logger = logging.getLogger("werkzeug") if _logger.level == logging.NOTSET: _logger.setLevel(logging.INFO) if not _has_level_handler(_logger): _logger.addHandler(logging.StreamHandler()) getattr(_logger, type)(message.rstrip(), *args, **kwargs)
[ "def", "_log", "(", "type", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_logger", "if", "_logger", "is", "None", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"werkzeug\"", ")", "if", "_logger", ".", "level", "==", "logging", ".", "NOTSET", ":", "_logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "if", "not", "_has_level_handler", "(", "_logger", ")", ":", "_logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", ")", ")", "getattr", "(", "_logger", ",", "type", ")", "(", "message", ".", "rstrip", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 102, 0 ]
[ 121, 61 ]
python
en
['en', 'en', 'en']
True
_parse_signature
(func)
Return a signature object for the function.
Return a signature object for the function.
def _parse_signature(func): """Return a signature object for the function.""" if hasattr(func, "im_func"): func = func.im_func # if we have a cached validator for this function, return it parse = _signature_cache.get(func) if parse is not None: return parse # inspect the function signature and collect all the information if hasattr(inspect, "getfullargspec"): tup = inspect.getfullargspec(func) else: tup = inspect.getargspec(func) positional, vararg_var, kwarg_var, defaults = tup[:4] defaults = defaults or () arg_count = len(positional) arguments = [] for idx, name in enumerate(positional): if isinstance(name, list): raise TypeError( "cannot parse functions that unpack tuples in the function signature" ) try: default = defaults[idx - arg_count] except IndexError: param = (name, False, None) else: param = (name, True, default) arguments.append(param) arguments = tuple(arguments) def parse(args, kwargs): new_args = [] missing = [] extra = {} # consume as many arguments as positional as possible for idx, (name, has_default, default) in enumerate(arguments): try: new_args.append(args[idx]) except IndexError: try: new_args.append(kwargs.pop(name)) except KeyError: if has_default: new_args.append(default) else: missing.append(name) else: if name in kwargs: extra[name] = kwargs.pop(name) # handle extra arguments extra_positional = args[arg_count:] if vararg_var is not None: new_args.extend(extra_positional) extra_positional = () if kwargs and kwarg_var is None: extra.update(kwargs) kwargs = {} return ( new_args, kwargs, missing, extra, extra_positional, arguments, vararg_var, kwarg_var, ) _signature_cache[func] = parse return parse
[ "def", "_parse_signature", "(", "func", ")", ":", "if", "hasattr", "(", "func", ",", "\"im_func\"", ")", ":", "func", "=", "func", ".", "im_func", "# if we have a cached validator for this function, return it", "parse", "=", "_signature_cache", ".", "get", "(", "func", ")", "if", "parse", "is", "not", "None", ":", "return", "parse", "# inspect the function signature and collect all the information", "if", "hasattr", "(", "inspect", ",", "\"getfullargspec\"", ")", ":", "tup", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "else", ":", "tup", "=", "inspect", ".", "getargspec", "(", "func", ")", "positional", ",", "vararg_var", ",", "kwarg_var", ",", "defaults", "=", "tup", "[", ":", "4", "]", "defaults", "=", "defaults", "or", "(", ")", "arg_count", "=", "len", "(", "positional", ")", "arguments", "=", "[", "]", "for", "idx", ",", "name", "in", "enumerate", "(", "positional", ")", ":", "if", "isinstance", "(", "name", ",", "list", ")", ":", "raise", "TypeError", "(", "\"cannot parse functions that unpack tuples in the function signature\"", ")", "try", ":", "default", "=", "defaults", "[", "idx", "-", "arg_count", "]", "except", "IndexError", ":", "param", "=", "(", "name", ",", "False", ",", "None", ")", "else", ":", "param", "=", "(", "name", ",", "True", ",", "default", ")", "arguments", ".", "append", "(", "param", ")", "arguments", "=", "tuple", "(", "arguments", ")", "def", "parse", "(", "args", ",", "kwargs", ")", ":", "new_args", "=", "[", "]", "missing", "=", "[", "]", "extra", "=", "{", "}", "# consume as many arguments as positional as possible", "for", "idx", ",", "(", "name", ",", "has_default", ",", "default", ")", "in", "enumerate", "(", "arguments", ")", ":", "try", ":", "new_args", ".", "append", "(", "args", "[", "idx", "]", ")", "except", "IndexError", ":", "try", ":", "new_args", ".", "append", "(", "kwargs", ".", "pop", "(", "name", ")", ")", "except", "KeyError", ":", "if", "has_default", ":", "new_args", ".", "append", "(", "default", ")", "else", ":", "missing", ".", "append", "(", "name", ")", "else", ":", "if", "name", "in", "kwargs", ":", "extra", "[", "name", "]", "=", "kwargs", ".", "pop", "(", "name", ")", "# handle extra arguments", "extra_positional", "=", "args", "[", "arg_count", ":", "]", "if", "vararg_var", "is", "not", "None", ":", "new_args", ".", "extend", "(", "extra_positional", ")", "extra_positional", "=", "(", ")", "if", "kwargs", "and", "kwarg_var", "is", "None", ":", "extra", ".", "update", "(", "kwargs", ")", "kwargs", "=", "{", "}", "return", "(", "new_args", ",", "kwargs", ",", "missing", ",", "extra", ",", "extra_positional", ",", "arguments", ",", "vararg_var", ",", "kwarg_var", ",", ")", "_signature_cache", "[", "func", "]", "=", "parse", "return", "parse" ]
[ 124, 0 ]
[ 199, 16 ]
python
en
['en', 'en', 'en']
True
_date_to_unix
(arg)
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
def _date_to_unix(arg): """Converts a timetuple, integer or datetime object into the seconds from epoch in utc. """ if isinstance(arg, datetime): arg = arg.utctimetuple() elif isinstance(arg, integer_types + (float,)): return int(arg) year, month, day, hour, minute, second = arg[:6] days = date(year, month, 1).toordinal() - _epoch_ord + day - 1 hours = days * 24 + hour minutes = hours * 60 + minute seconds = minutes * 60 + second return seconds
[ "def", "_date_to_unix", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "datetime", ")", ":", "arg", "=", "arg", ".", "utctimetuple", "(", ")", "elif", "isinstance", "(", "arg", ",", "integer_types", "+", "(", "float", ",", ")", ")", ":", "return", "int", "(", "arg", ")", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", "=", "arg", "[", ":", "6", "]", "days", "=", "date", "(", "year", ",", "month", ",", "1", ")", ".", "toordinal", "(", ")", "-", "_epoch_ord", "+", "day", "-", "1", "hours", "=", "days", "*", "24", "+", "hour", "minutes", "=", "hours", "*", "60", "+", "minute", "seconds", "=", "minutes", "*", "60", "+", "second", "return", "seconds" ]
[ 202, 0 ]
[ 215, 18 ]
python
en
['en', 'en', 'en']
True
_cookie_parse_impl
(b)
Lowlevel cookie parsing facility that operates on bytes.
Lowlevel cookie parsing facility that operates on bytes.
def _cookie_parse_impl(b): """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) while i < n: match = _cookie_re.search(b + b";", i) if not match: break key = match.group("key").strip() value = match.group("val") or b"" i = match.end(0) # Ignore parameters. We have no interest in them. if key.lower() not in _cookie_params: yield _cookie_unquote(key), _cookie_unquote(value)
[ "def", "_cookie_parse_impl", "(", "b", ")", ":", "i", "=", "0", "n", "=", "len", "(", "b", ")", "while", "i", "<", "n", ":", "match", "=", "_cookie_re", ".", "search", "(", "b", "+", "b\";\"", ",", "i", ")", "if", "not", "match", ":", "break", "key", "=", "match", ".", "group", "(", "\"key\"", ")", ".", "strip", "(", ")", "value", "=", "match", ".", "group", "(", "\"val\"", ")", "or", "b\"\"", "i", "=", "match", ".", "end", "(", "0", ")", "# Ignore parameters. We have no interest in them.", "if", "key", ".", "lower", "(", ")", "not", "in", "_cookie_params", ":", "yield", "_cookie_unquote", "(", "key", ")", ",", "_cookie_unquote", "(", "value", ")" ]
[ 323, 0 ]
[ 339, 62 ]
python
en
['en', 'en', 'en']
True
_easteregg
(app=None)
Like the name says. But who knows how it works?
Like the name says. But who knows how it works?
def _easteregg(app=None): """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver): import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = u"\n".join( [ x + (77 - len(x)) * u" " for x in bzzzzzzz( b""" eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m 9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz 4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY jmEzE4naFp58PdzhPMdslLVWHTGUVpSxImw+pS/D+JhzLfdS1j7PzUMxij+mc2U0I9zcbZ/HcZxc q1QjvvcThMYFnp93agEx392ZdLJWXbi/Ca4Oivl4h/Y1ErEqP+lrg7Xa4qnUKu5UE9UUA4xeqLJ5 jWlPKJvR2yhRI7xFPdzPuc6adXu6ovwXwRPXXnZHxlPtkSkqWHilsOrGrvcVWXgGP3daXomCj317 8P2UOw/NnA0OOikZyFf3zZ76eN9QXNwYdD8f8/LdBRFg0BO3bB+Pe/+G8er8tDJv83XTkj7WeMBJ v/rnAfdO51d6sFglfi8U7zbnr0u9tyJHhFZNXYfH8Iafv2Oa+DT6l8u9UYlajV/hcEgk1x8E8L/r XJXl2SK+GJCxtnyhVKv6GFCEB1OO3f9YWAIEbwcRWv/6RPpsEzOkXURMN37J0PoCSYeBnJQd9Giu LxYQJNlYPSo/iTQwgaihbART7Fcyem2tTSCcwNCs85MOOpJtXhXDe0E7zgZJkcxWTar/zEjdIVCk iXy87FW6j5aGZhttDBoAZ3vnmlkx4q4mMmCdLtnHkBXFMCReqthSGkQ+MDXLLCpXwBs0t+sIhsDI tjBB8MwqYQpLygZ56rRHHpw+OAVyGgaGRHWy2QfXez+ZQQTTBkmRXdV/A9LwH6XGZpEAZU8rs4pE 1R4FQ3Uwt8RKEtRc0/CrANUoes3EzM6WYcFyskGZ6UTHJWenBDS7h163Eo2bpzqxNE9aVgEM2CqI GAJe9Yra4P5qKmta27VjzYdR04Vc7KHeY4vs61C0nbywFmcSXYjzBHdiEjraS7PGG2jHHTpJUMxN Jlxr3pUuFvlBWLJGE3GcA1/1xxLcHmlO+LAXbhrXah1tD6Ze+uqFGdZa5FM+3eHcKNaEarutAQ0A QMAZHV+ve6LxAwWnXbbSXEG2DmCX5ijeLCKj5lhVFBrMm+ryOttCAeFpUdZyQLAQkA06RLs56rzG 8MID55vqr/g64Qr/wqwlE0TVxgoiZhHrbY2h1iuuyUVg1nlkpDrQ7Vm1xIkI5XRKLedN9EjzVchu jQhXcVkjVdgP2O99QShpdvXWoSwkp5uMwyjt3jiWCqWGSiaaPAzohjPanXVLbM3x0dNskJsaCEyz DTKIs+7WKJD4ZcJGfMhLFBf6hlbnNkLEePF8Cx2o2kwmYF4+MzAxa6i+6xIQkswOqGO+3x9NaZX8 MrZRaFZpLeVTYI9F/djY6DDVVs340nZGmwrDqTCiiqD5luj3OzwpmQCiQhdRYowUYEA3i1WWGwL4 GCtSoO4XbIPFeKGU13XPkDf5IdimLpAvi2kVDVQbzOOa4KAXMFlpi/hV8F6IDe0Y2reg3PuNKT3i RYhZqtkQZqSB2Qm0SGtjAw7RDwaM1roESC8HWiPxkoOy0lLTRFG39kvbLZbU9gFKFRvixDZBJmpi Xyq3RE5lW00EJjaqwp/v3EByMSpVZYsEIJ4APaHmVtpGSieV5CALOtNUAzTBiw81GLgC0quyzf6c NlWknzJeCsJ5fup2R4d8CYGN77mu5vnO1UqbfElZ9E6cR6zbHjgsr9ly18fXjZoPeDjPuzlWbFwS pdvPkhntFvkc13qb9094LL5NrA3NIq3r9eNnop9DizWOqCEbyRBFJTHn6Tt3CG1o8a4HevYh0XiJ sR0AVVHuGuMOIfbuQ/OKBkGRC6NJ4u7sbPX8bG/n5sNIOQ6/Y/BX3IwRlTSabtZpYLB85lYtkkgm p1qXK3Du2mnr5INXmT/78KI12n11EFBkJHHp0wJyLe9MvPNUGYsf+170maayRoy2lURGHAIapSpQ krEDuNoJCHNlZYhKpvw4mspVWxqo415n8cD62N9+EfHrAvqQnINStetek7RY2Urv8nxsnGaZfRr/ nhXbJ6m/yl1LzYqscDZA9QHLNbdaSTTr+kFg3bC0iYbX/eQy0Bv3h4B50/SGYzKAXkCeOLI3bcAt mj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p 7f2zLkGNv8b191cD/3vs9Q833z8t""" ).splitlines() ] ) def easteregged(environ, start_response): def injecting_start_response(status, headers, exc_info=None): headers.append(("X-Powered-By", "Werkzeug")) return start_response(status, headers, exc_info) if app is not None and environ.get("QUERY_STRING") != "macgybarchakku": return app(environ, injecting_start_response) injecting_start_response("200 OK", [("Content-Type", "text/html")]) return [ ( u""" <!DOCTYPE html> <html> <head> <title>About Werkzeug</title> <style type="text/css"> body { font: 15px Georgia, serif; text-align: center; } a { color: #333; text-decoration: none; } h1 { font-size: 30px; margin: 20px 0 10px 0; } p { margin: 0 0 30px 0; } pre { font: 11px 'Consolas', 'Monaco', monospace; line-height: 0.95; } </style> </head> <body> <h1><a href="http://werkzeug.pocoo.org/">Werkzeug</a></h1> <p>the Swiss Army knife of Python web development.</p> <pre>%s\n\n\n</pre> </body> </html>""" % gyver ).encode("latin1") ] return easteregged
[ "def", "_easteregg", "(", "app", "=", "None", ")", ":", "def", "bzzzzzzz", "(", "gyver", ")", ":", "import", "base64", "import", "zlib", "return", "zlib", ".", "decompress", "(", "base64", ".", "b64decode", "(", "gyver", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "gyver", "=", "u\"\\n\"", ".", "join", "(", "[", "x", "+", "(", "77", "-", "len", "(", "x", ")", ")", "*", "u\" \"", "for", "x", "in", "bzzzzzzz", "(", "b\"\"\"\neJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m\n9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz\n4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY\njmEzE4naFp58PdzhPMdslLVWHTGUVpSxImw+pS/D+JhzLfdS1j7PzUMxij+mc2U0I9zcbZ/HcZxc\nq1QjvvcThMYFnp93agEx392ZdLJWXbi/Ca4Oivl4h/Y1ErEqP+lrg7Xa4qnUKu5UE9UUA4xeqLJ5\njWlPKJvR2yhRI7xFPdzPuc6adXu6ovwXwRPXXnZHxlPtkSkqWHilsOrGrvcVWXgGP3daXomCj317\n8P2UOw/NnA0OOikZyFf3zZ76eN9QXNwYdD8f8/LdBRFg0BO3bB+Pe/+G8er8tDJv83XTkj7WeMBJ\nv/rnAfdO51d6sFglfi8U7zbnr0u9tyJHhFZNXYfH8Iafv2Oa+DT6l8u9UYlajV/hcEgk1x8E8L/r\nXJXl2SK+GJCxtnyhVKv6GFCEB1OO3f9YWAIEbwcRWv/6RPpsEzOkXURMN37J0PoCSYeBnJQd9Giu\nLxYQJNlYPSo/iTQwgaihbART7Fcyem2tTSCcwNCs85MOOpJtXhXDe0E7zgZJkcxWTar/zEjdIVCk\niXy87FW6j5aGZhttDBoAZ3vnmlkx4q4mMmCdLtnHkBXFMCReqthSGkQ+MDXLLCpXwBs0t+sIhsDI\ntjBB8MwqYQpLygZ56rRHHpw+OAVyGgaGRHWy2QfXez+ZQQTTBkmRXdV/A9LwH6XGZpEAZU8rs4pE\n1R4FQ3Uwt8RKEtRc0/CrANUoes3EzM6WYcFyskGZ6UTHJWenBDS7h163Eo2bpzqxNE9aVgEM2CqI\nGAJe9Yra4P5qKmta27VjzYdR04Vc7KHeY4vs61C0nbywFmcSXYjzBHdiEjraS7PGG2jHHTpJUMxN\nJlxr3pUuFvlBWLJGE3GcA1/1xxLcHmlO+LAXbhrXah1tD6Ze+uqFGdZa5FM+3eHcKNaEarutAQ0A\nQMAZHV+ve6LxAwWnXbbSXEG2DmCX5ijeLCKj5lhVFBrMm+ryOttCAeFpUdZyQLAQkA06RLs56rzG\n8MID55vqr/g64Qr/wqwlE0TVxgoiZhHrbY2h1iuuyUVg1nlkpDrQ7Vm1xIkI5XRKLedN9EjzVchu\njQhXcVkjVdgP2O99QShpdvXWoSwkp5uMwyjt3jiWCqWGSiaaPAzohjPanXVLbM3x0dNskJsaCEyz\nDTKIs+7WKJD4ZcJGfMhLFBf6hlbnNkLEePF8Cx2o2kwmYF4+MzAxa6i+6xIQkswOqGO+3x9NaZX8\nMrZRaFZpLeVTYI9F/djY6DDVVs340nZGmwrDqTCiiqD5luj3OzwpmQCiQhdRYowUYEA3i1WWGwL4\nGCtSoO4XbIPFeKGU13XPkDf5IdimLpAvi2kVDVQbzOOa4KAXMFlpi/hV8F6IDe0Y2reg3PuNKT3i\nRYhZqtkQZqSB2Qm0SGtjAw7RDwaM1roESC8HWiPxkoOy0lLTRFG39kvbLZbU9gFKFRvixDZBJmpi\nXyq3RE5lW00EJjaqwp/v3EByMSpVZYsEIJ4APaHmVtpGSieV5CALOtNUAzTBiw81GLgC0quyzf6c\nNlWknzJeCsJ5fup2R4d8CYGN77mu5vnO1UqbfElZ9E6cR6zbHjgsr9ly18fXjZoPeDjPuzlWbFwS\npdvPkhntFvkc13qb9094LL5NrA3NIq3r9eNnop9DizWOqCEbyRBFJTHn6Tt3CG1o8a4HevYh0XiJ\nsR0AVVHuGuMOIfbuQ/OKBkGRC6NJ4u7sbPX8bG/n5sNIOQ6/Y/BX3IwRlTSabtZpYLB85lYtkkgm\np1qXK3Du2mnr5INXmT/78KI12n11EFBkJHHp0wJyLe9MvPNUGYsf+170maayRoy2lURGHAIapSpQ\nkrEDuNoJCHNlZYhKpvw4mspVWxqo415n8cD62N9+EfHrAvqQnINStetek7RY2Urv8nxsnGaZfRr/\nnhXbJ6m/yl1LzYqscDZA9QHLNbdaSTTr+kFg3bC0iYbX/eQy0Bv3h4B50/SGYzKAXkCeOLI3bcAt\nmj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p\n7f2zLkGNv8b191cD/3vs9Q833z8t\"\"\"", ")", ".", "splitlines", "(", ")", "]", ")", "def", "easteregged", "(", "environ", ",", "start_response", ")", ":", "def", "injecting_start_response", "(", "status", ",", "headers", ",", "exc_info", "=", "None", ")", ":", "headers", ".", "append", "(", "(", "\"X-Powered-By\"", ",", "\"Werkzeug\"", ")", ")", "return", "start_response", "(", "status", ",", "headers", ",", "exc_info", ")", "if", "app", "is", "not", "None", "and", "environ", ".", "get", "(", "\"QUERY_STRING\"", ")", "!=", "\"macgybarchakku\"", ":", "return", "app", "(", "environ", ",", "injecting_start_response", ")", "injecting_start_response", "(", "\"200 OK\"", ",", "[", "(", "\"Content-Type\"", ",", "\"text/html\"", ")", "]", ")", "return", "[", "(", "u\"\"\"\n<!DOCTYPE html>\n<html>\n<head>\n<title>About Werkzeug</title>\n<style type=\"text/css\">\n body { font: 15px Georgia, serif; text-align: center; }\n a { color: #333; text-decoration: none; }\n h1 { font-size: 30px; margin: 20px 0 10px 0; }\n p { margin: 0 0 30px 0; }\n pre { font: 11px 'Consolas', 'Monaco', monospace; line-height: 0.95; }\n</style>\n</head>\n<body>\n<h1><a href=\"http://werkzeug.pocoo.org/\">Werkzeug</a></h1>\n<p>the Swiss Army knife of Python web development.</p>\n<pre>%s\\n\\n\\n</pre>\n</body>\n</html>\"\"\"", "%", "gyver", ")", ".", "encode", "(", "\"latin1\"", ")", "]", "return", "easteregged" ]
[ 401, 0 ]
[ 483, 22 ]
python
en
['en', 'en', 'en']
True
SetEncoder._componentSortKey
(componentAndType)
Sort SET components by tag Sort depending on the actual Choice value (dynamic sort)
Sort SET components by tag
def _componentSortKey(componentAndType): """Sort SET components by tag Sort depending on the actual Choice value (dynamic sort) """ component, asn1Spec = componentAndType if asn1Spec is None: compType = component else: compType = asn1Spec if compType.typeId == univ.Choice.typeId and not compType.tagSet: if asn1Spec is None: return component.getComponent().tagSet else: # TODO: move out of sorting key function names = [namedType.name for namedType in asn1Spec.componentType.namedTypes if namedType.name in component] if len(names) != 1: raise error.PyAsn1Error( '%s components for Choice at %r' % (len(names) and 'Multiple ' or 'None ', component)) # TODO: support nested CHOICE ordering return asn1Spec[names[0]].tagSet else: return compType.tagSet
[ "def", "_componentSortKey", "(", "componentAndType", ")", ":", "component", ",", "asn1Spec", "=", "componentAndType", "if", "asn1Spec", "is", "None", ":", "compType", "=", "component", "else", ":", "compType", "=", "asn1Spec", "if", "compType", ".", "typeId", "==", "univ", ".", "Choice", ".", "typeId", "and", "not", "compType", ".", "tagSet", ":", "if", "asn1Spec", "is", "None", ":", "return", "component", ".", "getComponent", "(", ")", ".", "tagSet", "else", ":", "# TODO: move out of sorting key function", "names", "=", "[", "namedType", ".", "name", "for", "namedType", "in", "asn1Spec", ".", "componentType", ".", "namedTypes", "if", "namedType", ".", "name", "in", "component", "]", "if", "len", "(", "names", ")", "!=", "1", ":", "raise", "error", ".", "PyAsn1Error", "(", "'%s components for Choice at %r'", "%", "(", "len", "(", "names", ")", "and", "'Multiple '", "or", "'None '", ",", "component", ")", ")", "# TODO: support nested CHOICE ordering", "return", "asn1Spec", "[", "names", "[", "0", "]", "]", ".", "tagSet", "else", ":", "return", "compType", ".", "tagSet" ]
[ 15, 4 ]
[ 42, 34 ]
python
en
['en', 'en', 'en']
True
encode_string
(boundary, name, value)
Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.
Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.
def encode_string(boundary, name, value): """Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.""" return MultipartParam(name, value).encode(boundary)
[ "def", "encode_string", "(", "boundary", ",", "name", ",", "value", ")", ":", "return", "MultipartParam", "(", "name", ",", "value", ")", ".", "encode", "(", "boundary", ")" ]
[ 303, 0 ]
[ 308, 55 ]
python
en
['en', 'en', 'en']
True
encode_file_header
(boundary, paramname, filesize, filename=None, filetype=None)
Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname`` is the name of the variable in this request. ``filesize`` is the size of the file data. ``filename`` if specified is the filename to give to this field. This field is only useful to the server for determining the original filename. ``filetype`` if specified is the MIME type of this file. The actual file data should be sent after this header has been sent.
Returns the leading data for a multipart/form-data field that contains file data.
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname`` is the name of the variable in this request. ``filesize`` is the size of the file data. ``filename`` if specified is the filename to give to this field. This field is only useful to the server for determining the original filename. ``filetype`` if specified is the MIME type of this file. The actual file data should be sent after this header has been sent. """ return MultipartParam(paramname, filesize=filesize, filename=filename, filetype=filetype).encode_hdr(boundary)
[ "def", "encode_file_header", "(", "boundary", ",", "paramname", ",", "filesize", ",", "filename", "=", "None", ",", "filetype", "=", "None", ")", ":", "return", "MultipartParam", "(", "paramname", ",", "filesize", "=", "filesize", ",", "filename", "=", "filename", ",", "filetype", "=", "filetype", ")", ".", "encode_hdr", "(", "boundary", ")" ]
[ 311, 0 ]
[ 331, 65 ]
python
en
['en', 'en', 'en']
True
get_body_size
(params, boundary)
Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.
Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.
def get_body_size(params, boundary): """Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.""" size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) return size + len(boundary) + 6
[ "def", "get_body_size", "(", "params", ",", "boundary", ")", ":", "size", "=", "sum", "(", "p", ".", "get_size", "(", "boundary", ")", "for", "p", "in", "MultipartParam", ".", "from_params", "(", "params", ")", ")", "return", "size", "+", "len", "(", "boundary", ")", "+", "6" ]
[ 334, 0 ]
[ 338, 35 ]
python
en
['en', 'en', 'en']
True
get_headers
(params, boundary)
Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.
Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.
def get_headers(params, boundary): """Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.""" headers = {} boundary = quote_plus(boundary) headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary headers['Content-Length'] = str(get_body_size(params, boundary)) return headers
[ "def", "get_headers", "(", "params", ",", "boundary", ")", ":", "headers", "=", "{", "}", "boundary", "=", "quote_plus", "(", "boundary", ")", "headers", "[", "'Content-Type'", "]", "=", "\"multipart/form-data; boundary=%s\"", "%", "boundary", "headers", "[", "'Content-Length'", "]", "=", "str", "(", "get_body_size", "(", "params", ",", "boundary", ")", ")", "return", "headers" ]
[ 341, 0 ]
[ 348, 18 ]
python
en
['en', 'en', 'en']
True
multipart_encode
(params, boundary=None, cb=None)
Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and either .fileno() or both .seek() and .tell(). If ``boundary`` is set, then it as used as the MIME boundary. Otherwise a randomly generated boundary will be used. In either case, if the boundary string appears in the parameter values a ValueError will be raised. If ``cb`` is set, it should be a callback which will get called as blocks of data are encoded. It will be called with (param, current, total), indicating the current parameter being encoded, the current amount encoded, and the total amount to encode. Returns a tuple of `datagen`, `headers`, where `datagen` is a generator that will yield blocks of data that make up the encoded parameters, and `headers` is a dictionary with the assoicated Content-Type and Content-Length headers. Examples: >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] ) >>> s = "".join(datagen) >>> assert "value2" in s and "value1" in s >>> p = MultipartParam("key", "value2") >>> datagen, headers = multipart_encode( [("key", "value1"), p] ) >>> s = "".join(datagen) >>> assert "value2" in s and "value1" in s >>> datagen, headers = multipart_encode( {"key": "value1"} ) >>> s = "".join(datagen) >>> assert "value2" not in s and "value1" in s
Encode ``params`` as multipart/form-data.
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and either .fileno() or both .seek() and .tell(). If ``boundary`` is set, then it as used as the MIME boundary. Otherwise a randomly generated boundary will be used. In either case, if the boundary string appears in the parameter values a ValueError will be raised. If ``cb`` is set, it should be a callback which will get called as blocks of data are encoded. It will be called with (param, current, total), indicating the current parameter being encoded, the current amount encoded, and the total amount to encode. Returns a tuple of `datagen`, `headers`, where `datagen` is a generator that will yield blocks of data that make up the encoded parameters, and `headers` is a dictionary with the assoicated Content-Type and Content-Length headers. Examples: >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] ) >>> s = "".join(datagen) >>> assert "value2" in s and "value1" in s >>> p = MultipartParam("key", "value2") >>> datagen, headers = multipart_encode( [("key", "value1"), p] ) >>> s = "".join(datagen) >>> assert "value2" in s and "value1" in s >>> datagen, headers = multipart_encode( {"key": "value1"} ) >>> s = "".join(datagen) >>> assert "value2" not in s and "value1" in s """ if boundary is None: boundary = gen_boundary() else: boundary = quote_plus(boundary) headers = get_headers(params, boundary) params = MultipartParam.from_params(params) return multipart_yielder(params, boundary, cb), headers
[ "def", "multipart_encode", "(", "params", ",", "boundary", "=", "None", ",", "cb", "=", "None", ")", ":", "if", "boundary", "is", "None", ":", "boundary", "=", "gen_boundary", "(", ")", "else", ":", "boundary", "=", "quote_plus", "(", "boundary", ")", "headers", "=", "get_headers", "(", "params", ",", "boundary", ")", "params", "=", "MultipartParam", ".", "from_params", "(", "params", ")", "return", "multipart_yielder", "(", "params", ",", "boundary", ",", "cb", ")", ",", "headers" ]
[ 407, 0 ]
[ 455, 59 ]
python
en
['en', 'en', 'en']
True
MultipartParam.from_file
(cls, paramname, filename)
Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set to os.path.basename(``filename``)
Returns a new MultipartParam object constructed from the local file at ``filename``.
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set to os.path.basename(``filename``) """ return cls(paramname, filename=os.path.basename(filename), filetype=mimetypes.guess_type(filename)[0], filesize=os.path.getsize(filename), fileobj=open(filename, "rb"))
[ "def", "from_file", "(", "cls", ",", "paramname", ",", "filename", ")", ":", "return", "cls", "(", "paramname", ",", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "filetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", ",", "filesize", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", ",", "fileobj", "=", "open", "(", "filename", ",", "\"rb\"", ")", ")" ]
[ 163, 4 ]
[ 177, 48 ]
python
en
['en', 'en', 'en']
True
MultipartParam.from_params
(cls, params)
Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must match the given names in the name,value pairs or mapping, if applicable.
Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values
def from_params(cls, params): """Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must match the given names in the name,value pairs or mapping, if applicable.""" if hasattr(params, 'items'): params = params.items() retval = [] for item in params: if isinstance(item, cls): retval.append(item) continue name, value = item if isinstance(value, cls): assert value.name == name retval.append(value) continue if hasattr(value, 'read'): # Looks like a file object filename = getattr(value, 'name', None) if filename is not None: filetype = mimetypes.guess_type(filename)[0] else: filetype = None retval.append(cls(name=name, filename=filename, filetype=filetype, fileobj=value)) else: retval.append(cls(name, value)) return retval
[ "def", "from_params", "(", "cls", ",", "params", ")", ":", "if", "hasattr", "(", "params", ",", "'items'", ")", ":", "params", "=", "params", ".", "items", "(", ")", "retval", "=", "[", "]", "for", "item", "in", "params", ":", "if", "isinstance", "(", "item", ",", "cls", ")", ":", "retval", ".", "append", "(", "item", ")", "continue", "name", ",", "value", "=", "item", "if", "isinstance", "(", "value", ",", "cls", ")", ":", "assert", "value", ".", "name", "==", "name", "retval", ".", "append", "(", "value", ")", "continue", "if", "hasattr", "(", "value", ",", "'read'", ")", ":", "# Looks like a file object", "filename", "=", "getattr", "(", "value", ",", "'name'", ",", "None", ")", "if", "filename", "is", "not", "None", ":", "filetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "else", ":", "filetype", "=", "None", "retval", ".", "append", "(", "cls", "(", "name", "=", "name", ",", "filename", "=", "filename", ",", "filetype", "=", "filetype", ",", "fileobj", "=", "value", ")", ")", "else", ":", "retval", ".", "append", "(", "cls", "(", "name", ",", "value", ")", ")", "return", "retval" ]
[ 180, 4 ]
[ 213, 21 ]
python
en
['en', 'en', 'en']
True
MultipartParam.encode_hdr
(self, boundary)
Returns the header of the encoding of this parameter
Returns the header of the encoding of this parameter
def encode_hdr(self, boundary): """Returns the header of the encoding of this parameter""" boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % ( self.name, to_string(self.filename)) else: disposition = 'form-data; name="%s"' % self.name headers.append("Content-Disposition: %s" % disposition) if self.filetype: filetype = to_string(self.filetype) else: filetype = "text/plain; charset=utf-8" headers.append("Content-Type: %s" % filetype) headers.append("") headers.append("") return "\r\n".join(headers)
[ "def", "encode_hdr", "(", "self", ",", "boundary", ")", ":", "boundary", "=", "encode_and_quote", "(", "boundary", ")", "headers", "=", "[", "\"--%s\"", "%", "boundary", "]", "if", "self", ".", "filename", ":", "disposition", "=", "'form-data; name=\"%s\"; filename=\"%s\"'", "%", "(", "self", ".", "name", ",", "to_string", "(", "self", ".", "filename", ")", ")", "else", ":", "disposition", "=", "'form-data; name=\"%s\"'", "%", "self", ".", "name", "headers", ".", "append", "(", "\"Content-Disposition: %s\"", "%", "disposition", ")", "if", "self", ".", "filetype", ":", "filetype", "=", "to_string", "(", "self", ".", "filetype", ")", "else", ":", "filetype", "=", "\"text/plain; charset=utf-8\"", "headers", ".", "append", "(", "\"Content-Type: %s\"", "%", "filetype", ")", "headers", ".", "append", "(", "\"\"", ")", "headers", ".", "append", "(", "\"\"", ")", "return", "\"\\r\\n\"", ".", "join", "(", "headers", ")" ]
[ 215, 4 ]
[ 239, 35 ]
python
en
['en', 'en', 'en']
True
MultipartParam.encode
(self, boundary)
Returns the string encoding of this parameter
Returns the string encoding of this parameter
def encode(self, boundary): """Returns the string encoding of this parameter""" if self.value is None: value = self.fileobj.read() else: value = self.value if re.search(to_bytes("^--%s$" % re.escape(boundary)), value, re.M): raise ValueError("boundary found in encoded string") return to_bytes(self.encode_hdr(boundary)) + value + b"\r\n"
[ "def", "encode", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "value", "is", "None", ":", "value", "=", "self", ".", "fileobj", ".", "read", "(", ")", "else", ":", "value", "=", "self", ".", "value", "if", "re", ".", "search", "(", "to_bytes", "(", "\"^--%s$\"", "%", "re", ".", "escape", "(", "boundary", ")", ")", ",", "value", ",", "re", ".", "M", ")", ":", "raise", "ValueError", "(", "\"boundary found in encoded string\"", ")", "return", "to_bytes", "(", "self", ".", "encode_hdr", "(", "boundary", ")", ")", "+", "value", "+", "b\"\\r\\n\"" ]
[ 241, 4 ]
[ 251, 68 ]
python
en
['en', 'en', 'en']
True
MultipartParam.iter_encode
(self, boundary, blocksize=4096)
Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.
Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.
def iter_encode(self, boundary, blocksize=4096): """Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.""" total = self.get_size(boundary) current = 0 if self.value is not None: block = self.encode(boundary) current += len(block) yield block if self.cb: self.cb(self, current, total) else: block = to_bytes(self.encode_hdr(boundary)) current += len(block) yield block if self.cb: self.cb(self, current, total) last_block = to_bytearray("") encoded_boundary = "--%s" % encode_and_quote(boundary) boundary_exp = re.compile( to_bytes("^%s$" % re.escape(encoded_boundary)), re.M) while True: block = self.fileobj.read(blocksize) if not block: current += 2 yield to_bytes("\r\n") if self.cb: self.cb(self, current, total) break last_block += block if boundary_exp.search(last_block): raise ValueError("boundary found in file data") last_block = last_block[-len(to_bytes(encoded_boundary))-2:] current += len(block) yield block if self.cb: self.cb(self, current, total)
[ "def", "iter_encode", "(", "self", ",", "boundary", ",", "blocksize", "=", "4096", ")", ":", "total", "=", "self", ".", "get_size", "(", "boundary", ")", "current", "=", "0", "if", "self", ".", "value", "is", "not", "None", ":", "block", "=", "self", ".", "encode", "(", "boundary", ")", "current", "+=", "len", "(", "block", ")", "yield", "block", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ",", "current", ",", "total", ")", "else", ":", "block", "=", "to_bytes", "(", "self", ".", "encode_hdr", "(", "boundary", ")", ")", "current", "+=", "len", "(", "block", ")", "yield", "block", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ",", "current", ",", "total", ")", "last_block", "=", "to_bytearray", "(", "\"\"", ")", "encoded_boundary", "=", "\"--%s\"", "%", "encode_and_quote", "(", "boundary", ")", "boundary_exp", "=", "re", ".", "compile", "(", "to_bytes", "(", "\"^%s$\"", "%", "re", ".", "escape", "(", "encoded_boundary", ")", ")", ",", "re", ".", "M", ")", "while", "True", ":", "block", "=", "self", ".", "fileobj", ".", "read", "(", "blocksize", ")", "if", "not", "block", ":", "current", "+=", "2", "yield", "to_bytes", "(", "\"\\r\\n\"", ")", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ",", "current", ",", "total", ")", "break", "last_block", "+=", "block", "if", "boundary_exp", ".", "search", "(", "last_block", ")", ":", "raise", "ValueError", "(", "\"boundary found in file data\"", ")", "last_block", "=", "last_block", "[", "-", "len", "(", "to_bytes", "(", "encoded_boundary", ")", ")", "-", "2", ":", "]", "current", "+=", "len", "(", "block", ")", "yield", "block", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ",", "current", ",", "total", ")" ]
[ 253, 4 ]
[ 290, 49 ]
python
en
['en', 'en', 'en']
True
MultipartParam.get_size
(self, boundary)
Returns the size in bytes that this param will be when encoded with the given boundary.
Returns the size in bytes that this param will be when encoded with the given boundary.
def get_size(self, boundary): """Returns the size in bytes that this param will be when encoded with the given boundary.""" if self.filesize is not None: valuesize = self.filesize else: valuesize = len(self.value) return len(self.encode_hdr(boundary)) + 2 + valuesize
[ "def", "get_size", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "filesize", "is", "not", "None", ":", "valuesize", "=", "self", ".", "filesize", "else", ":", "valuesize", "=", "len", "(", "self", ".", "value", ")", "return", "len", "(", "self", ".", "encode_hdr", "(", "boundary", ")", ")", "+", "2", "+", "valuesize" ]
[ 292, 4 ]
[ 300, 61 ]
python
en
['en', 'en', 'en']
True
multipart_yielder.next
(self)
generator function to yield multipart/form-data representation of parameters
generator function to yield multipart/form-data representation of parameters
def next(self): """generator function to yield multipart/form-data representation of parameters""" if self.param_iter is not None: try: block = advance_iterator(self.param_iter) self.current += len(block) if self.cb: self.cb(self.p, self.current, self.total) return block except StopIteration: self.p = None self.param_iter = None if self.i is None: raise StopIteration elif self.i >= len(self.params): self.param_iter = None self.p = None self.i = None block = to_bytes("--%s--\r\n" % self.boundary) self.current += len(block) if self.cb: self.cb(self.p, self.current, self.total) return block self.p = self.params[self.i] self.param_iter = self.p.iter_encode(self.boundary) self.i += 1 return advance_iterator(self)
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "param_iter", "is", "not", "None", ":", "try", ":", "block", "=", "advance_iterator", "(", "self", ".", "param_iter", ")", "self", ".", "current", "+=", "len", "(", "block", ")", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ".", "p", ",", "self", ".", "current", ",", "self", ".", "total", ")", "return", "block", "except", "StopIteration", ":", "self", ".", "p", "=", "None", "self", ".", "param_iter", "=", "None", "if", "self", ".", "i", "is", "None", ":", "raise", "StopIteration", "elif", "self", ".", "i", ">=", "len", "(", "self", ".", "params", ")", ":", "self", ".", "param_iter", "=", "None", "self", ".", "p", "=", "None", "self", ".", "i", "=", "None", "block", "=", "to_bytes", "(", "\"--%s--\\r\\n\"", "%", "self", ".", "boundary", ")", "self", ".", "current", "+=", "len", "(", "block", ")", "if", "self", ".", "cb", ":", "self", ".", "cb", "(", "self", ".", "p", ",", "self", ".", "current", ",", "self", ".", "total", ")", "return", "block", "self", ".", "p", "=", "self", ".", "params", "[", "self", ".", "i", "]", "self", ".", "param_iter", "=", "self", ".", "p", ".", "iter_encode", "(", "self", ".", "boundary", ")", "self", ".", "i", "+=", "1", "return", "advance_iterator", "(", "self", ")" ]
[ 369, 4 ]
[ 398, 37 ]
python
en
['en', 'en', 'en']
True
calculate_basic_statistics
(comparison_table: pandas.DataFrame)
Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table Returns -------
Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table
def calculate_basic_statistics(comparison_table: pandas.DataFrame)->pandas.DataFrame: """ Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table Returns ------- """ sample_columns = [i for i in comparison_table.columns if '-' in i] reference = comparison_table['ref'] mutation_category = comparison_table['mutationCategory'].copy() mutation_category_table = list() for sample_column in sample_columns: sample = comparison_table[sample_column] sample_variants = sample != reference sample_mutation_category = mutation_category[sample_variants].value_counts().to_dict() sample_mutation_category['sampleName'] = sample_column mutation_category_table.append(sample_mutation_category) mutation_category_table = pandas.DataFrame(mutation_category_table) mutation_category_table = mutation_category_table.fillna(0.0) try: mutation_category_table['dN/dS'] = mutation_category_table['snp_nonsynonymous'] / mutation_category_table['snp_synonymous'] except KeyError: mutation_category_table['dN/dS'] = 0 # Sort the columns so it behaves more consistently mutation_category_table = mutation_category_table[sorted(mutation_category_table.columns)] return mutation_category_table
[ "def", "calculate_basic_statistics", "(", "comparison_table", ":", "pandas", ".", "DataFrame", ")", "->", "pandas", ".", "DataFrame", ":", "sample_columns", "=", "[", "i", "for", "i", "in", "comparison_table", ".", "columns", "if", "'-'", "in", "i", "]", "reference", "=", "comparison_table", "[", "'ref'", "]", "mutation_category", "=", "comparison_table", "[", "'mutationCategory'", "]", ".", "copy", "(", ")", "mutation_category_table", "=", "list", "(", ")", "for", "sample_column", "in", "sample_columns", ":", "sample", "=", "comparison_table", "[", "sample_column", "]", "sample_variants", "=", "sample", "!=", "reference", "sample_mutation_category", "=", "mutation_category", "[", "sample_variants", "]", ".", "value_counts", "(", ")", ".", "to_dict", "(", ")", "sample_mutation_category", "[", "'sampleName'", "]", "=", "sample_column", "mutation_category_table", ".", "append", "(", "sample_mutation_category", ")", "mutation_category_table", "=", "pandas", ".", "DataFrame", "(", "mutation_category_table", ")", "mutation_category_table", "=", "mutation_category_table", ".", "fillna", "(", "0.0", ")", "try", ":", "mutation_category_table", "[", "'dN/dS'", "]", "=", "mutation_category_table", "[", "'snp_nonsynonymous'", "]", "/", "mutation_category_table", "[", "'snp_synonymous'", "]", "except", "KeyError", ":", "mutation_category_table", "[", "'dN/dS'", "]", "=", "0", "# Sort the columns so it behaves more consistently", "mutation_category_table", "=", "mutation_category_table", "[", "sorted", "(", "mutation_category_table", ".", "columns", ")", "]", "return", "mutation_category_table" ]
[ 6, 0 ]
[ 39, 31 ]
python
en
['en', 'error', 'th']
False
parse_bdist_wininst
(name)
Return (base,pyversion) or (None,None) for possible .exe name
Return (base,pyversion) or (None,None) for possible .exe name
def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower.startswith('.win32-py', -16): py_ver = name[-7:-4] base = name[:-16] plat = 'win32' elif lower.endswith('.win-amd64.exe'): base = name[:-14] plat = 'win-amd64' elif lower.startswith('.win-amd64-py', -20): py_ver = name[-7:-4] base = name[:-20] plat = 'win-amd64' return base, py_ver, plat
[ "def", "parse_bdist_wininst", "(", "name", ")", ":", "lower", "=", "name", ".", "lower", "(", ")", "base", ",", "py_ver", ",", "plat", "=", "None", ",", "None", ",", "None", "if", "lower", ".", "endswith", "(", "'.exe'", ")", ":", "if", "lower", ".", "endswith", "(", "'.win32.exe'", ")", ":", "base", "=", "name", "[", ":", "-", "10", "]", "plat", "=", "'win32'", "elif", "lower", ".", "startswith", "(", "'.win32-py'", ",", "-", "16", ")", ":", "py_ver", "=", "name", "[", "-", "7", ":", "-", "4", "]", "base", "=", "name", "[", ":", "-", "16", "]", "plat", "=", "'win32'", "elif", "lower", ".", "endswith", "(", "'.win-amd64.exe'", ")", ":", "base", "=", "name", "[", ":", "-", "14", "]", "plat", "=", "'win-amd64'", "elif", "lower", ".", "startswith", "(", "'.win-amd64-py'", ",", "-", "20", ")", ":", "py_ver", "=", "name", "[", "-", "7", ":", "-", "4", "]", "base", "=", "name", "[", ":", "-", "20", "]", "plat", "=", "'win-amd64'", "return", "base", ",", "py_ver", ",", "plat" ]
[ 58, 0 ]
[ 79, 29 ]
python
en
['en', 'en', 'en']
True
distros_for_url
(url, metadata=None)
Yield egg or source distribution objects that might be found at a URL
Yield egg or source distribution objects that might be found at a URL
def distros_for_url(url, metadata=None): """Yield egg or source distribution objects that might be found at a URL""" base, fragment = egg_info_for_url(url) for dist in distros_for_location(url, base, metadata): yield dist if fragment: match = EGG_FRAGMENT.match(fragment) if match: for dist in interpret_distro_name( url, match.group(1), metadata, precedence=CHECKOUT_DIST ): yield dist
[ "def", "distros_for_url", "(", "url", ",", "metadata", "=", "None", ")", ":", "base", ",", "fragment", "=", "egg_info_for_url", "(", "url", ")", "for", "dist", "in", "distros_for_location", "(", "url", ",", "base", ",", "metadata", ")", ":", "yield", "dist", "if", "fragment", ":", "match", "=", "EGG_FRAGMENT", ".", "match", "(", "fragment", ")", "if", "match", ":", "for", "dist", "in", "interpret_distro_name", "(", "url", ",", "match", ".", "group", "(", "1", ")", ",", "metadata", ",", "precedence", "=", "CHECKOUT_DIST", ")", ":", "yield", "dist" ]
[ 93, 0 ]
[ 104, 26 ]
python
en
['en', 'en', 'en']
True
distros_for_location
(location, basename, metadata=None)
Yield egg or source distribution objects based on basename
Yield egg or source distribution objects based on basename
def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretation return [Distribution.from_location(location, basename, metadata)] if basename.endswith('.whl') and '-' in basename: wheel = Wheel(basename) if not wheel.is_compatible(): return [] return [Distribution( location=location, project_name=wheel.project_name, version=wheel.version, # Increase priority over eggs. precedence=EGG_DIST + 1, )] if basename.endswith('.exe'): win_base, py_ver, platform = parse_bdist_wininst(basename) if win_base is not None: return interpret_distro_name( location, win_base, metadata, py_ver, BINARY_DIST, platform ) # Try source distro extensions (.zip, .tgz, etc.) # for ext in EXTENSIONS: if basename.endswith(ext): basename = basename[:-len(ext)] return interpret_distro_name(location, basename, metadata) return []
[ "def", "distros_for_location", "(", "location", ",", "basename", ",", "metadata", "=", "None", ")", ":", "if", "basename", ".", "endswith", "(", "'.egg.zip'", ")", ":", "basename", "=", "basename", "[", ":", "-", "4", "]", "# strip the .zip", "if", "basename", ".", "endswith", "(", "'.egg'", ")", "and", "'-'", "in", "basename", ":", "# only one, unambiguous interpretation", "return", "[", "Distribution", ".", "from_location", "(", "location", ",", "basename", ",", "metadata", ")", "]", "if", "basename", ".", "endswith", "(", "'.whl'", ")", "and", "'-'", "in", "basename", ":", "wheel", "=", "Wheel", "(", "basename", ")", "if", "not", "wheel", ".", "is_compatible", "(", ")", ":", "return", "[", "]", "return", "[", "Distribution", "(", "location", "=", "location", ",", "project_name", "=", "wheel", ".", "project_name", ",", "version", "=", "wheel", ".", "version", ",", "# Increase priority over eggs.", "precedence", "=", "EGG_DIST", "+", "1", ",", ")", "]", "if", "basename", ".", "endswith", "(", "'.exe'", ")", ":", "win_base", ",", "py_ver", ",", "platform", "=", "parse_bdist_wininst", "(", "basename", ")", "if", "win_base", "is", "not", "None", ":", "return", "interpret_distro_name", "(", "location", ",", "win_base", ",", "metadata", ",", "py_ver", ",", "BINARY_DIST", ",", "platform", ")", "# Try source distro extensions (.zip, .tgz, etc.)", "#", "for", "ext", "in", "EXTENSIONS", ":", "if", "basename", ".", "endswith", "(", "ext", ")", ":", "basename", "=", "basename", "[", ":", "-", "len", "(", "ext", ")", "]", "return", "interpret_distro_name", "(", "location", ",", "basename", ",", "metadata", ")", "return", "[", "]" ]
[ 107, 0 ]
[ 137, 13 ]
python
en
['en', 'en', 'en']
True
distros_for_filename
(filename, metadata=None)
Yield possible egg or source distribution objects based on a filename
Yield possible egg or source distribution objects based on a filename
def distros_for_filename(filename, metadata=None): """Yield possible egg or source distribution objects based on a filename""" return distros_for_location( normalize_path(filename), os.path.basename(filename), metadata )
[ "def", "distros_for_filename", "(", "filename", ",", "metadata", "=", "None", ")", ":", "return", "distros_for_location", "(", "normalize_path", "(", "filename", ")", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "metadata", ")" ]
[ 140, 0 ]
[ 144, 5 ]
python
en
['en', 'en', 'en']
True
interpret_distro_name
( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None )
Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine!
Generate alternative interpretations of a source distro name
def interpret_distro_name( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine! """ # Generate alternative interpretations of a source distro name # Because some packages are ambiguous as to name/versions split # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, # the spurious interpretations should be ignored, because in the event # there's also an "adns" package, the spurious "python-1.1.0" version will # compare lower than any numeric version number, and is therefore unlikely # to match a request for it. It's still a potential problem, though, and # in the long run PyPI and the distutils should go for "safe" names and # versions in distribution archive names (sdist and bdist). parts = basename.split('-') if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]): # it is a bdist_dumb, not an sdist -- bail out return for p in range(1, len(parts) + 1): yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence=precedence, platform=platform )
[ "def", "interpret_distro_name", "(", "location", ",", "basename", ",", "metadata", ",", "py_version", "=", "None", ",", "precedence", "=", "SOURCE_DIST", ",", "platform", "=", "None", ")", ":", "# Generate alternative interpretations of a source distro name", "# Because some packages are ambiguous as to name/versions split", "# e.g. \"adns-python-1.1.0\", \"egenix-mx-commercial\", etc.", "# So, we generate each possible interepretation (e.g. \"adns, python-1.1.0\"", "# \"adns-python, 1.1.0\", and \"adns-python-1.1.0, no version\"). In practice,", "# the spurious interpretations should be ignored, because in the event", "# there's also an \"adns\" package, the spurious \"python-1.1.0\" version will", "# compare lower than any numeric version number, and is therefore unlikely", "# to match a request for it. It's still a potential problem, though, and", "# in the long run PyPI and the distutils should go for \"safe\" names and", "# versions in distribution archive names (sdist and bdist).", "parts", "=", "basename", ".", "split", "(", "'-'", ")", "if", "not", "py_version", "and", "any", "(", "re", ".", "match", "(", "r'py\\d\\.\\d$'", ",", "p", ")", "for", "p", "in", "parts", "[", "2", ":", "]", ")", ":", "# it is a bdist_dumb, not an sdist -- bail out", "return", "for", "p", "in", "range", "(", "1", ",", "len", "(", "parts", ")", "+", "1", ")", ":", "yield", "Distribution", "(", "location", ",", "metadata", ",", "'-'", ".", "join", "(", "parts", "[", ":", "p", "]", ")", ",", "'-'", ".", "join", "(", "parts", "[", "p", ":", "]", ")", ",", "py_version", "=", "py_version", ",", "precedence", "=", "precedence", ",", "platform", "=", "platform", ")" ]
[ 147, 0 ]
[ 179, 9 ]
python
en
['en', 'it', 'en']
True
unique_everseen
(iterable, key=None)
List unique elements, preserving order. Remember all elements ever seen.
List unique elements, preserving order. Remember all elements ever seen.
def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in six.moves.filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
[ "def", "unique_everseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "# unique_everseen('AAAABBBCCDAABBB') --> A B C D", "# unique_everseen('ABBCcAD', str.lower) --> A B C D", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "if", "key", "is", "None", ":", "for", "element", "in", "six", ".", "moves", ".", "filterfalse", "(", "seen", ".", "__contains__", ",", "iterable", ")", ":", "seen_add", "(", "element", ")", "yield", "element", "else", ":", "for", "element", "in", "iterable", ":", "k", "=", "key", "(", "element", ")", "if", "k", "not", "in", "seen", ":", "seen_add", "(", "k", ")", "yield", "element" ]
[ 183, 0 ]
[ 198, 29 ]
python
ca
['ca', 'ca', 'en']
True
unique_values
(func)
Wrap a function returning an iterable such that the resulting iterable only ever yields unique items.
Wrap a function returning an iterable such that the resulting iterable only ever yields unique items.
def unique_values(func): """ Wrap a function returning an iterable such that the resulting iterable only ever yields unique items. """ @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper
[ "def", "unique_values", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "unique_everseen", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "wrapper" ]
[ 201, 0 ]
[ 211, 18 ]
python
en
['en', 'error', 'th']
False
find_external_links
(url, page)
Find rel="homepage" and rel="download" links in `page`, yielding URLs
Find rel="homepage" and rel="download" links in `page`, yielding URLs
def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for match in HREF.finditer(tag): yield urllib.parse.urljoin(url, htmldecode(match.group(1))) for tag in ("<th>Home Page", "<th>Download URL"): pos = page.find(tag) if pos != -1: match = HREF.search(page, pos) if match: yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
[ "def", "find_external_links", "(", "url", ",", "page", ")", ":", "for", "match", "in", "REL", ".", "finditer", "(", "page", ")", ":", "tag", ",", "rel", "=", "match", ".", "groups", "(", ")", "rels", "=", "set", "(", "map", "(", "str", ".", "strip", ",", "rel", ".", "lower", "(", ")", ".", "split", "(", "','", ")", ")", ")", "if", "'homepage'", "in", "rels", "or", "'download'", "in", "rels", ":", "for", "match", "in", "HREF", ".", "finditer", "(", "tag", ")", ":", "yield", "urllib", ".", "parse", ".", "urljoin", "(", "url", ",", "htmldecode", "(", "match", ".", "group", "(", "1", ")", ")", ")", "for", "tag", "in", "(", "\"<th>Home Page\"", ",", "\"<th>Download URL\"", ")", ":", "pos", "=", "page", ".", "find", "(", "tag", ")", "if", "pos", "!=", "-", "1", ":", "match", "=", "HREF", ".", "search", "(", "page", ",", "pos", ")", "if", "match", ":", "yield", "urllib", ".", "parse", ".", "urljoin", "(", "url", ",", "htmldecode", "(", "match", ".", "group", "(", "1", ")", ")", ")" ]
[ 219, 0 ]
[ 234, 75 ]
python
en
['en', 'en', 'en']
True
htmldecode
(text)
Decode HTML entities in the given text.
Decode HTML entities in the given text.
def htmldecode(text): """Decode HTML entities in the given text.""" return entity_sub(decode_entity, text)
[ "def", "htmldecode", "(", "text", ")", ":", "return", "entity_sub", "(", "decode_entity", ",", "text", ")" ]
[ 939, 0 ]
[ 941, 42 ]
python
en
['en', 'en', 'en']
True
_encode_auth
(auth)
A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:' + 'password'*10 >>> chr(10) in str(_encode_auth(long_auth)) False
A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ='
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:' + 'password'*10 >>> chr(10) in str(_encode_auth(long_auth)) False """ auth_s = urllib.parse.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() # use the legacy interface for Python 2.3 support encoded_bytes = base64.encodestring(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.replace('\n', '')
[ "def", "_encode_auth", "(", "auth", ")", ":", "auth_s", "=", "urllib", ".", "parse", ".", "unquote", "(", "auth", ")", "# convert to bytes", "auth_bytes", "=", "auth_s", ".", "encode", "(", ")", "# use the legacy interface for Python 2.3 support", "encoded_bytes", "=", "base64", ".", "encodestring", "(", "auth_bytes", ")", "# convert back to a string", "encoded", "=", "encoded_bytes", ".", "decode", "(", ")", "# strip the trailing carriage return", "return", "encoded", ".", "replace", "(", "'\\n'", ",", "''", ")" ]
[ 959, 0 ]
[ 979, 36 ]
python
en
['en', 'error', 'th']
False
open_with_auth
(url, opener=urllib.request.urlopen)
Open a urllib2 request, handling HTTP authentication
Open a urllib2 request, handling HTTP authentication
def open_with_auth(url, opener=urllib.request.urlopen): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urllib.parse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise http_client.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = urllib.parse.splituser(netloc) else: auth = None if not auth: cred = PyPIConfig().find_credential(url) if cred: auth = str(cred) info = cred.username, url log.info('Authenticating as %s for %s (from .pypirc)', *info) if auth: auth = "Basic " + _encode_auth(auth) parts = scheme, host, path, params, query, frag new_url = urllib.parse.urlunparse(parts) request = urllib.request.Request(new_url) request.add_header("Authorization", auth) else: request = urllib.request.Request(url) request.add_header('User-Agent', user_agent) fp = opener(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url) if s2 == scheme and h2 == host: parts = s2, netloc, path2, param2, query2, frag2 fp.url = urllib.parse.urlunparse(parts) return fp
[ "def", "open_with_auth", "(", "url", ",", "opener", "=", "urllib", ".", "request", ".", "urlopen", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "frag", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "# Double scheme does not raise on Mac OS X as revealed by a", "# failing test. We would expect \"nonnumeric port\". Refs #20.", "if", "netloc", ".", "endswith", "(", "':'", ")", ":", "raise", "http_client", ".", "InvalidURL", "(", "\"nonnumeric port: ''\"", ")", "if", "scheme", "in", "(", "'http'", ",", "'https'", ")", ":", "auth", ",", "host", "=", "urllib", ".", "parse", ".", "splituser", "(", "netloc", ")", "else", ":", "auth", "=", "None", "if", "not", "auth", ":", "cred", "=", "PyPIConfig", "(", ")", ".", "find_credential", "(", "url", ")", "if", "cred", ":", "auth", "=", "str", "(", "cred", ")", "info", "=", "cred", ".", "username", ",", "url", "log", ".", "info", "(", "'Authenticating as %s for %s (from .pypirc)'", ",", "*", "info", ")", "if", "auth", ":", "auth", "=", "\"Basic \"", "+", "_encode_auth", "(", "auth", ")", "parts", "=", "scheme", ",", "host", ",", "path", ",", "params", ",", "query", ",", "frag", "new_url", "=", "urllib", ".", "parse", ".", "urlunparse", "(", "parts", ")", "request", "=", "urllib", ".", "request", ".", "Request", "(", "new_url", ")", "request", ".", "add_header", "(", "\"Authorization\"", ",", "auth", ")", "else", ":", "request", "=", "urllib", ".", "request", ".", "Request", "(", "url", ")", "request", ".", "add_header", "(", "'User-Agent'", ",", "user_agent", ")", "fp", "=", "opener", "(", "request", ")", "if", "auth", ":", "# Put authentication info back into request URL if same host,", "# so that links found on the page will work", "s2", ",", "h2", ",", "path2", ",", "param2", ",", "query2", ",", "frag2", "=", "urllib", ".", "parse", ".", "urlparse", "(", "fp", ".", "url", ")", "if", "s2", "==", "scheme", "and", "h2", "==", "host", ":", "parts", "=", "s2", ",", "netloc", ",", "path2", ",", "param2", ",", "query2", ",", "frag2", "fp", ".", "url", "=", "urllib", ".", "parse", ".", "urlunparse", "(", "parts", ")", "return", "fp" ]
[ 1037, 0 ]
[ 1079, 13 ]
python
en
['en', 'lb', 'en']
True
local_open
(url)
Read a local path, with special support for directories
Read a local path, with special support for directories
def local_open(url): """Read a local path, with special support for directories""" scheme, server, path, param, query, frag = urllib.parse.urlparse(url) filename = urllib.request.url2pathname(path) if os.path.isfile(filename): return urllib.request.urlopen(url) elif path.endswith('/') and os.path.isdir(filename): files = [] for f in os.listdir(filename): filepath = os.path.join(filename, f) if f == 'index.html': with open(filepath, 'r') as fp: body = fp.read() break elif os.path.isdir(filepath): f += '/' files.append('<a href="{name}">{name}</a>'.format(name=f)) else: tmpl = ( "<html><head><title>{url}</title>" "</head><body>{files}</body></html>") body = tmpl.format(url=url, files='\n'.join(files)) status, message = 200, "OK" else: status, message, body = 404, "Path not found", "Not found" headers = {'content-type': 'text/html'} body_stream = six.StringIO(body) return urllib.error.HTTPError(url, status, message, headers, body_stream)
[ "def", "local_open", "(", "url", ")", ":", "scheme", ",", "server", ",", "path", ",", "param", ",", "query", ",", "frag", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "filename", "=", "urllib", ".", "request", ".", "url2pathname", "(", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "elif", "path", ".", "endswith", "(", "'/'", ")", "and", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "files", "=", "[", "]", "for", "f", "in", "os", ".", "listdir", "(", "filename", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "filename", ",", "f", ")", "if", "f", "==", "'index.html'", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "fp", ":", "body", "=", "fp", ".", "read", "(", ")", "break", "elif", "os", ".", "path", ".", "isdir", "(", "filepath", ")", ":", "f", "+=", "'/'", "files", ".", "append", "(", "'<a href=\"{name}\">{name}</a>'", ".", "format", "(", "name", "=", "f", ")", ")", "else", ":", "tmpl", "=", "(", "\"<html><head><title>{url}</title>\"", "\"</head><body>{files}</body></html>\"", ")", "body", "=", "tmpl", ".", "format", "(", "url", "=", "url", ",", "files", "=", "'\\n'", ".", "join", "(", "files", ")", ")", "status", ",", "message", "=", "200", ",", "\"OK\"", "else", ":", "status", ",", "message", ",", "body", "=", "404", ",", "\"Path not found\"", ",", "\"Not found\"", "headers", "=", "{", "'content-type'", ":", "'text/html'", "}", "body_stream", "=", "six", ".", "StringIO", "(", "body", ")", "return", "urllib", ".", "error", ".", "HTTPError", "(", "url", ",", "status", ",", "message", ",", "headers", ",", "body_stream", ")" ]
[ 1090, 0 ]
[ 1118, 77 ]
python
en
['en', 'en', 'en']
True
ContentChecker.feed
(self, block)
Feed a block of data to the hash.
Feed a block of data to the hash.
def feed(self, block): """ Feed a block of data to the hash. """ return
[ "def", "feed", "(", "self", ",", "block", ")", ":", "return" ]
[ 242, 4 ]
[ 246, 14 ]
python
en
['en', 'error', 'th']
False
ContentChecker.is_valid
(self)
Check the hash. Return False if validation fails.
Check the hash. Return False if validation fails.
def is_valid(self): """ Check the hash. Return False if validation fails. """ return True
[ "def", "is_valid", "(", "self", ")", ":", "return", "True" ]
[ 248, 4 ]
[ 252, 19 ]
python
en
['en', 'error', 'th']
False
ContentChecker.report
(self, reporter, template)
Call reporter with information about the checker (hash name) substituted into the template.
Call reporter with information about the checker (hash name) substituted into the template.
def report(self, reporter, template): """ Call reporter with information about the checker (hash name) substituted into the template. """ return
[ "def", "report", "(", "self", ",", "reporter", ",", "template", ")", ":", "return" ]
[ 254, 4 ]
[ 259, 14 ]
python
en
['en', 'error', 'th']
False
HashChecker.from_url
(cls, url)
Construct a (possibly null) ContentChecker from a URL
Construct a (possibly null) ContentChecker from a URL
def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urllib.parse.urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls(**match.groupdict())
[ "def", "from_url", "(", "cls", ",", "url", ")", ":", "fragment", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "[", "-", "1", "]", "if", "not", "fragment", ":", "return", "ContentChecker", "(", ")", "match", "=", "cls", ".", "pattern", ".", "search", "(", "fragment", ")", "if", "not", "match", ":", "return", "ContentChecker", "(", ")", "return", "cls", "(", "*", "*", "match", ".", "groupdict", "(", ")", ")" ]
[ 274, 4 ]
[ 282, 39 ]
python
en
['en', 'en', 'en']
True
PackageIndex.process_url
(self, url, retrieve=False)
Evaluate a URL as a possible download, and maybe retrieve it
Evaluate a URL as a possible download, and maybe retrieve it
def process_url(self, url, retrieve=False): """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return else: dists = list(distros_for_url(url)) if dists: if not self.url_ok(url): return self.debug("Found link: %s", url) if dists or not retrieve or url in self.fetched_urls: list(map(self.add, dists)) return # don't need the actual page if not self.url_ok(url): self.fetched_urls[url] = True return self.info("Reading %s", url) self.fetched_urls[url] = True # prevent multiple fetch attempts tmpl = "Download error on %s: %%s -- Some packages may not be found!" f = self.open_url(url, tmpl % url) if f is None: return self.fetched_urls[f.url] = True if 'html' not in f.headers.get('content-type', '').lower(): f.close() # not html, we can't process it return base = f.url # handle redirects page = f.read() if not isinstance(page, str): # In Python 3 and got bytes but want str. if isinstance(f, urllib.error.HTTPError): # Errors have no charset, assume latin1: charset = 'latin-1' else: charset = f.headers.get_param('charset') or 'latin-1' page = page.decode(charset, "ignore") f.close() for match in HREF.finditer(page): link = urllib.parse.urljoin(base, htmldecode(match.group(1))) self.process_url(link) if url.startswith(self.index_url) and getattr(f, 'code', None) != 404: page = self.process_index(url, page)
[ "def", "process_url", "(", "self", ",", "url", ",", "retrieve", "=", "False", ")", ":", "if", "url", "in", "self", ".", "scanned_urls", "and", "not", "retrieve", ":", "return", "self", ".", "scanned_urls", "[", "url", "]", "=", "True", "if", "not", "URL_SCHEME", "(", "url", ")", ":", "self", ".", "process_filename", "(", "url", ")", "return", "else", ":", "dists", "=", "list", "(", "distros_for_url", "(", "url", ")", ")", "if", "dists", ":", "if", "not", "self", ".", "url_ok", "(", "url", ")", ":", "return", "self", ".", "debug", "(", "\"Found link: %s\"", ",", "url", ")", "if", "dists", "or", "not", "retrieve", "or", "url", "in", "self", ".", "fetched_urls", ":", "list", "(", "map", "(", "self", ".", "add", ",", "dists", ")", ")", "return", "# don't need the actual page", "if", "not", "self", ".", "url_ok", "(", "url", ")", ":", "self", ".", "fetched_urls", "[", "url", "]", "=", "True", "return", "self", ".", "info", "(", "\"Reading %s\"", ",", "url", ")", "self", ".", "fetched_urls", "[", "url", "]", "=", "True", "# prevent multiple fetch attempts", "tmpl", "=", "\"Download error on %s: %%s -- Some packages may not be found!\"", "f", "=", "self", ".", "open_url", "(", "url", ",", "tmpl", "%", "url", ")", "if", "f", "is", "None", ":", "return", "self", ".", "fetched_urls", "[", "f", ".", "url", "]", "=", "True", "if", "'html'", "not", "in", "f", ".", "headers", ".", "get", "(", "'content-type'", ",", "''", ")", ".", "lower", "(", ")", ":", "f", ".", "close", "(", ")", "# not html, we can't process it", "return", "base", "=", "f", ".", "url", "# handle redirects", "page", "=", "f", ".", "read", "(", ")", "if", "not", "isinstance", "(", "page", ",", "str", ")", ":", "# In Python 3 and got bytes but want str.", "if", "isinstance", "(", "f", ",", "urllib", ".", "error", ".", "HTTPError", ")", ":", "# Errors have no charset, assume latin1:", "charset", "=", "'latin-1'", "else", ":", "charset", "=", "f", ".", "headers", ".", "get_param", "(", "'charset'", ")", "or", "'latin-1'", "page", "=", "page", ".", "decode", "(", "charset", ",", "\"ignore\"", ")", "f", ".", "close", "(", ")", "for", "match", "in", "HREF", ".", "finditer", "(", "page", ")", ":", "link", "=", "urllib", ".", "parse", ".", "urljoin", "(", "base", ",", "htmldecode", "(", "match", ".", "group", "(", "1", ")", ")", ")", "self", ".", "process_url", "(", "link", ")", "if", "url", ".", "startswith", "(", "self", ".", "index_url", ")", "and", "getattr", "(", "f", ",", "'code'", ",", "None", ")", "!=", "404", ":", "page", "=", "self", ".", "process_index", "(", "url", ",", "page", ")" ]
[ 319, 4 ]
[ 368, 48 ]
python
en
['en', 'en', 'en']
True
PackageIndex.process_index
(self, url, page)
Process the contents of a PyPI page
Process the contents of a PyPI page
def process_index(self, url, page): """Process the contents of a PyPI page""" def scan(link): # Process a URL to see if it's for a package page if link.startswith(self.index_url): parts = list(map( urllib.parse.unquote, link[len(self.index_url):].split('/') )) if len(parts) == 2 and '#' not in parts[1]: # it's a package page, sanitize and index it pkg = safe_name(parts[0]) ver = safe_version(parts[1]) self.package_pages.setdefault(pkg.lower(), {})[link] = True return to_filename(pkg), to_filename(ver) return None, None # process an index page into the package-page index for match in HREF.finditer(page): try: scan(urllib.parse.urljoin(url, htmldecode(match.group(1)))) except ValueError: pass pkg, ver = scan(url) # ensure this page is in the page index if pkg: # process individual package page for new_url in find_external_links(url, page): # Process the found URL base, frag = egg_info_for_url(new_url) if base.endswith('.py') and not frag: if ver: new_url += '#egg=%s-%s' % (pkg, ver) else: self.need_version_info(url) self.scan_url(new_url) return PYPI_MD5.sub( lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page ) else: return ""
[ "def", "process_index", "(", "self", ",", "url", ",", "page", ")", ":", "def", "scan", "(", "link", ")", ":", "# Process a URL to see if it's for a package page", "if", "link", ".", "startswith", "(", "self", ".", "index_url", ")", ":", "parts", "=", "list", "(", "map", "(", "urllib", ".", "parse", ".", "unquote", ",", "link", "[", "len", "(", "self", ".", "index_url", ")", ":", "]", ".", "split", "(", "'/'", ")", ")", ")", "if", "len", "(", "parts", ")", "==", "2", "and", "'#'", "not", "in", "parts", "[", "1", "]", ":", "# it's a package page, sanitize and index it", "pkg", "=", "safe_name", "(", "parts", "[", "0", "]", ")", "ver", "=", "safe_version", "(", "parts", "[", "1", "]", ")", "self", ".", "package_pages", ".", "setdefault", "(", "pkg", ".", "lower", "(", ")", ",", "{", "}", ")", "[", "link", "]", "=", "True", "return", "to_filename", "(", "pkg", ")", ",", "to_filename", "(", "ver", ")", "return", "None", ",", "None", "# process an index page into the package-page index", "for", "match", "in", "HREF", ".", "finditer", "(", "page", ")", ":", "try", ":", "scan", "(", "urllib", ".", "parse", ".", "urljoin", "(", "url", ",", "htmldecode", "(", "match", ".", "group", "(", "1", ")", ")", ")", ")", "except", "ValueError", ":", "pass", "pkg", ",", "ver", "=", "scan", "(", "url", ")", "# ensure this page is in the page index", "if", "pkg", ":", "# process individual package page", "for", "new_url", "in", "find_external_links", "(", "url", ",", "page", ")", ":", "# Process the found URL", "base", ",", "frag", "=", "egg_info_for_url", "(", "new_url", ")", "if", "base", ".", "endswith", "(", "'.py'", ")", "and", "not", "frag", ":", "if", "ver", ":", "new_url", "+=", "'#egg=%s-%s'", "%", "(", "pkg", ",", "ver", ")", "else", ":", "self", ".", "need_version_info", "(", "url", ")", "self", ".", "scan_url", "(", "new_url", ")", "return", "PYPI_MD5", ".", "sub", "(", "lambda", "m", ":", "'<a href=\"%s#md5=%s\">%s</a>'", "%", "m", ".", "group", "(", "1", ",", "3", ",", "2", ")", ",", "page", ")", "else", ":", "return", "\"\"" ]
[ 425, 4 ]
[ 466, 21 ]
python
en
['en', 'en', 'en']
True
PackageIndex.check_hash
(self, checker, filename, tfp)
checker is a ContentChecker
checker is a ContentChecker
def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report( self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise DistutilsError( "%s validation failed for %s; " "possible download problem?" % (checker.hash.name, os.path.basename(filename)) )
[ "def", "check_hash", "(", "self", ",", "checker", ",", "filename", ",", "tfp", ")", ":", "checker", ".", "report", "(", "self", ".", "debug", ",", "\"Validating %%s checksum for %s\"", "%", "filename", ")", "if", "not", "checker", ".", "is_valid", "(", ")", ":", "tfp", ".", "close", "(", ")", "os", ".", "unlink", "(", "filename", ")", "raise", "DistutilsError", "(", "\"%s validation failed for %s; \"", "\"possible download problem?\"", "%", "(", "checker", ".", "hash", ".", "name", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", ")" ]
[ 507, 4 ]
[ 521, 13 ]
python
en
['en', 'error', 'th']
False
PackageIndex.add_find_links
(self, urls)
Add `urls` to the list that will be prescanned for searches
Add `urls` to the list that will be prescanned for searches
def add_find_links(self, urls): """Add `urls` to the list that will be prescanned for searches""" for url in urls: if ( self.to_scan is None # if we have already "gone online" or not URL_SCHEME(url) # or it's a local file/directory or url.startswith('file:') or list(distros_for_url(url)) # or a direct package link ): # then go ahead and process it now self.scan_url(url) else: # otherwise, defer retrieval till later self.to_scan.append(url)
[ "def", "add_find_links", "(", "self", ",", "urls", ")", ":", "for", "url", "in", "urls", ":", "if", "(", "self", ".", "to_scan", "is", "None", "# if we have already \"gone online\"", "or", "not", "URL_SCHEME", "(", "url", ")", "# or it's a local file/directory", "or", "url", ".", "startswith", "(", "'file:'", ")", "or", "list", "(", "distros_for_url", "(", "url", ")", ")", "# or a direct package link", ")", ":", "# then go ahead and process it now", "self", ".", "scan_url", "(", "url", ")", "else", ":", "# otherwise, defer retrieval till later", "self", ".", "to_scan", ".", "append", "(", "url", ")" ]
[ 523, 4 ]
[ 536, 40 ]
python
en
['en', 'en', 'en']
True
PackageIndex.prescan
(self)
Scan urls scheduled for prescanning (e.g. --find-links)
Scan urls scheduled for prescanning (e.g. --find-links)
def prescan(self): """Scan urls scheduled for prescanning (e.g. --find-links)""" if self.to_scan: list(map(self.scan_url, self.to_scan)) self.to_scan = None
[ "def", "prescan", "(", "self", ")", ":", "if", "self", ".", "to_scan", ":", "list", "(", "map", "(", "self", ".", "scan_url", ",", "self", ".", "to_scan", ")", ")", "self", ".", "to_scan", "=", "None" ]
[ 538, 4 ]
[ 542, 27 ]
python
en
['en', 'de', 'en']
True
PackageIndex.download
(self, spec, tmpdir)
Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is automatically created alongside the downloaded file. If `spec` is a ``Requirement`` object or a string containing a project/version requirement spec, this method returns the location of a matching distribution (possibly after downloading it to `tmpdir`). If `spec` is a locally existing file or directory name, it is simply returned unchanged. If `spec` is a URL, it is downloaded to a subpath of `tmpdir`, and the local filename is returned. Various errors may be raised if a problem occurs during downloading.
Locate and/or download `spec` to `tmpdir`, returning a local path
def download(self, spec, tmpdir): """Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is automatically created alongside the downloaded file. If `spec` is a ``Requirement`` object or a string containing a project/version requirement spec, this method returns the location of a matching distribution (possibly after downloading it to `tmpdir`). If `spec` is a locally existing file or directory name, it is simply returned unchanged. If `spec` is a URL, it is downloaded to a subpath of `tmpdir`, and the local filename is returned. Various errors may be raised if a problem occurs during downloading. """ if not isinstance(spec, Requirement): scheme = URL_SCHEME(spec) if scheme: # It's a url, download it to tmpdir found = self._download_url(scheme.group(1), spec, tmpdir) base, fragment = egg_info_for_url(spec) if base.endswith('.py'): found = self.gen_setup(found, fragment, tmpdir) return found elif os.path.exists(spec): # Existing file or directory, just return it return spec else: spec = parse_requirement_arg(spec) return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
[ "def", "download", "(", "self", ",", "spec", ",", "tmpdir", ")", ":", "if", "not", "isinstance", "(", "spec", ",", "Requirement", ")", ":", "scheme", "=", "URL_SCHEME", "(", "spec", ")", "if", "scheme", ":", "# It's a url, download it to tmpdir", "found", "=", "self", ".", "_download_url", "(", "scheme", ".", "group", "(", "1", ")", ",", "spec", ",", "tmpdir", ")", "base", ",", "fragment", "=", "egg_info_for_url", "(", "spec", ")", "if", "base", ".", "endswith", "(", "'.py'", ")", ":", "found", "=", "self", ".", "gen_setup", "(", "found", ",", "fragment", ",", "tmpdir", ")", "return", "found", "elif", "os", ".", "path", ".", "exists", "(", "spec", ")", ":", "# Existing file or directory, just return it", "return", "spec", "else", ":", "spec", "=", "parse_requirement_arg", "(", "spec", ")", "return", "getattr", "(", "self", ".", "fetch_distribution", "(", "spec", ",", "tmpdir", ")", ",", "'location'", ",", "None", ")" ]
[ 554, 4 ]
[ 586, 79 ]
python
en
['en', 'en', 'en']
True
PackageIndex.fetch_distribution
( self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None)
Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored.
Obtain a distribution suitable for fulfilling `requirement`
def fetch_distribution( self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = {} dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence == DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn( "Skipping development or system egg: %s", dist, ) skipped[dist] = 1 continue test = ( dist in req and (dist.precedence <= SOURCE_DIST or not source) ) if test: loc = self.download(dist.location, tmpdir) dist.download_location = loc if os.path.exists(dist.download_location): return dist if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if not dist and local_index is not None: dist = find(requirement, local_index) if dist is None: if self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or working download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) else: self.info("Best match: %s", dist) return dist.clone(location=dist.download_location)
[ "def", "fetch_distribution", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ",", "develop_ok", "=", "False", ",", "local_index", "=", "None", ")", ":", "# process a Requirement", "self", ".", "info", "(", "\"Searching for %s\"", ",", "requirement", ")", "skipped", "=", "{", "}", "dist", "=", "None", "def", "find", "(", "req", ",", "env", "=", "None", ")", ":", "if", "env", "is", "None", ":", "env", "=", "self", "# Find a matching distribution; may be called more than once", "for", "dist", "in", "env", "[", "req", ".", "key", "]", ":", "if", "dist", ".", "precedence", "==", "DEVELOP_DIST", "and", "not", "develop_ok", ":", "if", "dist", "not", "in", "skipped", ":", "self", ".", "warn", "(", "\"Skipping development or system egg: %s\"", ",", "dist", ",", ")", "skipped", "[", "dist", "]", "=", "1", "continue", "test", "=", "(", "dist", "in", "req", "and", "(", "dist", ".", "precedence", "<=", "SOURCE_DIST", "or", "not", "source", ")", ")", "if", "test", ":", "loc", "=", "self", ".", "download", "(", "dist", ".", "location", ",", "tmpdir", ")", "dist", ".", "download_location", "=", "loc", "if", "os", ".", "path", ".", "exists", "(", "dist", ".", "download_location", ")", ":", "return", "dist", "if", "force_scan", ":", "self", ".", "prescan", "(", ")", "self", ".", "find_packages", "(", "requirement", ")", "dist", "=", "find", "(", "requirement", ")", "if", "not", "dist", "and", "local_index", "is", "not", "None", ":", "dist", "=", "find", "(", "requirement", ",", "local_index", ")", "if", "dist", "is", "None", ":", "if", "self", ".", "to_scan", "is", "not", "None", ":", "self", ".", "prescan", "(", ")", "dist", "=", "find", "(", "requirement", ")", "if", "dist", "is", "None", "and", "not", "force_scan", ":", "self", ".", "find_packages", "(", "requirement", ")", "dist", "=", "find", "(", "requirement", ")", "if", "dist", "is", "None", ":", "self", ".", "warn", "(", "\"No local packages or working download links found for %s%s\"", ",", "(", "source", "and", "\"a source distribution of \"", "or", "\"\"", ")", ",", "requirement", ",", ")", "else", ":", "self", ".", "info", "(", "\"Best match: %s\"", ",", "dist", ")", "return", "dist", ".", "clone", "(", "location", "=", "dist", ".", "download_location", ")" ]
[ 588, 4 ]
[ 662, 62 ]
python
en
['en', 'en', 'en']
True
PackageIndex.fetch
(self, requirement, tmpdir, force_scan=False, source=False)
Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object.
Obtain a file suitable for fulfilling `requirement`
def fetch(self, requirement, tmpdir, force_scan=False, source=False): """Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object. """ dist = self.fetch_distribution(requirement, tmpdir, force_scan, source) if dist is not None: return dist.location return None
[ "def", "fetch", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ")", ":", "dist", "=", "self", ".", "fetch_distribution", "(", "requirement", ",", "tmpdir", ",", "force_scan", ",", "source", ")", "if", "dist", "is", "not", "None", ":", "return", "dist", ".", "location", "return", "None" ]
[ 664, 4 ]
[ 675, 19 ]
python
en
['en', 'en', 'en']
True
PyPIConfig.__init__
(self)
Load from ~/.pypirc
Load from ~/.pypirc
def __init__(self): """ Load from ~/.pypirc """ defaults = dict.fromkeys(['username', 'password', 'repository'], '') configparser.RawConfigParser.__init__(self, defaults) rc = os.path.join(os.path.expanduser('~'), '.pypirc') if os.path.exists(rc): self.read(rc)
[ "def", "__init__", "(", "self", ")", ":", "defaults", "=", "dict", ".", "fromkeys", "(", "[", "'username'", ",", "'password'", ",", "'repository'", "]", ",", "''", ")", "configparser", ".", "RawConfigParser", ".", "__init__", "(", "self", ",", "defaults", ")", "rc", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.pypirc'", ")", "if", "os", ".", "path", ".", "exists", "(", "rc", ")", ":", "self", ".", "read", "(", "rc", ")" ]
[ 1000, 4 ]
[ 1009, 25 ]
python
en
['en', 'error', 'th']
False
PyPIConfig.find_credential
(self, url)
If the URL indicated appears to be a repository defined in this config, return the credential for that repository.
If the URL indicated appears to be a repository defined in this config, return the credential for that repository.
def find_credential(self, url): """ If the URL indicated appears to be a repository defined in this config, return the credential for that repository. """ for repository, cred in self.creds_by_repository.items(): if url.startswith(repository): return cred
[ "def", "find_credential", "(", "self", ",", "url", ")", ":", "for", "repository", ",", "cred", "in", "self", ".", "creds_by_repository", ".", "items", "(", ")", ":", "if", "url", ".", "startswith", "(", "repository", ")", ":", "return", "cred" ]
[ 1027, 4 ]
[ 1034, 27 ]
python
en
['en', 'error', 'th']
False
get_pin_and_cookie_name
(app)
Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for remembering.
Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`.
def get_pin_and_cookie_name(app): """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for remembering. """ pin = os.environ.get("WERKZEUG_DEBUG_PIN") rv = None num = None # Pin was explicitly disabled if pin == "off": return None, None # Pin was provided explicitly if pin is not None and pin.replace("-", "").isdigit(): # If there are separators in the pin, return it directly if "-" in pin: rv = pin else: num = pin modname = getattr(app, "__module__", app.__class__.__module__) try: # getuser imports the pwd module, which does not exist in Google # App Engine. It may also raise a KeyError if the UID does not # have a username, such as in Docker. username = getpass.getuser() except (ImportError, KeyError): username = None mod = sys.modules.get(modname) # This information only exists to make the cookie unique on the # computer, not as a security feature. probably_public_bits = [ username, modname, getattr(app, "__name__", app.__class__.__name__), getattr(mod, "__file__", None), ] # This information is here to make it harder for an attacker to # guess the cookie name. They are unlikely to be contained anywhere # within the unauthenticated debug page. private_bits = [str(uuid.getnode()), get_machine_id()] h = hashlib.md5() for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, text_type): bit = bit.encode("utf-8") h.update(bit) h.update(b"cookiesalt") cookie_name = "__wzd" + h.hexdigest()[:20] # If we need to generate a pin we salt it a bit more so that we don't # end up with the same value and generate out 9 digits if num is None: h.update(b"pinsalt") num = ("%09d" % int(h.hexdigest(), 16))[:9] # Format the pincode in groups of digits for easier remembering if # we don't have a result yet. if rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = "-".join( num[x : x + group_size].rjust(group_size, "0") for x in range(0, len(num), group_size) ) break else: rv = num return rv, cookie_name
[ "def", "get_pin_and_cookie_name", "(", "app", ")", ":", "pin", "=", "os", ".", "environ", ".", "get", "(", "\"WERKZEUG_DEBUG_PIN\"", ")", "rv", "=", "None", "num", "=", "None", "# Pin was explicitly disabled", "if", "pin", "==", "\"off\"", ":", "return", "None", ",", "None", "# Pin was provided explicitly", "if", "pin", "is", "not", "None", "and", "pin", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ".", "isdigit", "(", ")", ":", "# If there are separators in the pin, return it directly", "if", "\"-\"", "in", "pin", ":", "rv", "=", "pin", "else", ":", "num", "=", "pin", "modname", "=", "getattr", "(", "app", ",", "\"__module__\"", ",", "app", ".", "__class__", ".", "__module__", ")", "try", ":", "# getuser imports the pwd module, which does not exist in Google", "# App Engine. It may also raise a KeyError if the UID does not", "# have a username, such as in Docker.", "username", "=", "getpass", ".", "getuser", "(", ")", "except", "(", "ImportError", ",", "KeyError", ")", ":", "username", "=", "None", "mod", "=", "sys", ".", "modules", ".", "get", "(", "modname", ")", "# This information only exists to make the cookie unique on the", "# computer, not as a security feature.", "probably_public_bits", "=", "[", "username", ",", "modname", ",", "getattr", "(", "app", ",", "\"__name__\"", ",", "app", ".", "__class__", ".", "__name__", ")", ",", "getattr", "(", "mod", ",", "\"__file__\"", ",", "None", ")", ",", "]", "# This information is here to make it harder for an attacker to", "# guess the cookie name. They are unlikely to be contained anywhere", "# within the unauthenticated debug page.", "private_bits", "=", "[", "str", "(", "uuid", ".", "getnode", "(", ")", ")", ",", "get_machine_id", "(", ")", "]", "h", "=", "hashlib", ".", "md5", "(", ")", "for", "bit", "in", "chain", "(", "probably_public_bits", ",", "private_bits", ")", ":", "if", "not", "bit", ":", "continue", "if", "isinstance", "(", "bit", ",", "text_type", ")", ":", "bit", "=", "bit", ".", "encode", "(", "\"utf-8\"", ")", "h", ".", "update", "(", "bit", ")", "h", ".", "update", "(", "b\"cookiesalt\"", ")", "cookie_name", "=", "\"__wzd\"", "+", "h", ".", "hexdigest", "(", ")", "[", ":", "20", "]", "# If we need to generate a pin we salt it a bit more so that we don't", "# end up with the same value and generate out 9 digits", "if", "num", "is", "None", ":", "h", ".", "update", "(", "b\"pinsalt\"", ")", "num", "=", "(", "\"%09d\"", "%", "int", "(", "h", ".", "hexdigest", "(", ")", ",", "16", ")", ")", "[", ":", "9", "]", "# Format the pincode in groups of digits for easier remembering if", "# we don't have a result yet.", "if", "rv", "is", "None", ":", "for", "group_size", "in", "5", ",", "4", ",", "3", ":", "if", "len", "(", "num", ")", "%", "group_size", "==", "0", ":", "rv", "=", "\"-\"", ".", "join", "(", "num", "[", "x", ":", "x", "+", "group_size", "]", ".", "rjust", "(", "group_size", ",", "\"0\"", ")", "for", "x", "in", "range", "(", "0", ",", "len", "(", "num", ")", ",", "group_size", ")", ")", "break", "else", ":", "rv", "=", "num", "return", "rv", ",", "cookie_name" ]
[ 147, 0 ]
[ 227, 26 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.pin_cookie_name
(self)
The name of the pin cookie.
The name of the pin cookie.
def pin_cookie_name(self): """The name of the pin cookie.""" if not hasattr(self, "_pin_cookie"): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin_cookie
[ "def", "pin_cookie_name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_pin_cookie\"", ")", ":", "self", ".", "_pin", ",", "self", ".", "_pin_cookie", "=", "get_pin_and_cookie_name", "(", "self", ".", "app", ")", "return", "self", ".", "_pin_cookie" ]
[ 319, 4 ]
[ 323, 31 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.debug_application
(self, environ, start_response)
Run the application and conserve the traceback frames.
Run the application and conserve the traceback frames.
def debug_application(self, environ, start_response): """Run the application and conserve the traceback frames.""" app_iter = None try: app_iter = self.app(environ, start_response) for item in app_iter: yield item if hasattr(app_iter, "close"): app_iter.close() except Exception: if hasattr(app_iter, "close"): app_iter.close() traceback = get_current_traceback( skip=1, show_hidden_frames=self.show_hidden_frames, ignore_system_exceptions=True, ) for frame in traceback.frames: self.frames[frame.id] = frame self.tracebacks[traceback.id] = traceback try: start_response( "500 INTERNAL SERVER ERROR", [ ("Content-Type", "text/html; charset=utf-8"), # Disable Chrome's XSS protection, the debug # output can cause false-positives. ("X-XSS-Protection", "0"), ], ) except Exception: # if we end up here there has been output but an error # occurred. in that situation we can do nothing fancy any # more, better log something into the error log and fall # back gracefully. environ["wsgi.errors"].write( "Debugging middleware caught exception in streamed " "response at a point where response headers were already " "sent.\n" ) else: is_trusted = bool(self.check_pin_trust(environ)) yield traceback.render_full( evalex=self.evalex, evalex_trusted=is_trusted, secret=self.secret ).encode("utf-8", "replace") traceback.log(environ["wsgi.errors"])
[ "def", "debug_application", "(", "self", ",", "environ", ",", "start_response", ")", ":", "app_iter", "=", "None", "try", ":", "app_iter", "=", "self", ".", "app", "(", "environ", ",", "start_response", ")", "for", "item", "in", "app_iter", ":", "yield", "item", "if", "hasattr", "(", "app_iter", ",", "\"close\"", ")", ":", "app_iter", ".", "close", "(", ")", "except", "Exception", ":", "if", "hasattr", "(", "app_iter", ",", "\"close\"", ")", ":", "app_iter", ".", "close", "(", ")", "traceback", "=", "get_current_traceback", "(", "skip", "=", "1", ",", "show_hidden_frames", "=", "self", ".", "show_hidden_frames", ",", "ignore_system_exceptions", "=", "True", ",", ")", "for", "frame", "in", "traceback", ".", "frames", ":", "self", ".", "frames", "[", "frame", ".", "id", "]", "=", "frame", "self", ".", "tracebacks", "[", "traceback", ".", "id", "]", "=", "traceback", "try", ":", "start_response", "(", "\"500 INTERNAL SERVER ERROR\"", ",", "[", "(", "\"Content-Type\"", ",", "\"text/html; charset=utf-8\"", ")", ",", "# Disable Chrome's XSS protection, the debug", "# output can cause false-positives.", "(", "\"X-XSS-Protection\"", ",", "\"0\"", ")", ",", "]", ",", ")", "except", "Exception", ":", "# if we end up here there has been output but an error", "# occurred. in that situation we can do nothing fancy any", "# more, better log something into the error log and fall", "# back gracefully.", "environ", "[", "\"wsgi.errors\"", "]", ".", "write", "(", "\"Debugging middleware caught exception in streamed \"", "\"response at a point where response headers were already \"", "\"sent.\\n\"", ")", "else", ":", "is_trusted", "=", "bool", "(", "self", ".", "check_pin_trust", "(", "environ", ")", ")", "yield", "traceback", ".", "render_full", "(", "evalex", "=", "self", ".", "evalex", ",", "evalex_trusted", "=", "is_trusted", ",", "secret", "=", "self", ".", "secret", ")", ".", "encode", "(", "\"utf-8\"", ",", "\"replace\"", ")", "traceback", ".", "log", "(", "environ", "[", "\"wsgi.errors\"", "]", ")" ]
[ 325, 4 ]
[ 372, 49 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.execute_command
(self, request, command, frame)
Execute a command in a console.
Execute a command in a console.
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype="text/html")
[ "def", "execute_command", "(", "self", ",", "request", ",", "command", ",", "frame", ")", ":", "return", "Response", "(", "frame", ".", "console", ".", "eval", "(", "command", ")", ",", "mimetype", "=", "\"text/html\"", ")" ]
[ 374, 4 ]
[ 376, 74 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.display_console
(self, request)
Display a standalone shell.
Display a standalone shell.
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.app) self.frames[0] = _ConsoleFrame(ns) is_trusted = bool(self.check_pin_trust(request.environ)) return Response( render_console_html(secret=self.secret, evalex_trusted=is_trusted), mimetype="text/html", )
[ "def", "display_console", "(", "self", ",", "request", ")", ":", "if", "0", "not", "in", "self", ".", "frames", ":", "if", "self", ".", "console_init_func", "is", "None", ":", "ns", "=", "{", "}", "else", ":", "ns", "=", "dict", "(", "self", ".", "console_init_func", "(", ")", ")", "ns", ".", "setdefault", "(", "\"app\"", ",", "self", ".", "app", ")", "self", ".", "frames", "[", "0", "]", "=", "_ConsoleFrame", "(", "ns", ")", "is_trusted", "=", "bool", "(", "self", ".", "check_pin_trust", "(", "request", ".", "environ", ")", ")", "return", "Response", "(", "render_console_html", "(", "secret", "=", "self", ".", "secret", ",", "evalex_trusted", "=", "is_trusted", ")", ",", "mimetype", "=", "\"text/html\"", ",", ")" ]
[ 378, 4 ]
[ 391, 9 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.paste_traceback
(self, request, traceback)
Paste the traceback and return a JSON response.
Paste the traceback and return a JSON response.
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), mimetype="application/json")
[ "def", "paste_traceback", "(", "self", ",", "request", ",", "traceback", ")", ":", "rv", "=", "traceback", ".", "paste", "(", ")", "return", "Response", "(", "json", ".", "dumps", "(", "rv", ")", ",", "mimetype", "=", "\"application/json\"", ")" ]
[ 393, 4 ]
[ 396, 68 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.get_resource
(self, request, filename)
Return a static resource from the shared folder.
Return a static resource from the shared folder.
def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, filename) except OSError: data = None if data is not None: mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" return Response(data, mimetype=mimetype) return Response("Not Found", status=404)
[ "def", "get_resource", "(", "self", ",", "request", ",", "filename", ")", ":", "filename", "=", "join", "(", "\"shared\"", ",", "basename", "(", "filename", ")", ")", "try", ":", "data", "=", "pkgutil", ".", "get_data", "(", "__package__", ",", "filename", ")", "except", "OSError", ":", "data", "=", "None", "if", "data", "is", "not", "None", ":", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "\"application/octet-stream\"", "return", "Response", "(", "data", ",", "mimetype", "=", "mimetype", ")", "return", "Response", "(", "\"Not Found\"", ",", "status", "=", "404", ")" ]
[ 398, 4 ]
[ 408, 48 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.check_pin_trust
(self, environ)
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken.
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken.
def check_pin_trust(self, environ): """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken. """ if self.pin is None: return True val = parse_cookie(environ).get(self.pin_cookie_name) if not val or "|" not in val: return False ts, pin_hash = val.split("|", 1) if not ts.isdigit(): return False if pin_hash != hash_pin(self.pin): return None return (time.time() - PIN_TIME) < int(ts)
[ "def", "check_pin_trust", "(", "self", ",", "environ", ")", ":", "if", "self", ".", "pin", "is", "None", ":", "return", "True", "val", "=", "parse_cookie", "(", "environ", ")", ".", "get", "(", "self", ".", "pin_cookie_name", ")", "if", "not", "val", "or", "\"|\"", "not", "in", "val", ":", "return", "False", "ts", ",", "pin_hash", "=", "val", ".", "split", "(", "\"|\"", ",", "1", ")", "if", "not", "ts", ".", "isdigit", "(", ")", ":", "return", "False", "if", "pin_hash", "!=", "hash_pin", "(", "self", ".", "pin", ")", ":", "return", "None", "return", "(", "time", ".", "time", "(", ")", "-", "PIN_TIME", ")", "<", "int", "(", "ts", ")" ]
[ 410, 4 ]
[ 426, 49 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.pin_auth
(self, request)
Authenticates with the pin.
Authenticates with the pin.
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the # pin was changed. In this case we count a bad auth and unset the # cookie. This way it becomes harder to guess the cookie name # instead of the pin as we still count up failures. bad_cookie = False if trust is None: self._fail_pin_auth() bad_cookie = True # If we're trusted, we're authenticated. elif trust: auth = True # If we failed too many times, then we're locked out. elif self._failed_pin_auth > 10: exhausted = True # Otherwise go through pin based authentication else: entered_pin = request.args.get("pin") if entered_pin.strip().replace("-", "") == self.pin.replace("-", ""): self._failed_pin_auth = 0 auth = True else: self._fail_pin_auth() rv = Response( json.dumps({"auth": auth, "exhausted": exhausted}), mimetype="application/json", ) if auth: rv.set_cookie( self.pin_cookie_name, "%s|%s" % (int(time.time()), hash_pin(self.pin)), httponly=True, ) elif bad_cookie: rv.delete_cookie(self.pin_cookie_name) return rv
[ "def", "pin_auth", "(", "self", ",", "request", ")", ":", "exhausted", "=", "False", "auth", "=", "False", "trust", "=", "self", ".", "check_pin_trust", "(", "request", ".", "environ", ")", "# If the trust return value is `None` it means that the cookie is", "# set but the stored pin hash value is bad. This means that the", "# pin was changed. In this case we count a bad auth and unset the", "# cookie. This way it becomes harder to guess the cookie name", "# instead of the pin as we still count up failures.", "bad_cookie", "=", "False", "if", "trust", "is", "None", ":", "self", ".", "_fail_pin_auth", "(", ")", "bad_cookie", "=", "True", "# If we're trusted, we're authenticated.", "elif", "trust", ":", "auth", "=", "True", "# If we failed too many times, then we're locked out.", "elif", "self", ".", "_failed_pin_auth", ">", "10", ":", "exhausted", "=", "True", "# Otherwise go through pin based authentication", "else", ":", "entered_pin", "=", "request", ".", "args", ".", "get", "(", "\"pin\"", ")", "if", "entered_pin", ".", "strip", "(", ")", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", "==", "self", ".", "pin", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ":", "self", ".", "_failed_pin_auth", "=", "0", "auth", "=", "True", "else", ":", "self", ".", "_fail_pin_auth", "(", ")", "rv", "=", "Response", "(", "json", ".", "dumps", "(", "{", "\"auth\"", ":", "auth", ",", "\"exhausted\"", ":", "exhausted", "}", ")", ",", "mimetype", "=", "\"application/json\"", ",", ")", "if", "auth", ":", "rv", ".", "set_cookie", "(", "self", ".", "pin_cookie_name", ",", "\"%s|%s\"", "%", "(", "int", "(", "time", ".", "time", "(", ")", ")", ",", "hash_pin", "(", "self", ".", "pin", ")", ")", ",", "httponly", "=", "True", ",", ")", "elif", "bad_cookie", ":", "rv", ".", "delete_cookie", "(", "self", ".", "pin_cookie_name", ")", "return", "rv" ]
[ 432, 4 ]
[ 477, 17 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.log_pin_request
(self)
Log the pin if needed.
Log the pin if needed.
def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to enter the security pin:" ) _log("info", " * Debugger pin code: %s" % self.pin) return Response("")
[ "def", "log_pin_request", "(", "self", ")", ":", "if", "self", ".", "pin_logging", "and", "self", ".", "pin", "is", "not", "None", ":", "_log", "(", "\"info\"", ",", "\" * To enable the debugger you need to enter the security pin:\"", ")", "_log", "(", "\"info\"", ",", "\" * Debugger pin code: %s\"", "%", "self", ".", "pin", ")", "return", "Response", "(", "\"\"", ")" ]
[ 479, 4 ]
[ 486, 27 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.__call__
(self, environ, start_response)
Dispatch the requests.
Dispatch the requests.
def __call__(self, environ, start_response): """Dispatch the requests.""" # important: don't ever access a function here that reads the incoming # form data! Otherwise the application won't have access to that data # any more! request = Request(environ) response = self.debug_application if request.args.get("__debugger__") == "yes": cmd = request.args.get("cmd") arg = request.args.get("f") secret = request.args.get("s") traceback = self.tracebacks.get(request.args.get("tb", type=int)) frame = self.frames.get(request.args.get("frm", type=int)) if cmd == "resource" and arg: response = self.get_resource(request, arg) elif cmd == "paste" and traceback is not None and secret == self.secret: response = self.paste_traceback(request, traceback) elif cmd == "pinauth" and secret == self.secret: response = self.pin_auth(request) elif cmd == "printpin" and secret == self.secret: response = self.log_pin_request() elif ( self.evalex and cmd is not None and frame is not None and self.secret == secret and self.check_pin_trust(environ) ): response = self.execute_command(request, cmd, frame) elif ( self.evalex and self.console_path is not None and request.path == self.console_path ): response = self.display_console(request) return response(environ, start_response)
[ "def", "__call__", "(", "self", ",", "environ", ",", "start_response", ")", ":", "# important: don't ever access a function here that reads the incoming", "# form data! Otherwise the application won't have access to that data", "# any more!", "request", "=", "Request", "(", "environ", ")", "response", "=", "self", ".", "debug_application", "if", "request", ".", "args", ".", "get", "(", "\"__debugger__\"", ")", "==", "\"yes\"", ":", "cmd", "=", "request", ".", "args", ".", "get", "(", "\"cmd\"", ")", "arg", "=", "request", ".", "args", ".", "get", "(", "\"f\"", ")", "secret", "=", "request", ".", "args", ".", "get", "(", "\"s\"", ")", "traceback", "=", "self", ".", "tracebacks", ".", "get", "(", "request", ".", "args", ".", "get", "(", "\"tb\"", ",", "type", "=", "int", ")", ")", "frame", "=", "self", ".", "frames", ".", "get", "(", "request", ".", "args", ".", "get", "(", "\"frm\"", ",", "type", "=", "int", ")", ")", "if", "cmd", "==", "\"resource\"", "and", "arg", ":", "response", "=", "self", ".", "get_resource", "(", "request", ",", "arg", ")", "elif", "cmd", "==", "\"paste\"", "and", "traceback", "is", "not", "None", "and", "secret", "==", "self", ".", "secret", ":", "response", "=", "self", ".", "paste_traceback", "(", "request", ",", "traceback", ")", "elif", "cmd", "==", "\"pinauth\"", "and", "secret", "==", "self", ".", "secret", ":", "response", "=", "self", ".", "pin_auth", "(", "request", ")", "elif", "cmd", "==", "\"printpin\"", "and", "secret", "==", "self", ".", "secret", ":", "response", "=", "self", ".", "log_pin_request", "(", ")", "elif", "(", "self", ".", "evalex", "and", "cmd", "is", "not", "None", "and", "frame", "is", "not", "None", "and", "self", ".", "secret", "==", "secret", "and", "self", ".", "check_pin_trust", "(", "environ", ")", ")", ":", "response", "=", "self", ".", "execute_command", "(", "request", ",", "cmd", ",", "frame", ")", "elif", "(", "self", ".", "evalex", "and", "self", ".", "console_path", "is", "not", "None", "and", "request", ".", "path", "==", "self", ".", "console_path", ")", ":", "response", "=", "self", ".", "display_console", "(", "request", ")", "return", "response", "(", "environ", ",", "start_response", ")" ]
[ 488, 4 ]
[ 523, 48 ]
python
en
['en', 'en', 'en']
True
read_quizfile
(quizfile)
Reads the quiz file into a big dictionary.
Reads the quiz file into a big dictionary.
def read_quizfile(quizfile): "Reads the quiz file into a big dictionary." try: with open(quizfile) as f: linelist = f.readlines() except IOError: questionlist = None else: questionlist = [] # Splits the line into category:question*answers match groups. rgx = re.compile("(?:([^:]*):)?([^*]*)\*(.*)") for line in linelist: match = rgx.search(line) question = match.group(1), match.group(2), match.group(3) questionlist.append(question) return questionlist
[ "def", "read_quizfile", "(", "quizfile", ")", ":", "try", ":", "with", "open", "(", "quizfile", ")", "as", "f", ":", "linelist", "=", "f", ".", "readlines", "(", ")", "except", "IOError", ":", "questionlist", "=", "None", "else", ":", "questionlist", "=", "[", "]", "# Splits the line into category:question*answers match groups.", "rgx", "=", "re", ".", "compile", "(", "\"(?:([^:]*):)?([^*]*)\\*(.*)\"", ")", "for", "line", "in", "linelist", ":", "match", "=", "rgx", ".", "search", "(", "line", ")", "question", "=", "match", ".", "group", "(", "1", ")", ",", "match", ".", "group", "(", "2", ")", ",", "match", ".", "group", "(", "3", ")", "questionlist", ".", "append", "(", "question", ")", "return", "questionlist" ]
[ 8, 0 ]
[ 24, 23 ]
python
en
['en', 'en', 'en']
True
update_hint
(factory)
Create a hint for an answer.
Create a hint for an answer.
def update_hint(factory): "Create a hint for an answer." hint = list(factory.hint) answer = factory.answer count = 0 while count < 3: index = random.randrange(len(answer)) if hint[index] == "_": hint[index] = answer[index] count += 1 factory.hint = "".join(hint)
[ "def", "update_hint", "(", "factory", ")", ":", "hint", "=", "list", "(", "factory", ".", "hint", ")", "answer", "=", "factory", ".", "answer", "count", "=", "0", "while", "count", "<", "3", ":", "index", "=", "random", ".", "randrange", "(", "len", "(", "answer", ")", ")", "if", "hint", "[", "index", "]", "==", "\"_\"", ":", "hint", "[", "index", "]", "=", "answer", "[", "index", "]", "count", "+=", "1", "factory", ".", "hint", "=", "\"\"", ".", "join", "(", "hint", ")" ]
[ 27, 0 ]
[ 38, 32 ]
python
en
['en', 'en', 'en']
True
command_quiz
(bot, user, channel, args)
A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>].
A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>].
def command_quiz(bot, user, channel, args): "A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>]." # TODO: delay = 25 if args == "hint" or args == "clue": update_hint(bot.factory) return bot.say(channel, bot.factory.hint) elif args == "on": bot.factory.quiz_enabled = True bot.say(channel, "Quiz is now enabled. Delay: {}.".format(delay)) elif args == "off": bot.factory.quiz_enabled = False return bot.say(channel, "Quiz is now disabled.") elif args == "help": bot.say(channel, "Usage: quiz [on|off|<delay>].") elif args.isdigit() and not args > 60: delay = int(args) bot.say(channel, "Delay changed to: {}.".format(delay)) else: bot.say(channel, "Quiz running: {}. Delay: {}" .format(bot.factory.quiz_enabled, delay)) quizlist = None if bot.factory.quiz_enabled: quizfile = os.path.join(bot.factory.moduledir, "quiz_general.txt") quizlist = read_quizfile(quizfile) while bot.factory.quiz_enabled and quizlist: category, question, answers = random.choice(quizlist) question = question.strip().capitalize() # Format the question poco. bot.factory.answer = answers.split("*")[0] bot.factory.hint = "".join(["_" if i != " " else " " for i in\ bot.factory.answer]) if category: bot.say(channel, "{}: {}?".format(category, question)) else: bot.say(channel, "{}?".format(question)) reactor.callLater(delay, bot.say, channel, answers) time.sleep(delay + 5)
[ "def", "command_quiz", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "# TODO:", "delay", "=", "25", "if", "args", "==", "\"hint\"", "or", "args", "==", "\"clue\"", ":", "update_hint", "(", "bot", ".", "factory", ")", "return", "bot", ".", "say", "(", "channel", ",", "bot", ".", "factory", ".", "hint", ")", "elif", "args", "==", "\"on\"", ":", "bot", ".", "factory", ".", "quiz_enabled", "=", "True", "bot", ".", "say", "(", "channel", ",", "\"Quiz is now enabled. Delay: {}.\"", ".", "format", "(", "delay", ")", ")", "elif", "args", "==", "\"off\"", ":", "bot", ".", "factory", ".", "quiz_enabled", "=", "False", "return", "bot", ".", "say", "(", "channel", ",", "\"Quiz is now disabled.\"", ")", "elif", "args", "==", "\"help\"", ":", "bot", ".", "say", "(", "channel", ",", "\"Usage: quiz [on|off|<delay>].\"", ")", "elif", "args", ".", "isdigit", "(", ")", "and", "not", "args", ">", "60", ":", "delay", "=", "int", "(", "args", ")", "bot", ".", "say", "(", "channel", ",", "\"Delay changed to: {}.\"", ".", "format", "(", "delay", ")", ")", "else", ":", "bot", ".", "say", "(", "channel", ",", "\"Quiz running: {}. Delay: {}\"", ".", "format", "(", "bot", ".", "factory", ".", "quiz_enabled", ",", "delay", ")", ")", "quizlist", "=", "None", "if", "bot", ".", "factory", ".", "quiz_enabled", ":", "quizfile", "=", "os", ".", "path", ".", "join", "(", "bot", ".", "factory", ".", "moduledir", ",", "\"quiz_general.txt\"", ")", "quizlist", "=", "read_quizfile", "(", "quizfile", ")", "while", "bot", ".", "factory", ".", "quiz_enabled", "and", "quizlist", ":", "category", ",", "question", ",", "answers", "=", "random", ".", "choice", "(", "quizlist", ")", "question", "=", "question", ".", "strip", "(", ")", ".", "capitalize", "(", ")", "# Format the question poco.", "bot", ".", "factory", ".", "answer", "=", "answers", ".", "split", "(", "\"*\"", ")", "[", "0", "]", "bot", ".", "factory", ".", "hint", "=", "\"\"", ".", "join", "(", "[", "\"_\"", "if", "i", "!=", "\" \"", "else", "\" \"", "for", "i", "in", "bot", ".", "factory", ".", "answer", "]", ")", "if", "category", ":", "bot", ".", "say", "(", "channel", ",", "\"{}: {}?\"", ".", "format", "(", "category", ",", "question", ")", ")", "else", ":", "bot", ".", "say", "(", "channel", ",", "\"{}?\"", ".", "format", "(", "question", ")", ")", "reactor", ".", "callLater", "(", "delay", ",", "bot", ".", "say", ",", "channel", ",", "answers", ")", "time", ".", "sleep", "(", "delay", "+", "5", ")" ]
[ 41, 0 ]
[ 81, 29 ]
python
en
['es', 'en', 'en']
True
report
(crawler, file=None)
Print a report on all completed URLs.
Print a report on all completed URLs.
def report(crawler, file=None): """Print a report on all completed URLs.""" t1 = crawler.t1 or time.time() dt = t1 - crawler.t0 if dt and crawler.max_tasks: speed = len(crawler.done) / dt / crawler.max_tasks else: speed = 0 stats = Stats() print('*** Report ***', file=file) try: show = [] show.extend(crawler.done.items()) show.extend(crawler.busy.items()) show.sort() for url, fetcher in show: fetcher_report(fetcher, stats, file=file) except KeyboardInterrupt: print('\nInterrupted', file=file) print('Finished', len(crawler.done), 'urls in %.3f secs' % dt, '(max_tasks=%d)' % crawler.max_tasks, '(%.3f urls/sec/task)' % speed, file=file) stats.report(file=file) print('Todo:', len(crawler.todo), file=file) print('Busy:', len(crawler.busy), file=file) print('Done:', len(crawler.done), file=file) print('Date:', time.ctime(), 'local time', file=file)
[ "def", "report", "(", "crawler", ",", "file", "=", "None", ")", ":", "t1", "=", "crawler", ".", "t1", "or", "time", ".", "time", "(", ")", "dt", "=", "t1", "-", "crawler", ".", "t0", "if", "dt", "and", "crawler", ".", "max_tasks", ":", "speed", "=", "len", "(", "crawler", ".", "done", ")", "/", "dt", "/", "crawler", ".", "max_tasks", "else", ":", "speed", "=", "0", "stats", "=", "Stats", "(", ")", "print", "(", "'*** Report ***'", ",", "file", "=", "file", ")", "try", ":", "show", "=", "[", "]", "show", ".", "extend", "(", "crawler", ".", "done", ".", "items", "(", ")", ")", "show", ".", "extend", "(", "crawler", ".", "busy", ".", "items", "(", ")", ")", "show", ".", "sort", "(", ")", "for", "url", ",", "fetcher", "in", "show", ":", "fetcher_report", "(", "fetcher", ",", "stats", ",", "file", "=", "file", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'\\nInterrupted'", ",", "file", "=", "file", ")", "print", "(", "'Finished'", ",", "len", "(", "crawler", ".", "done", ")", ",", "'urls in %.3f secs'", "%", "dt", ",", "'(max_tasks=%d)'", "%", "crawler", ".", "max_tasks", ",", "'(%.3f urls/sec/task)'", "%", "speed", ",", "file", "=", "file", ")", "stats", ".", "report", "(", "file", "=", "file", ")", "print", "(", "'Todo:'", ",", "len", "(", "crawler", ".", "todo", ")", ",", "file", "=", "file", ")", "print", "(", "'Busy:'", ",", "len", "(", "crawler", ".", "busy", ")", ",", "file", "=", "file", ")", "print", "(", "'Done:'", ",", "len", "(", "crawler", ".", "done", ")", ",", "file", "=", "file", ")", "print", "(", "'Date:'", ",", "time", ".", "ctime", "(", ")", ",", "'local time'", ",", "file", "=", "file", ")" ]
[ 19, 0 ]
[ 47, 57 ]
python
en
['en', 'en', 'en']
True
fetcher_report
(fetcher, stats, file=None)
Print a report on the state for this URL. Also update the Stats instance.
Print a report on the state for this URL.
def fetcher_report(fetcher, stats, file=None): """Print a report on the state for this URL. Also update the Stats instance. """ if fetcher.task is not None: if not fetcher.task.done(): stats.add('pending') print(fetcher.url, 'pending', file=file) return elif fetcher.task.cancelled(): stats.add('cancelled') print(fetcher.url, 'cancelled', file=file) return elif fetcher.task.exception(): stats.add('exception') exc = fetcher.task.exception() stats.add('exception_' + exc.__class__.__name__) print(fetcher.url, exc, file=file) return if len(fetcher.exceptions) == fetcher.tries: stats.add('fail') exc = fetcher.exceptions[-1] stats.add('fail_' + str(exc.__class__.__name__)) print(fetcher.url, 'error', exc, file=file) elif fetcher.next_url: stats.add('redirect') print(fetcher.url, fetcher.status, 'redirect', fetcher.next_url, file=file) elif fetcher.ctype == 'text/html': stats.add('html') size = len(fetcher.body or b'') stats.add('html_bytes', size) print(fetcher.url, fetcher.status, fetcher.ctype, fetcher.encoding, size, '%d/%d' % (len(fetcher.new_urls or ()), len(fetcher.urls or ())), file=file) else: size = len(fetcher.body or b'') if fetcher.status == 200: stats.add('other') stats.add('other_bytes', size) else: stats.add('error') stats.add('error_bytes', size) stats.add('status_%s' % fetcher.status) print(fetcher.url, fetcher.status, fetcher.ctype, fetcher.encoding, size, file=file)
[ "def", "fetcher_report", "(", "fetcher", ",", "stats", ",", "file", "=", "None", ")", ":", "if", "fetcher", ".", "task", "is", "not", "None", ":", "if", "not", "fetcher", ".", "task", ".", "done", "(", ")", ":", "stats", ".", "add", "(", "'pending'", ")", "print", "(", "fetcher", ".", "url", ",", "'pending'", ",", "file", "=", "file", ")", "return", "elif", "fetcher", ".", "task", ".", "cancelled", "(", ")", ":", "stats", ".", "add", "(", "'cancelled'", ")", "print", "(", "fetcher", ".", "url", ",", "'cancelled'", ",", "file", "=", "file", ")", "return", "elif", "fetcher", ".", "task", ".", "exception", "(", ")", ":", "stats", ".", "add", "(", "'exception'", ")", "exc", "=", "fetcher", ".", "task", ".", "exception", "(", ")", "stats", ".", "add", "(", "'exception_'", "+", "exc", ".", "__class__", ".", "__name__", ")", "print", "(", "fetcher", ".", "url", ",", "exc", ",", "file", "=", "file", ")", "return", "if", "len", "(", "fetcher", ".", "exceptions", ")", "==", "fetcher", ".", "tries", ":", "stats", ".", "add", "(", "'fail'", ")", "exc", "=", "fetcher", ".", "exceptions", "[", "-", "1", "]", "stats", ".", "add", "(", "'fail_'", "+", "str", "(", "exc", ".", "__class__", ".", "__name__", ")", ")", "print", "(", "fetcher", ".", "url", ",", "'error'", ",", "exc", ",", "file", "=", "file", ")", "elif", "fetcher", ".", "next_url", ":", "stats", ".", "add", "(", "'redirect'", ")", "print", "(", "fetcher", ".", "url", ",", "fetcher", ".", "status", ",", "'redirect'", ",", "fetcher", ".", "next_url", ",", "file", "=", "file", ")", "elif", "fetcher", ".", "ctype", "==", "'text/html'", ":", "stats", ".", "add", "(", "'html'", ")", "size", "=", "len", "(", "fetcher", ".", "body", "or", "b''", ")", "stats", ".", "add", "(", "'html_bytes'", ",", "size", ")", "print", "(", "fetcher", ".", "url", ",", "fetcher", ".", "status", ",", "fetcher", ".", "ctype", ",", "fetcher", ".", "encoding", ",", "size", ",", "'%d/%d'", "%", "(", "len", "(", "fetcher", ".", "new_urls", "or", "(", ")", ")", ",", "len", "(", "fetcher", ".", "urls", "or", "(", ")", ")", ")", ",", "file", "=", "file", ")", "else", ":", "size", "=", "len", "(", "fetcher", ".", "body", "or", "b''", ")", "if", "fetcher", ".", "status", "==", "200", ":", "stats", ".", "add", "(", "'other'", ")", "stats", ".", "add", "(", "'other_bytes'", ",", "size", ")", "else", ":", "stats", ".", "add", "(", "'error'", ")", "stats", ".", "add", "(", "'error_bytes'", ",", "size", ")", "stats", ".", "add", "(", "'status_%s'", "%", "fetcher", ".", "status", ")", "print", "(", "fetcher", ".", "url", ",", "fetcher", ".", "status", ",", "fetcher", ".", "ctype", ",", "fetcher", ".", "encoding", ",", "size", ",", "file", "=", "file", ")" ]
[ 50, 0 ]
[ 100, 24 ]
python
en
['en', 'en', 'en']
True
CurrentSiteManager._get_field_name
(self)
Return self.__field_name or 'site' or 'sites'.
Return self.__field_name or 'site' or 'sites'.
def _get_field_name(self): """ Return self.__field_name or 'site' or 'sites'. """ if not self.__field_name: try: self.model._meta.get_field('site') except FieldDoesNotExist: self.__field_name = 'sites' else: self.__field_name = 'site' return self.__field_name
[ "def", "_get_field_name", "(", "self", ")", ":", "if", "not", "self", ".", "__field_name", ":", "try", ":", "self", ".", "model", ".", "_meta", ".", "get_field", "(", "'site'", ")", "except", "FieldDoesNotExist", ":", "self", ".", "__field_name", "=", "'sites'", "else", ":", "self", ".", "__field_name", "=", "'site'", "return", "self", ".", "__field_name" ]
[ 46, 4 ]
[ 56, 32 ]
python
en
['en', 'en', 'en']
True
threadsafe_generator
(f)
A decorator that takes a generator function and makes it thread-safe.
A decorator that takes a generator function and makes it thread-safe.
def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g
[ "def", "threadsafe_generator", "(", "f", ")", ":", "def", "g", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "return", "threadsafe_iter", "(", "f", "(", "*", "a", ",", "*", "*", "kw", ")", ")", "return", "g" ]
[ 32, 0 ]
[ 37, 12 ]
python
en
['en', 'en', 'en']
True
localize
(value)
Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``.
Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``.
def localize(value): """ Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``. """ return str(formats.localize(value, use_l10n=True))
[ "def", "localize", "(", "value", ")", ":", "return", "str", "(", "formats", ".", "localize", "(", "value", ",", "use_l10n", "=", "True", ")", ")" ]
[ 7, 0 ]
[ 12, 54 ]
python
en
['en', 'error', 'th']
False
unlocalize
(value)
Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``.
Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``.
def unlocalize(value): """ Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``. """ return str(formats.localize(value, use_l10n=False))
[ "def", "unlocalize", "(", "value", ")", ":", "return", "str", "(", "formats", ".", "localize", "(", "value", ",", "use_l10n", "=", "False", ")", ")" ]
[ 16, 0 ]
[ 21, 55 ]
python
en
['en', 'error', 'th']
False
localize_tag
(parser, token)
Force or prevents localization of values, regardless of the value of `settings.USE_L10N`. Sample usage:: {% localize off %} var pi = {{ 3.1415 }}; {% endlocalize %}
Force or prevents localization of values, regardless of the value of `settings.USE_L10N`.
def localize_tag(parser, token): """ Force or prevents localization of values, regardless of the value of `settings.USE_L10N`. Sample usage:: {% localize off %} var pi = {{ 3.1415 }}; {% endlocalize %} """ use_l10n = None bits = list(token.split_contents()) if len(bits) == 1: use_l10n = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_l10n = bits[1] == 'on' nodelist = parser.parse(('endlocalize',)) parser.delete_first_token() return LocalizeNode(nodelist, use_l10n)
[ "def", "localize_tag", "(", "parser", ",", "token", ")", ":", "use_l10n", "=", "None", "bits", "=", "list", "(", "token", ".", "split_contents", "(", ")", ")", "if", "len", "(", "bits", ")", "==", "1", ":", "use_l10n", "=", "True", "elif", "len", "(", "bits", ")", ">", "2", "or", "bits", "[", "1", "]", "not", "in", "(", "'on'", ",", "'off'", ")", ":", "raise", "TemplateSyntaxError", "(", "\"%r argument should be 'on' or 'off'\"", "%", "bits", "[", "0", "]", ")", "else", ":", "use_l10n", "=", "bits", "[", "1", "]", "==", "'on'", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endlocalize'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "LocalizeNode", "(", "nodelist", ",", "use_l10n", ")" ]
[ 41, 0 ]
[ 62, 43 ]
python
en
['en', 'error', 'th']
False
publish_feedback
(feedback)
pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function
pull_feedback
def publish_feedback(feedback): # TODO: Publish the feedback object to the feedback topic # END TODO """pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function """
[ "def", "publish_feedback", "(", "feedback", ")", ":", "# TODO: Publish the feedback object to the feedback topic", "# END TODO" ]
[ 57, 0 ]
[ 73, 3 ]
python
en
['en', 'cy', 'en']
False
interpret
(marker, execution_context=None)
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping
Interpret a marker and return a result depending on environment.
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: expr, rest = parse_marker(marker) except Exception as e: raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e)) if rest and rest[0] != '#': raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest)) context = dict(DEFAULT_CONTEXT) if execution_context: context.update(execution_context) return evaluator.evaluate(expr, context)
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker syntax: %s: %s'", "%", "(", "marker", ",", "e", ")", ")", "if", "rest", "and", "rest", "[", "0", "]", "!=", "'#'", ":", "raise", "SyntaxError", "(", "'unexpected trailing data in marker: %s: %s'", "%", "(", "marker", ",", "rest", ")", ")", "context", "=", "dict", "(", "DEFAULT_CONTEXT", ")", "if", "execution_context", ":", "context", ".", "update", "(", "execution_context", ")", "return", "evaluator", ".", "evaluate", "(", "expr", ",", "context", ")" ]
[ 111, 0 ]
[ 129, 44 ]
python
en
['en', 'error', 'th']
False
Evaluator.evaluate
(self, expr, context)
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, string_types): if expr[0] in '\'"': result = expr[1:-1] else: if expr not in context: raise SyntaxError('unknown variable: %s' % expr) result = context[expr] else: assert isinstance(expr, dict) op = expr['op'] if op not in self.operations: raise NotImplementedError('op not implemented: %s' % op) elhs = expr['lhs'] erhs = expr['rhs'] if _is_literal(expr['lhs']) and _is_literal(expr['rhs']): raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs)) lhs = self.evaluate(elhs, context) rhs = self.evaluate(erhs, context) result = self.operations[op](lhs, rhs) return result
[ "def", "evaluate", "(", "self", ",", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "if", "expr", "[", "0", "]", "in", "'\\'\"'", ":", "result", "=", "expr", "[", "1", ":", "-", "1", "]", "else", ":", "if", "expr", "not", "in", "context", ":", "raise", "SyntaxError", "(", "'unknown variable: %s'", "%", "expr", ")", "result", "=", "context", "[", "expr", "]", "else", ":", "assert", "isinstance", "(", "expr", ",", "dict", ")", "op", "=", "expr", "[", "'op'", "]", "if", "op", "not", "in", "self", ".", "operations", ":", "raise", "NotImplementedError", "(", "'op not implemented: %s'", "%", "op", ")", "elhs", "=", "expr", "[", "'lhs'", "]", "erhs", "=", "expr", "[", "'rhs'", "]", "if", "_is_literal", "(", "expr", "[", "'lhs'", "]", ")", "and", "_is_literal", "(", "expr", "[", "'rhs'", "]", ")", ":", "raise", "SyntaxError", "(", "'invalid comparison: %s %s %s'", "%", "(", "elhs", ",", "op", ",", "erhs", ")", ")", "lhs", "=", "self", ".", "evaluate", "(", "elhs", ",", "context", ")", "rhs", "=", "self", ".", "evaluate", "(", "erhs", ",", "context", ")", "result", "=", "self", ".", "operations", "[", "op", "]", "(", "lhs", ",", "rhs", ")", "return", "result" ]
[ 48, 4 ]
[ 73, 21 ]
python
en
['en', 'error', 'th']
False
generic_inlineformset_factory
(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True)
Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively.
Return a ``GenericInlineFormSet`` for the given kwargs.
def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True): """ Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate exclude = [*(exclude or []), ct_field.name, fk_field.name] FormSet = modelformset_factory( model, form=form, formfield_callback=formfield_callback, formset=formset, extra=extra, can_delete=can_delete, can_order=can_order, fields=fields, exclude=exclude, max_num=max_num, validate_max=validate_max, min_num=min_num, validate_min=validate_min, absolute_max=absolute_max, can_delete_extra=can_delete_extra, ) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
[ "def", "generic_inlineformset_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseGenericInlineFormSet", ",", "ct_field", "=", "\"content_type\"", ",", "fk_field", "=", "\"object_id\"", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "extra", "=", "3", ",", "can_order", "=", "False", ",", "can_delete", "=", "True", ",", "max_num", "=", "None", ",", "formfield_callback", "=", "None", ",", "validate_max", "=", "False", ",", "for_concrete_model", "=", "True", ",", "min_num", "=", "None", ",", "validate_min", "=", "False", ",", "absolute_max", "=", "None", ",", "can_delete_extra", "=", "True", ")", ":", "opts", "=", "model", ".", "_meta", "# if there is no field called `ct_field` let the exception propagate", "ct_field", "=", "opts", ".", "get_field", "(", "ct_field", ")", "if", "not", "isinstance", "(", "ct_field", ",", "models", ".", "ForeignKey", ")", "or", "ct_field", ".", "remote_field", ".", "model", "!=", "ContentType", ":", "raise", "Exception", "(", "\"fk_name '%s' is not a ForeignKey to ContentType\"", "%", "ct_field", ")", "fk_field", "=", "opts", ".", "get_field", "(", "fk_field", ")", "# let the exception propagate", "exclude", "=", "[", "*", "(", "exclude", "or", "[", "]", ")", ",", "ct_field", ".", "name", ",", "fk_field", ".", "name", "]", "FormSet", "=", "modelformset_factory", "(", "model", ",", "form", "=", "form", ",", "formfield_callback", "=", "formfield_callback", ",", "formset", "=", "formset", ",", "extra", "=", "extra", ",", "can_delete", "=", "can_delete", ",", "can_order", "=", "can_order", ",", "fields", "=", "fields", ",", "exclude", "=", "exclude", ",", "max_num", "=", "max_num", ",", "validate_max", "=", "validate_max", ",", "min_num", "=", "min_num", ",", "validate_min", "=", "validate_min", ",", "absolute_max", "=", "absolute_max", ",", "can_delete_extra", "=", "can_delete_extra", ",", ")", "FormSet", ".", "ct_field", "=", "ct_field", "FormSet", ".", "ct_fk_field", "=", "fk_field", "FormSet", ".", "for_concrete_model", "=", "for_concrete_model", "return", "FormSet" ]
[ 51, 0 ]
[ 83, 18 ]
python
en
['en', 'error', 'th']
False
getLogger
(name: str)
logging.getLogger, but ensures our VerboseLogger class is returned
logging.getLogger, but ensures our VerboseLogger class is returned
def getLogger(name: str) -> VerboseLogger: """logging.getLogger, but ensures our VerboseLogger class is returned""" return cast(VerboseLogger, logging.getLogger(name))
[ "def", "getLogger", "(", "name", ":", "str", ")", "->", "VerboseLogger", ":", "return", "cast", "(", "VerboseLogger", ",", "logging", ".", "getLogger", "(", "name", ")", ")" ]
[ 25, 0 ]
[ 27, 55 ]
python
en
['en', 'en', 'en']
True
init_logging
()
Register our VerboseLogger and VERBOSE log level. Should be called before any calls to getLogger(), i.e. in pip._internal.__init__
Register our VerboseLogger and VERBOSE log level.
def init_logging() -> None: """Register our VerboseLogger and VERBOSE log level. Should be called before any calls to getLogger(), i.e. in pip._internal.__init__ """ logging.setLoggerClass(VerboseLogger) logging.addLevelName(VERBOSE, "VERBOSE")
[ "def", "init_logging", "(", ")", "->", "None", ":", "logging", ".", "setLoggerClass", "(", "VerboseLogger", ")", "logging", ".", "addLevelName", "(", "VERBOSE", ",", "\"VERBOSE\"", ")" ]
[ 30, 0 ]
[ 37, 44 ]
python
en
['en', 'da', 'en']
True
_download_and_clean_file
(filename, url)
Downloads data from url, and makes changes to match the CSV format. The CSVs may use spaces after the comma delimters (non-standard) or include rows which do not represent well-formed examples. This function strips out some of these problems. Args: filename: filename to save url to url: URL of resource to download
Downloads data from url, and makes changes to match the CSV format.
def _download_and_clean_file(filename, url): """Downloads data from url, and makes changes to match the CSV format. The CSVs may use spaces after the comma delimters (non-standard) or include rows which do not represent well-formed examples. This function strips out some of these problems. Args: filename: filename to save url to url: URL of resource to download """ temp_file, _ = urllib.request.urlretrieve(url) with tf.io.gfile.GFile(temp_file, 'r') as temp_file_object: with tf.io.gfile.GFile(filename, 'w') as file_object: for line in temp_file_object: line = line.strip() line = line.replace(', ', ',') if not line or ',' not in line: continue if line[-1] == '.': line = line[:-1] line += '\n' file_object.write(line) tf.io.gfile.remove(temp_file)
[ "def", "_download_and_clean_file", "(", "filename", ",", "url", ")", ":", "temp_file", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ")", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "temp_file", ",", "'r'", ")", "as", "temp_file_object", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "filename", ",", "'w'", ")", "as", "file_object", ":", "for", "line", "in", "temp_file_object", ":", "line", "=", "line", ".", "strip", "(", ")", "line", "=", "line", ".", "replace", "(", "', '", ",", "','", ")", "if", "not", "line", "or", "','", "not", "in", "line", ":", "continue", "if", "line", "[", "-", "1", "]", "==", "'.'", ":", "line", "=", "line", "[", ":", "-", "1", "]", "line", "+=", "'\\n'", "file_object", ".", "write", "(", "line", ")", "tf", ".", "io", ".", "gfile", ".", "remove", "(", "temp_file", ")" ]
[ 100, 0 ]
[ 123, 33 ]
python
en
['en', 'en', 'en']
True
download
(data_dir)
Downloads census data if it is not already present. Args: data_dir: directory where we will access/save the census data
Downloads census data if it is not already present.
def download(data_dir): """Downloads census data if it is not already present. Args: data_dir: directory where we will access/save the census data """ tf.io.gfile.makedirs(data_dir) training_file_path = os.path.join(data_dir, TRAINING_FILE) if not tf.io.gfile.exists(training_file_path): _download_and_clean_file(training_file_path, TRAINING_URL) eval_file_path = os.path.join(data_dir, EVAL_FILE) if not tf.io.gfile.exists(eval_file_path): _download_and_clean_file(eval_file_path, EVAL_URL) return training_file_path, eval_file_path
[ "def", "download", "(", "data_dir", ")", ":", "tf", ".", "io", ".", "gfile", ".", "makedirs", "(", "data_dir", ")", "training_file_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "TRAINING_FILE", ")", "if", "not", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "training_file_path", ")", ":", "_download_and_clean_file", "(", "training_file_path", ",", "TRAINING_URL", ")", "eval_file_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "EVAL_FILE", ")", "if", "not", "tf", ".", "io", ".", "gfile", ".", "exists", "(", "eval_file_path", ")", ":", "_download_and_clean_file", "(", "eval_file_path", ",", "EVAL_URL", ")", "return", "training_file_path", ",", "eval_file_path" ]
[ 126, 0 ]
[ 142, 45 ]
python
en
['en', 'en', 'en']
True
preprocess
(dataframe)
Converts categorical features to numeric. Removes unused columns. Args: dataframe: Pandas dataframe with raw data Returns: Dataframe with preprocessed data
Converts categorical features to numeric. Removes unused columns.
def preprocess(dataframe): """Converts categorical features to numeric. Removes unused columns. Args: dataframe: Pandas dataframe with raw data Returns: Dataframe with preprocessed data """ dataframe = dataframe.drop(columns=UNUSED_COLUMNS) # Convert integer valued (numeric) columns to floating point numeric_columns = dataframe.select_dtypes(['int64']).columns dataframe[numeric_columns] = dataframe[numeric_columns].astype('float32') # Convert categorical columns to numeric cat_columns = dataframe.select_dtypes(['object']).columns dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.astype( _CATEGORICAL_TYPES[x.name])) dataframe[cat_columns] = dataframe[cat_columns].apply(lambda x: x.cat.codes) return dataframe
[ "def", "preprocess", "(", "dataframe", ")", ":", "dataframe", "=", "dataframe", ".", "drop", "(", "columns", "=", "UNUSED_COLUMNS", ")", "# Convert integer valued (numeric) columns to floating point", "numeric_columns", "=", "dataframe", ".", "select_dtypes", "(", "[", "'int64'", "]", ")", ".", "columns", "dataframe", "[", "numeric_columns", "]", "=", "dataframe", "[", "numeric_columns", "]", ".", "astype", "(", "'float32'", ")", "# Convert categorical columns to numeric", "cat_columns", "=", "dataframe", ".", "select_dtypes", "(", "[", "'object'", "]", ")", ".", "columns", "dataframe", "[", "cat_columns", "]", "=", "dataframe", "[", "cat_columns", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "astype", "(", "_CATEGORICAL_TYPES", "[", "x", ".", "name", "]", ")", ")", "dataframe", "[", "cat_columns", "]", "=", "dataframe", "[", "cat_columns", "]", ".", "apply", "(", "lambda", "x", ":", "x", ".", "cat", ".", "codes", ")", "return", "dataframe" ]
[ 145, 0 ]
[ 165, 20 ]
python
en
['en', 'en', 'en']
True
standardize
(dataframe)
Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training. Args: dataframe: Pandas dataframe Returns: Input dataframe with the numerical columns scaled to z-scores
Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training.
def standardize(dataframe): """Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training. Args: dataframe: Pandas dataframe Returns: Input dataframe with the numerical columns scaled to z-scores """ dtypes = list(zip(dataframe.dtypes.index, map(str, dataframe.dtypes))) # Normalize numeric columns. for column, dtype in dtypes: if dtype == 'float32': dataframe[column] -= dataframe[column].mean() dataframe[column] /= dataframe[column].std() return dataframe
[ "def", "standardize", "(", "dataframe", ")", ":", "dtypes", "=", "list", "(", "zip", "(", "dataframe", ".", "dtypes", ".", "index", ",", "map", "(", "str", ",", "dataframe", ".", "dtypes", ")", ")", ")", "# Normalize numeric columns.", "for", "column", ",", "dtype", "in", "dtypes", ":", "if", "dtype", "==", "'float32'", ":", "dataframe", "[", "column", "]", "-=", "dataframe", "[", "column", "]", ".", "mean", "(", ")", "dataframe", "[", "column", "]", "/=", "dataframe", "[", "column", "]", ".", "std", "(", ")", "return", "dataframe" ]
[ 168, 0 ]
[ 185, 20 ]
python
en
['en', 'en', 'en']
True
load_data
()
Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes. Returns: A tuple (train_x, train_y, eval_x, eval_y), where train_x and eval_x are Pandas dataframes with features for training and train_y and eval_y are numpy arrays with the corresponding labels.
Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes.
def load_data(): """Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes. Returns: A tuple (train_x, train_y, eval_x, eval_y), where train_x and eval_x are Pandas dataframes with features for training and train_y and eval_y are numpy arrays with the corresponding labels. """ # Download Census dataset: Training and eval csv files. training_file_path, eval_file_path = download(DATA_DIR) # This census data uses the value '?' for missing entries. We use # na_values to # find ? and set it to NaN. # https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv # .html train_df = pd.read_csv(training_file_path, names=_CSV_COLUMNS, na_values='?') eval_df = pd.read_csv(eval_file_path, names=_CSV_COLUMNS, na_values='?') train_df = preprocess(train_df) eval_df = preprocess(eval_df) # Split train and eval data with labels. The pop method copies and removes # the label column from the dataframe. train_x, train_y = train_df, train_df.pop(_LABEL_COLUMN) eval_x, eval_y = eval_df, eval_df.pop(_LABEL_COLUMN) # Join train_x and eval_x to normalize on overall means and standard # deviations. Then separate them again. all_x = pd.concat([train_x, eval_x], keys=['train', 'eval']) all_x = standardize(all_x) train_x, eval_x = all_x.xs('train'), all_x.xs('eval') # Reshape label columns for use with tf.data.Dataset train_y = np.asarray(train_y).astype('float32').reshape((-1, 1)) eval_y = np.asarray(eval_y).astype('float32').reshape((-1, 1)) return train_x, train_y, eval_x, eval_y
[ "def", "load_data", "(", ")", ":", "# Download Census dataset: Training and eval csv files.", "training_file_path", ",", "eval_file_path", "=", "download", "(", "DATA_DIR", ")", "# This census data uses the value '?' for missing entries. We use", "# na_values to", "# find ? and set it to NaN.", "# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv", "# .html", "train_df", "=", "pd", ".", "read_csv", "(", "training_file_path", ",", "names", "=", "_CSV_COLUMNS", ",", "na_values", "=", "'?'", ")", "eval_df", "=", "pd", ".", "read_csv", "(", "eval_file_path", ",", "names", "=", "_CSV_COLUMNS", ",", "na_values", "=", "'?'", ")", "train_df", "=", "preprocess", "(", "train_df", ")", "eval_df", "=", "preprocess", "(", "eval_df", ")", "# Split train and eval data with labels. The pop method copies and removes", "# the label column from the dataframe.", "train_x", ",", "train_y", "=", "train_df", ",", "train_df", ".", "pop", "(", "_LABEL_COLUMN", ")", "eval_x", ",", "eval_y", "=", "eval_df", ",", "eval_df", ".", "pop", "(", "_LABEL_COLUMN", ")", "# Join train_x and eval_x to normalize on overall means and standard", "# deviations. Then separate them again.", "all_x", "=", "pd", ".", "concat", "(", "[", "train_x", ",", "eval_x", "]", ",", "keys", "=", "[", "'train'", ",", "'eval'", "]", ")", "all_x", "=", "standardize", "(", "all_x", ")", "train_x", ",", "eval_x", "=", "all_x", ".", "xs", "(", "'train'", ")", ",", "all_x", ".", "xs", "(", "'eval'", ")", "# Reshape label columns for use with tf.data.Dataset", "train_y", "=", "np", ".", "asarray", "(", "train_y", ")", ".", "astype", "(", "'float32'", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "eval_y", "=", "np", ".", "asarray", "(", "eval_y", ")", ".", "astype", "(", "'float32'", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "return", "train_x", ",", "train_y", ",", "eval_x", ",", "eval_y" ]
[ 188, 0 ]
[ 227, 43 ]
python
en
['en', 'es', 'en']
True
JSONWebSignatureSerializer.dumps
(self, obj, salt=None, header_fields=None)
Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header.
Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header.
def dumps(self, obj, salt=None, header_fields=None): """Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header. """ header = self.make_header(header_fields) signer = self.make_signer(salt, self.algorithm) return signer.sign(self.dump_payload(header, obj))
[ "def", "dumps", "(", "self", ",", "obj", ",", "salt", "=", "None", ",", "header_fields", "=", "None", ")", ":", "header", "=", "self", ".", "make_header", "(", "header_fields", ")", "signer", "=", "self", ".", "make_signer", "(", "salt", ",", "self", ".", "algorithm", ")", "return", "signer", ".", "sign", "(", "self", ".", "dump_payload", "(", "header", ",", "obj", ")", ")" ]
[ 128, 4 ]
[ 135, 58 ]
python
en
['en', 'en', 'en']
True
JSONWebSignatureSerializer.loads
(self, s, salt=None, return_header=False)
Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header.
Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header.
def loads(self, s, salt=None, return_header=False): """Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header. """ payload, header = self.load_payload( self.make_signer(salt, self.algorithm).unsign(want_bytes(s)), return_header=True, ) if header.get("alg") != self.algorithm_name: raise BadHeader("Algorithm mismatch", header=header, payload=payload) if return_header: return payload, header return payload
[ "def", "loads", "(", "self", ",", "s", ",", "salt", "=", "None", ",", "return_header", "=", "False", ")", ":", "payload", ",", "header", "=", "self", ".", "load_payload", "(", "self", ".", "make_signer", "(", "salt", ",", "self", ".", "algorithm", ")", ".", "unsign", "(", "want_bytes", "(", "s", ")", ")", ",", "return_header", "=", "True", ",", ")", "if", "header", ".", "get", "(", "\"alg\"", ")", "!=", "self", ".", "algorithm_name", ":", "raise", "BadHeader", "(", "\"Algorithm mismatch\"", ",", "header", "=", "header", ",", "payload", "=", "payload", ")", "if", "return_header", ":", "return", "payload", ",", "header", "return", "payload" ]
[ 137, 4 ]
[ 149, 22 ]
python
en
['en', 'en', 'en']
True
_contains_egg_info
(s)
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
Determine whether the string looks like an egg_info.
def _contains_egg_info(s): # type: (str) -> bool """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
[ "def", "_contains_egg_info", "(", "s", ")", ":", "# type: (str) -> bool", "return", "bool", "(", "_egg_info_re", ".", "search", "(", "s", ")", ")" ]
[ 36, 0 ]
[ 42, 39 ]
python
en
['en', 'en', 'en']
True
_should_build
( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate )
Return whether an InstallRequirement should be built into a wheel.
Return whether an InstallRequirement should be built into a wheel.
def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are merely constraints return False if req.is_wheel: if need_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) return False if need_wheel: # i.e. pip wheel, not pip install return True # From this point, this concerns the pip install command only # (need_wheel=False). if req.editable or not req.source_dir: return False if req.use_pep517: return True if not check_binary_allowed(req): logger.info( "Skipping wheel build for %s, due to binaries " "being disabled for it.", req.name, ) return False if not is_wheel_installed(): # we don't build legacy requirements if wheel is not installed logger.info( "Using legacy 'setup.py install' for %s, " "since package 'wheel' is not installed.", req.name, ) return False return True
[ "def", "_should_build", "(", "req", ",", "# type: InstallRequirement", "need_wheel", ",", "# type: bool", "check_binary_allowed", ",", "# type: BinaryAllowedPredicate", ")", ":", "# type: (...) -> bool", "if", "req", ".", "constraint", ":", "# never build requirements that are merely constraints", "return", "False", "if", "req", ".", "is_wheel", ":", "if", "need_wheel", ":", "logger", ".", "info", "(", "'Skipping %s, due to already being wheel.'", ",", "req", ".", "name", ",", ")", "return", "False", "if", "need_wheel", ":", "# i.e. pip wheel, not pip install", "return", "True", "# From this point, this concerns the pip install command only", "# (need_wheel=False).", "if", "req", ".", "editable", "or", "not", "req", ".", "source_dir", ":", "return", "False", "if", "req", ".", "use_pep517", ":", "return", "True", "if", "not", "check_binary_allowed", "(", "req", ")", ":", "logger", ".", "info", "(", "\"Skipping wheel build for %s, due to binaries \"", "\"being disabled for it.\"", ",", "req", ".", "name", ",", ")", "return", "False", "if", "not", "is_wheel_installed", "(", ")", ":", "# we don't build legacy requirements if wheel is not installed", "logger", ".", "info", "(", "\"Using legacy 'setup.py install' for %s, \"", "\"since package 'wheel' is not installed.\"", ",", "req", ".", "name", ",", ")", "return", "False", "return", "True" ]
[ 45, 0 ]
[ 90, 15 ]
python
en
['en', 'en', 'en']
True
_should_cache
( req, # type: InstallRequirement )
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
def _should_cache( req, # type: InstallRequirement ): # type: (...) -> Optional[bool] """ Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. """ if req.editable or not req.source_dir: # never cache editable requirements return False if req.link and req.link.is_vcs: # VCS checkout. Do not cache # unless it points to an immutable commit hash. assert not req.editable assert req.source_dir vcs_backend = vcs.get_backend_for_scheme(req.link.scheme) assert vcs_backend if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir): return True return False assert req.link base, ext = req.link.splitext() if _contains_egg_info(base): return True # Otherwise, do not cache. return False
[ "def", "_should_cache", "(", "req", ",", "# type: InstallRequirement", ")", ":", "# type: (...) -> Optional[bool]", "if", "req", ".", "editable", "or", "not", "req", ".", "source_dir", ":", "# never cache editable requirements", "return", "False", "if", "req", ".", "link", "and", "req", ".", "link", ".", "is_vcs", ":", "# VCS checkout. Do not cache", "# unless it points to an immutable commit hash.", "assert", "not", "req", ".", "editable", "assert", "req", ".", "source_dir", "vcs_backend", "=", "vcs", ".", "get_backend_for_scheme", "(", "req", ".", "link", ".", "scheme", ")", "assert", "vcs_backend", "if", "vcs_backend", ".", "is_immutable_rev_checkout", "(", "req", ".", "link", ".", "url", ",", "req", ".", "source_dir", ")", ":", "return", "True", "return", "False", "assert", "req", ".", "link", "base", ",", "ext", "=", "req", ".", "link", ".", "splitext", "(", ")", "if", "_contains_egg_info", "(", "base", ")", ":", "return", "True", "# Otherwise, do not cache.", "return", "False" ]
[ 112, 0 ]
[ 142, 16 ]
python
en
['en', 'error', 'th']
False
_get_cache_dir
( req, # type: InstallRequirement wheel_cache, # type: WheelCache )
Return the persistent or temporary cache directory where the built wheel need to be stored.
Return the persistent or temporary cache directory where the built wheel need to be stored.
def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) assert req.link if cache_available and _should_cache(req): cache_dir = wheel_cache.get_path_for_link(req.link) else: cache_dir = wheel_cache.get_ephem_path_for_link(req.link) return cache_dir
[ "def", "_get_cache_dir", "(", "req", ",", "# type: InstallRequirement", "wheel_cache", ",", "# type: WheelCache", ")", ":", "# type: (...) -> str", "cache_available", "=", "bool", "(", "wheel_cache", ".", "cache_dir", ")", "assert", "req", ".", "link", "if", "cache_available", "and", "_should_cache", "(", "req", ")", ":", "cache_dir", "=", "wheel_cache", ".", "get_path_for_link", "(", "req", ".", "link", ")", "else", ":", "cache_dir", "=", "wheel_cache", ".", "get_ephem_path_for_link", "(", "req", ".", "link", ")", "return", "cache_dir" ]
[ 145, 0 ]
[ 159, 20 ]
python
en
['en', 'en', 'en']
True
_build_one
( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] )
Build one wheel. :return: The filename of the built wheel, or None if the build failed.
Build one wheel.
def _build_one( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ensure_dir(output_dir) except OSError as e: logger.warning( "Building wheel for %s failed: %s", req.name, e, ) return None # Install build deps into temporary directory (PEP 518) with req.build_env: wheel_path = _build_one_inside_env( req, output_dir, build_options, global_options ) if wheel_path and verify: try: _verify_one(req, wheel_path) except (InvalidWheelFilename, UnsupportedWheel) as e: logger.warning("Built wheel for %s is invalid: %s", req.name, e) return None return wheel_path
[ "def", "_build_one", "(", "req", ",", "# type: InstallRequirement", "output_dir", ",", "# type: str", "verify", ",", "# type: bool", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> Optional[str]", "try", ":", "ensure_dir", "(", "output_dir", ")", "except", "OSError", "as", "e", ":", "logger", ".", "warning", "(", "\"Building wheel for %s failed: %s\"", ",", "req", ".", "name", ",", "e", ",", ")", "return", "None", "# Install build deps into temporary directory (PEP 518)", "with", "req", ".", "build_env", ":", "wheel_path", "=", "_build_one_inside_env", "(", "req", ",", "output_dir", ",", "build_options", ",", "global_options", ")", "if", "wheel_path", "and", "verify", ":", "try", ":", "_verify_one", "(", "req", ",", "wheel_path", ")", "except", "(", "InvalidWheelFilename", ",", "UnsupportedWheel", ")", "as", "e", ":", "logger", ".", "warning", "(", "\"Built wheel for %s is invalid: %s\"", ",", "req", ".", "name", ",", "e", ")", "return", "None", "return", "wheel_path" ]
[ 199, 0 ]
[ 231, 21 ]
python
en
['en', 'sr', 'en']
True
build
( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] )
Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build.
Build wheels.
def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build. """ if not requirements: return [], [] # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join(req.name for req in requirements), # type: ignore ) with indent_log(): build_successes, build_failures = [], [] for req in requirements: cache_dir = _get_cache_dir(req, wheel_cache) wheel_file = _build_one( req, cache_dir, verify, build_options, global_options ) if wheel_file: # Update the link for this. req.link = Link(path_to_url(wheel_file)) req.local_file_path = req.link.file_path assert req.link.is_wheel build_successes.append(req) else: build_failures.append(req) # notify success/failure if build_successes: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_successes]), # type: ignore ) if build_failures: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failures]), # type: ignore ) # Return a list of requirements that failed to build return build_successes, build_failures
[ "def", "build", "(", "requirements", ",", "# type: Iterable[InstallRequirement]", "wheel_cache", ",", "# type: WheelCache", "verify", ",", "# type: bool", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> BuildResult", "if", "not", "requirements", ":", "return", "[", "]", ",", "[", "]", "# Build the wheels.", "logger", ".", "info", "(", "'Building wheels for collected packages: %s'", ",", "', '", ".", "join", "(", "req", ".", "name", "for", "req", "in", "requirements", ")", ",", "# type: ignore", ")", "with", "indent_log", "(", ")", ":", "build_successes", ",", "build_failures", "=", "[", "]", ",", "[", "]", "for", "req", "in", "requirements", ":", "cache_dir", "=", "_get_cache_dir", "(", "req", ",", "wheel_cache", ")", "wheel_file", "=", "_build_one", "(", "req", ",", "cache_dir", ",", "verify", ",", "build_options", ",", "global_options", ")", "if", "wheel_file", ":", "# Update the link for this.", "req", ".", "link", "=", "Link", "(", "path_to_url", "(", "wheel_file", ")", ")", "req", ".", "local_file_path", "=", "req", ".", "link", ".", "file_path", "assert", "req", ".", "link", ".", "is_wheel", "build_successes", ".", "append", "(", "req", ")", "else", ":", "build_failures", ".", "append", "(", "req", ")", "# notify success/failure", "if", "build_successes", ":", "logger", ".", "info", "(", "'Successfully built %s'", ",", "' '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "build_successes", "]", ")", ",", "# type: ignore", ")", "if", "build_failures", ":", "logger", ".", "info", "(", "'Failed to build %s'", ",", "' '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "build_failures", "]", ")", ",", "# type: ignore", ")", "# Return a list of requirements that failed to build", "return", "build_successes", ",", "build_failures" ]
[ 309, 0 ]
[ 359, 42 ]
python
en
['en', 'sr', 'en']
False
do_get_available_languages
(parser, token)
Store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This puts settings.LANGUAGES into the named variable.
Store a list of available languages in the context.
def do_get_available_languages(parser, token): """ Store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This puts settings.LANGUAGES into the named variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args) return GetAvailableLanguagesNode(args[2])
[ "def", "do_get_available_languages", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", "!=", "3", "or", "args", "[", "1", "]", "!=", "'as'", ":", "raise", "TemplateSyntaxError", "(", "\"'get_available_languages' requires 'as variable' (got %r)\"", "%", "args", ")", "return", "GetAvailableLanguagesNode", "(", "args", "[", "2", "]", ")" ]
[ 198, 0 ]
[ 215, 45 ]
python
en
['en', 'error', 'th']
False
do_get_language_info
(parser, token)
Store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }}
Store the language information dictionary for the given language code in a context variable.
def do_get_language_info(parser, token): """ Store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
[ "def", "do_get_language_info", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "5", "or", "args", "[", "1", "]", "!=", "'for'", "or", "args", "[", "3", "]", "!=", "'as'", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' requires 'for string as variable' (got %r)\"", "%", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", ")", ")", "return", "GetLanguageInfoNode", "(", "parser", ".", "compile_filter", "(", "args", "[", "2", "]", ")", ",", "args", "[", "4", "]", ")" ]
[ 219, 0 ]
[ 236, 71 ]
python
en
['en', 'error', 'th']
False
do_get_language_info_list
(parser, token)
Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %}
Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes).
def do_get_language_info_list(parser, token): """ Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %} """ args = token.split_contents() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
[ "def", "do_get_language_info_list", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "5", "or", "args", "[", "1", "]", "!=", "'for'", "or", "args", "[", "3", "]", "!=", "'as'", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' requires 'for sequence as variable' (got %r)\"", "%", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", ")", ")", "return", "GetLanguageInfoListNode", "(", "parser", ".", "compile_filter", "(", "args", "[", "2", "]", ")", ",", "args", "[", "4", "]", ")" ]
[ 240, 0 ]
[ 261, 75 ]
python
en
['en', 'error', 'th']
False
do_get_current_language
(parser, token)
Store the current language in the context. Usage:: {% get_current_language as language %} This fetches the currently active language and puts its value into the ``language`` context variable.
Store the current language in the context.
def do_get_current_language(parser, token): """ Store the current language in the context. Usage:: {% get_current_language as language %} This fetches the currently active language and puts its value into the ``language`` context variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args) return GetCurrentLanguageNode(args[2])
[ "def", "do_get_current_language", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", "!=", "3", "or", "args", "[", "1", "]", "!=", "'as'", ":", "raise", "TemplateSyntaxError", "(", "\"'get_current_language' requires 'as variable' (got %r)\"", "%", "args", ")", "return", "GetCurrentLanguageNode", "(", "args", "[", "2", "]", ")" ]
[ 286, 0 ]
[ 301, 42 ]
python
en
['en', 'error', 'th']
False
do_get_current_language_bidi
(parser, token)
Store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This fetches the currently active language's layout and puts its value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right.
Store the current language layout in the context.
def do_get_current_language_bidi(parser, token): """ Store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This fetches the currently active language's layout and puts its value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args) return GetCurrentLanguageBidiNode(args[2])
[ "def", "do_get_current_language_bidi", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", "!=", "3", "or", "args", "[", "1", "]", "!=", "'as'", ":", "raise", "TemplateSyntaxError", "(", "\"'get_current_language_bidi' requires 'as variable' (got %r)\"", "%", "args", ")", "return", "GetCurrentLanguageBidiNode", "(", "args", "[", "2", "]", ")" ]
[ 305, 0 ]
[ 321, 46 ]
python
en
['en', 'error', 'th']
False
do_translate
(parser, token)
Mark a string for translation and translate the string for the current language. Usage:: {% translate "this is a test" %} This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through the translation engine. There is a second form:: {% translate "this is a test" noop %} This marks the string for translation, but returns the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% translate variable %} This tries to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% translate "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% translate "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext.
Mark a string for translation and translate the string for the current language.
def do_translate(parser, token): """ Mark a string for translation and translate the string for the current language. Usage:: {% translate "this is a test" %} This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through the translation engine. There is a second form:: {% translate "this is a test" noop %} This marks the string for translation, but returns the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% translate variable %} This tries to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. It is possible to store the translated string into a variable:: {% translate "this is a test" as var %} {{ var }} Contextual translations are also supported:: {% translate "this is a test" context "greeting" %} This is equivalent to calling pgettext instead of (u)gettext. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {'as', 'noop'} while remaining: option = remaining.pop(0) if option in seen: raise TemplateSyntaxError( "The '%s' option was specified more than once." % option, ) elif option == 'noop': noop = True elif option == 'context': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the context option." % bits[0] ) if value in invalid_context: raise TemplateSyntaxError( "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == 'as': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the as option." % bits[0] ) asvar = value else: raise TemplateSyntaxError( "Unknown argument for '%s' tag: '%s'. The only options " "available are 'noop', 'context' \"xxx\", and 'as VAR'." % ( bits[0], option, ) ) seen.add(option) return TranslateNode(message_string, noop, asvar, message_context)
[ "def", "do_translate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least one argument\"", "%", "bits", "[", "0", "]", ")", "message_string", "=", "parser", ".", "compile_filter", "(", "bits", "[", "1", "]", ")", "remaining", "=", "bits", "[", "2", ":", "]", "noop", "=", "False", "asvar", "=", "None", "message_context", "=", "None", "seen", "=", "set", "(", ")", "invalid_context", "=", "{", "'as'", ",", "'noop'", "}", "while", "remaining", ":", "option", "=", "remaining", ".", "pop", "(", "0", ")", "if", "option", "in", "seen", ":", "raise", "TemplateSyntaxError", "(", "\"The '%s' option was specified more than once.\"", "%", "option", ",", ")", "elif", "option", "==", "'noop'", ":", "noop", "=", "True", "elif", "option", "==", "'context'", ":", "try", ":", "value", "=", "remaining", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "raise", "TemplateSyntaxError", "(", "\"No argument provided to the '%s' tag for the context option.\"", "%", "bits", "[", "0", "]", ")", "if", "value", "in", "invalid_context", ":", "raise", "TemplateSyntaxError", "(", "\"Invalid argument '%s' provided to the '%s' tag for the context option\"", "%", "(", "value", ",", "bits", "[", "0", "]", ")", ",", ")", "message_context", "=", "parser", ".", "compile_filter", "(", "value", ")", "elif", "option", "==", "'as'", ":", "try", ":", "value", "=", "remaining", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "raise", "TemplateSyntaxError", "(", "\"No argument provided to the '%s' tag for the as option.\"", "%", "bits", "[", "0", "]", ")", "asvar", "=", "value", "else", ":", "raise", "TemplateSyntaxError", "(", "\"Unknown argument for '%s' tag: '%s'. The only options \"", "\"available are 'noop', 'context' \\\"xxx\\\", and 'as VAR'.\"", "%", "(", "bits", "[", "0", "]", ",", "option", ",", ")", ")", "seen", ".", "add", "(", "option", ")", "return", "TranslateNode", "(", "message_string", ",", "noop", ",", "asvar", ",", "message_context", ")" ]
[ 326, 0 ]
[ 415, 70 ]
python
en
['en', 'error', 'th']
False
do_block_translate
(parser, token)
Translate a block of text with parameters. Usage:: {% blocktranslate with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} Additionally, this supports pluralization:: {% blocktranslate count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktranslate %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktranslate with foo|filter as bar and baz|filter as boo %} {% blocktranslate count var|length as count %} The translated string can be stored in a variable using `asvar`:: {% blocktranslate with bar=foo|filter boo=baz|filter asvar var %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} {{ var }} Contextual translations are supported:: {% blocktranslate with bar=foo|filter context "greeting" %} This is {{ bar }}. {% endblocktranslate %} This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext.
Translate a block of text with parameters.
def do_block_translate(parser, token): """ Translate a block of text with parameters. Usage:: {% blocktranslate with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} Additionally, this supports pluralization:: {% blocktranslate count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktranslate %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktranslate with foo|filter as bar and baz|filter as boo %} {% blocktranslate count var|length as count %} The translated string can be stored in a variable using `asvar`:: {% blocktranslate with bar=foo|filter boo=baz|filter asvar var %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} {{ var }} Contextual translations are supported:: {% blocktranslate with bar=foo|filter context "greeting" %} This is {{ bar }}. {% endblocktranslate %} This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext. """ bits = token.split_contents() options = {} remaining_bits = bits[1:] asvar = None while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError('The %r option was specified more ' 'than once.' % option) if option == 'with': value = token_kwargs(remaining_bits, parser, support_legacy=True) if not value: raise TemplateSyntaxError('"with" in %r tag needs at least ' 'one keyword argument.' % bits[0]) elif option == 'count': value = token_kwargs(remaining_bits, parser, support_legacy=True) if len(value) != 1: raise TemplateSyntaxError('"count" in %r tag expected exactly ' 'one keyword argument.' % bits[0]) elif option == "context": try: value = remaining_bits.pop(0) value = parser.compile_filter(value) except Exception: raise TemplateSyntaxError( '"context" in %r tag expected exactly one argument.' % bits[0] ) elif option == "trimmed": value = True elif option == "asvar": try: value = remaining_bits.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the asvar option." % bits[0] ) asvar = value else: raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % (bits[0], option)) options[option] = value if 'count' in options: countervar, counter = next(iter(options['count'].items())) else: countervar, counter = None, None if 'context' in options: message_context = options['context'] else: message_context = None extra_context = options.get('with', {}) trimmed = options.get("trimmed", False) singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TokenType.VAR, TokenType.TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError("%r doesn't allow other block tags inside it" % bits[0]) while parser.tokens: token = parser.next_token() if token.token_type in (TokenType.VAR, TokenType.TEXT): plural.append(token) else: break end_tag_name = 'end%s' % bits[0] if token.contents.strip() != end_tag_name: raise TemplateSyntaxError("%r doesn't allow other block tags (seen %r) inside it" % (bits[0], token.contents)) return BlockTranslateNode(extra_context, singular, plural, countervar, counter, message_context, trimmed=trimmed, asvar=asvar, tag_name=bits[0])
[ "def", "do_block_translate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "options", "=", "{", "}", "remaining_bits", "=", "bits", "[", "1", ":", "]", "asvar", "=", "None", "while", "remaining_bits", ":", "option", "=", "remaining_bits", ".", "pop", "(", "0", ")", "if", "option", "in", "options", ":", "raise", "TemplateSyntaxError", "(", "'The %r option was specified more '", "'than once.'", "%", "option", ")", "if", "option", "==", "'with'", ":", "value", "=", "token_kwargs", "(", "remaining_bits", ",", "parser", ",", "support_legacy", "=", "True", ")", "if", "not", "value", ":", "raise", "TemplateSyntaxError", "(", "'\"with\" in %r tag needs at least '", "'one keyword argument.'", "%", "bits", "[", "0", "]", ")", "elif", "option", "==", "'count'", ":", "value", "=", "token_kwargs", "(", "remaining_bits", ",", "parser", ",", "support_legacy", "=", "True", ")", "if", "len", "(", "value", ")", "!=", "1", ":", "raise", "TemplateSyntaxError", "(", "'\"count\" in %r tag expected exactly '", "'one keyword argument.'", "%", "bits", "[", "0", "]", ")", "elif", "option", "==", "\"context\"", ":", "try", ":", "value", "=", "remaining_bits", ".", "pop", "(", "0", ")", "value", "=", "parser", ".", "compile_filter", "(", "value", ")", "except", "Exception", ":", "raise", "TemplateSyntaxError", "(", "'\"context\" in %r tag expected exactly one argument.'", "%", "bits", "[", "0", "]", ")", "elif", "option", "==", "\"trimmed\"", ":", "value", "=", "True", "elif", "option", "==", "\"asvar\"", ":", "try", ":", "value", "=", "remaining_bits", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "raise", "TemplateSyntaxError", "(", "\"No argument provided to the '%s' tag for the asvar option.\"", "%", "bits", "[", "0", "]", ")", "asvar", "=", "value", "else", ":", "raise", "TemplateSyntaxError", "(", "'Unknown argument for %r tag: %r.'", "%", "(", "bits", "[", "0", "]", ",", "option", ")", ")", "options", "[", "option", "]", "=", "value", "if", "'count'", "in", "options", ":", "countervar", ",", "counter", "=", "next", "(", "iter", "(", "options", "[", "'count'", "]", ".", "items", "(", ")", ")", ")", "else", ":", "countervar", ",", "counter", "=", "None", ",", "None", "if", "'context'", "in", "options", ":", "message_context", "=", "options", "[", "'context'", "]", "else", ":", "message_context", "=", "None", "extra_context", "=", "options", ".", "get", "(", "'with'", ",", "{", "}", ")", "trimmed", "=", "options", ".", "get", "(", "\"trimmed\"", ",", "False", ")", "singular", "=", "[", "]", "plural", "=", "[", "]", "while", "parser", ".", "tokens", ":", "token", "=", "parser", ".", "next_token", "(", ")", "if", "token", ".", "token_type", "in", "(", "TokenType", ".", "VAR", ",", "TokenType", ".", "TEXT", ")", ":", "singular", ".", "append", "(", "token", ")", "else", ":", "break", "if", "countervar", "and", "counter", ":", "if", "token", ".", "contents", ".", "strip", "(", ")", "!=", "'plural'", ":", "raise", "TemplateSyntaxError", "(", "\"%r doesn't allow other block tags inside it\"", "%", "bits", "[", "0", "]", ")", "while", "parser", ".", "tokens", ":", "token", "=", "parser", ".", "next_token", "(", ")", "if", "token", ".", "token_type", "in", "(", "TokenType", ".", "VAR", ",", "TokenType", ".", "TEXT", ")", ":", "plural", ".", "append", "(", "token", ")", "else", ":", "break", "end_tag_name", "=", "'end%s'", "%", "bits", "[", "0", "]", "if", "token", ".", "contents", ".", "strip", "(", ")", "!=", "end_tag_name", ":", "raise", "TemplateSyntaxError", "(", "\"%r doesn't allow other block tags (seen %r) inside it\"", "%", "(", "bits", "[", "0", "]", ",", "token", ".", "contents", ")", ")", "return", "BlockTranslateNode", "(", "extra_context", ",", "singular", ",", "plural", ",", "countervar", ",", "counter", ",", "message_context", ",", "trimmed", "=", "trimmed", ",", "asvar", "=", "asvar", ",", "tag_name", "=", "bits", "[", "0", "]", ")" ]
[ 420, 0 ]
[ 539, 60 ]
python
en
['en', 'error', 'th']
False
language
(parser, token)
Enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %}
Enable the given language just for this block.
def language(parser, token): """ Enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0]) language = parser.compile_filter(bits[1]) nodelist = parser.parse(('endlanguage',)) parser.delete_first_token() return LanguageNode(nodelist, language)
[ "def", "language", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes one argument (language)\"", "%", "bits", "[", "0", "]", ")", "language", "=", "parser", ".", "compile_filter", "(", "bits", "[", "1", "]", ")", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endlanguage'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "LanguageNode", "(", "nodelist", ",", "language", ")" ]
[ 543, 0 ]
[ 559, 43 ]
python
en
['en', 'error', 'th']
False
preprocessing_judgement
(pred, bias)
前処理判断 :pred bias: model.predict()の戻り値 :return: 未定
前処理判断 :pred bias: model.predict()の戻り値 :return: 未定
def preprocessing_judgement(pred, bias): """ 前処理判断 :pred bias: model.predict()の戻り値 :return: 未定 """ # 判断がtargetだったら if pred[0].argmax() == 0: result = bias_judgement(score=max(pred[0]), threshold=bias) else: result = 'not_target' return result
[ "def", "preprocessing_judgement", "(", "pred", ",", "bias", ")", ":", "# 判断がtargetだったら", "if", "pred", "[", "0", "]", ".", "argmax", "(", ")", "==", "0", ":", "result", "=", "bias_judgement", "(", "score", "=", "max", "(", "pred", "[", "0", "]", ")", ",", "threshold", "=", "bias", ")", "else", ":", "result", "=", "'not_target'", "return", "result" ]
[ 5, 0 ]
[ 17, 17 ]
python
en
['en', 'error', 'th']
False
SetEncoder._componentSortKey
(componentAndType)
Sort SET components by tag Sort regardless of the Choice value (static sort)
Sort SET components by tag
def _componentSortKey(componentAndType): """Sort SET components by tag Sort regardless of the Choice value (static sort) """ component, asn1Spec = componentAndType if asn1Spec is None: asn1Spec = component if asn1Spec.typeId == univ.Choice.typeId and not asn1Spec.tagSet: if asn1Spec.tagSet: return asn1Spec.tagSet else: return asn1Spec.componentType.minTagSet else: return asn1Spec.tagSet
[ "def", "_componentSortKey", "(", "componentAndType", ")", ":", "component", ",", "asn1Spec", "=", "componentAndType", "if", "asn1Spec", "is", "None", ":", "asn1Spec", "=", "component", "if", "asn1Spec", ".", "typeId", "==", "univ", ".", "Choice", ".", "typeId", "and", "not", "asn1Spec", ".", "tagSet", ":", "if", "asn1Spec", ".", "tagSet", ":", "return", "asn1Spec", ".", "tagSet", "else", ":", "return", "asn1Spec", ".", "componentType", ".", "minTagSet", "else", ":", "return", "asn1Spec", ".", "tagSet" ]
[ 144, 4 ]
[ 160, 34 ]
python
en
['en', 'en', 'en']
True