buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
to the w3lib.url module. Always import those from there instead. """ import posixpath import re from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag, urlparse, parse_qsl, urlencode, unquote) # scrapy.utils.url was moved to w3lib....
to the w3lib.url module. Always import those from there instead. """ import posixpath import re import six from six.moves.urllib.parse import (ParseResult, urlunparse, urldefrag, urlparse, parse_qsl, urlencode, quote, unquote) if six.PY3: from ...
def url_has_any_extension(url, extensions): return posixpath.splitext(parse_url(url).path)[1].lower() in extensions def canonicalize_url(url, keep_blank_values=True, keep_fragments=False, encoding=None): """Canonicalize the given url by applying the following procedures: - sort query...
def url_has_any_extension(url, extensions): return posixpath.splitext(parse_url(url).path)[1].lower() in extensions def _safe_ParseResult(parts, encoding='utf8', path_encoding='utf8'): return ( to_native_str(parts.scheme), to_native_str(parts.netloc.encode('idna')), # default encoding...
def parse_url(url, encoding=None): """ if isinstance(url, ParseResult): return url return urlparse(to_native_str(url, encoding)) def escape_ajax(url):
def parse_url(url, encoding=None): """ if isinstance(url, ParseResult): return url return urlparse(to_unicode(url, encoding)) if six.PY3: from urllib.parse import _coerce_args, unquote_to_bytes def parse_qsl_to_bytes(qs, keep_blank_values=False, strict_parsing=False): """Parse a q...
import unittest import six from scrapy.spiders import Spider from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider, canonicalize_url, add_http_if_no_scheme, guess_scheme) __doctests__ = ['scrapy.utils.url']
import unittest import six from six.moves.urllib.parse import urlparse from scrapy.spiders import Spider from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider, canonicalize_url, add_http_if_no_scheme, guess_scheme, parse_url) __doctests__...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"), "http://www.example.com/do?a=1&q=a+space") @unittest.skipUnless(six.PY2, "TODO") def test_normalize_percent_encoding_in_paths(self): ...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.example.com/do?q=a%20space&a=1"), "http://www.example.com/do?a=1&q=a+space") def test_canonicalize_url_unicode_path(self): self.assertEqual(canonicalize_url(u"http:/...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.example.com/a%20do%C2%A3.html?a=1") def test_non_ascii_percent_encoding_in_query_arguments(self): self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=\xa3500&a=5&z=3"), ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.example.com/a%20do%C2%A3.html?a=1") def test_non_ascii_percent_encoding_in_query_arguments(self): self.assertEqual(canonicalize_url(u"http://www.example.com/do?price=£500&a=5&z=3"), ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"), "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html") @unittest.skipUnless(six.PY2, "TODO") ...
class CanonicalizeUrlTest(unittest.TestCase): "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html"), "http://www.simplybedrooms.com/White-Bedroom-Furniture/Bedroom-Mirror:-Josephine-Cheval-Mirror.html") def test_safe_characters_unicode(self): ...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"), "http://www.example.com/") def test_quoted_slash_and_question_sign(self): self.assertEqual(canonicalize_url("http://foo.com/AC%2FDC+rocks%3f/?yeah=1"...
class CanonicalizeUrlTest(unittest.TestCase): self.assertEqual(canonicalize_url("http://www.EXAMPLE.com/"), "http://www.example.com/") def test_canonicalize_idns(self): self.assertEqual(canonicalize_url(u'http://www.bücher.de?q=bücher'), ...
from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()} )
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(exc.errors())}, )
from typing import List from fastapi import FastAPI from pydantic import BaseModel from starlette.testclient import TestClient app = FastAPI()
from decimal import Decimal from typing import List from fastapi import FastAPI from pydantic import BaseModel, condecimal from starlette.testclient import TestClient app = FastAPI()
app = FastAPI() class Item(BaseModel): name: str age: int @app.post("/items/")
app = FastAPI() class Item(BaseModel): name: str age: condecimal(gt=Decimal(0.0)) @app.post("/items/")
openapi_schema = { "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "age": {"title": "Age", "type": "integer"}, }, }, "ValidationError": {
openapi_schema = { "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "age": {"title": "Age", "exclusiveMinimum": 0.0, "type": "number"}, }, }, "ValidationError": {
openapi_schema = { }, } multiple_errors = { "detail": [ {
openapi_schema = { }, } single_error = { "detail": [ { "ctx": {"limit_value": 0.0}, "loc": ["body", "item", 0, "age"], "msg": "ensure this value is greater than 0", "type": "value_error.number.not_gt", } ] } multiple_errors = { "detail": ...
multiple_errors = { }, { "loc": ["body", "item", 0, "age"], "msg": "value is not a valid integer", "type": "type_error.integer", }, { "loc": ["body", "item", 1, "name"],
multiple_errors = { }, { "loc": ["body", "item", 0, "age"], "msg": "value is not a valid decimal", "type": "type_error.decimal", }, { "loc": ["body", "item", 1, "name"],
multiple_errors = { }, { "loc": ["body", "item", 1, "age"], "msg": "value is not a valid integer", "type": "type_error.integer", }, ] }
multiple_errors = { }, { "loc": ["body", "item", 1, "age"], "msg": "value is not a valid decimal", "type": "type_error.decimal", }, ] }
def test_put_correct_body(): assert response.json() == {"item": [{"name": "Foo", "age": 5}]} def test_put_incorrect_body(): response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}]) assert response.status_code == 422 assert response.json() == multiple_errors
def test_put_correct_body(): assert response.json() == {"item": [{"name": "Foo", "age": 5}]} def test_jsonable_encoder_requiring_error(): response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}]) assert response.status_code == 422 assert response.json() == single_error def test_put_inco...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = url...
def test_osx_proxy_bypass(self): bypass = {'exclude_simple': True, 'exceptions': []} self.assertTrue(_proxy_bypass_macosx_sysconf('test', bypass)) def check_basic_auth(self, headers, realm): with self.subTest(realm=realm, headers=headers): opener = OpenerDirector() p...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' 'realm=(["\']?)([^"\']*)\\2', re.I) # XXX could pre-emptively send auth info alrea...
class AbstractBasicAuthHandler: # allow for double- and single-quoted realm values # (single quotes are a violation of the RFC, but appear in the wild) rx = re.compile('(?:^|,)' # start of the string or ',' '[ \t]*' # optional whitespaces '([^ \t]+)' # scheme li...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def http_error_auth_reqed(self, authreq, host, req, headers): # host may be an authority (without userinfo) or a URL with an # authority # XXX could be multiple hea...
def __init__(self, password_mgr=None): self.passwd = password_mgr self.add_password = self.passwd.add_password def _parse_realm(self, header): # parse WWW-Authenticate header: accept multiple challenges per header found_challenge = False for mo in AbstractBasicAuthHandler.rx...
import hashlib import json import random import string import sys import tempfile
import hashlib import json import random import stat import string import sys import tempfile
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s.json" % (self.VERSION, self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: data = json...
def build(self): cache_file = os.path.join( tempfile.gettempdir(), "rply-%s-%s-%s-%s.json" % (self.VERSION, os.getuid(), self.cache_id, self.compute_grammar_hash(g)) ) table = None if os.path.exists(cache_file): with open(cache_file) as f: ...
class InvalidModeException(CookiecutterException): Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time. """
class InvalidModeException(CookiecutterException): Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time. """ class FailedHookException(CookiecutterException): """ Raised when a hook script fails """
from binaryornot.check import is_binary from .exceptions import ( NonTemplatedInputDirException, ContextDecodingException, OutputDirExistsException ) from .find import find_template from .utils import make_sure_path_exists, work_in from .hooks import run_hook, EXIT_SUCCESS def copy_without_render(path, co...
from binaryornot.check import is_binary from .exceptions import ( NonTemplatedInputDirException, ContextDecodingException, FailedHookException, OutputDirExistsException ) from .find import find_template from .utils import make_sure_path_exists, work_in from .hooks import run_hook def copy_without_rend...
def generate_files(repo_dir, context=None, output_dir='.', # run pre-gen hook from repo_dir with work_in(repo_dir): if run_hook('pre_gen_project', project_dir, context) != EXIT_SUCCESS: logging.error("Stopping generation because pre_gen_project" " hook script didn'...
def generate_files(repo_dir, context=None, output_dir='.', # run pre-gen hook from repo_dir with work_in(repo_dir): try: run_hook('pre_gen_project', project_dir, context) except FailedHookException: shutil.rmtree(project_dir, ignore_errors=True) logging.error...
import tempfile from jinja2 import Template from cookiecutter import utils _HOOKS = [
import tempfile from jinja2 import Template from cookiecutter import utils from .exceptions import FailedHookException _HOOKS = [
def run_script(script_path, cwd='.'): shell=run_thru_shell, cwd=cwd ) return proc.wait() def run_script_with_context(script_path, cwd, context):
def run_script(script_path, cwd='.'): shell=run_thru_shell, cwd=cwd ) exit_status = proc.wait() if exit_status != EXIT_SUCCESS: raise FailedHookException( "Hook script failed (exit status: %d)" % exit_status) def run_script_with_context(script_path, cwd, context):
def run_script_with_context(script_path, cwd, context): ) as temp: temp.write(Template(contents).render(**context)) return run_script(temp.name, cwd) def run_hook(hook_name, project_dir, context):
def run_script_with_context(script_path, cwd, context): ) as temp: temp.write(Template(contents).render(**context)) run_script(temp.name, cwd) def run_hook(hook_name, project_dir, context):
def run_hook(hook_name, project_dir, context): script = find_hooks().get(hook_name) if script is None: logging.debug('No hooks found') return EXIT_SUCCESS return run_script_with_context(script, project_dir, context)
def run_hook(hook_name, project_dir, context): script = find_hooks().get(hook_name) if script is None: logging.debug('No hooks found') return run_script_with_context(script, project_dir, context)
Tests for `cookiecutter.hooks` module. import sys import os import stat from cookiecutter import hooks, utils def make_test_repo(name):
Tests for `cookiecutter.hooks` module. import sys import os import stat import pytest from cookiecutter import hooks, utils, exceptions def make_test_repo(name):
class TestExternalHooks(object): hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt'))
class TestExternalHooks(object): hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'shell_post.txt')) def test_run_failing_hook(self): hook_path = os.path.join(self.hooks_path, 'pre_gen_project.py') tests_dir = os.path.join(self...
def _read_file(filename): package_dir={'': 'src'}, python_requires='>= 3.6', install_requires=[ 'AccessControl >= 4.2', 'Acquisition', 'BTrees', 'Chameleon >= 3.7.0',
def _read_file(filename): package_dir={'': 'src'}, python_requires='>= 3.6', install_requires=[ 'AccessControl >= 5.2', 'Acquisition', 'BTrees', 'Chameleon >= 3.7.0',
import errno import grp import os import platform import pwd import shutil import socket import time import re from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
import errno import grp import os import platform import pty import pwd import select import shutil import socket import subprocess import time import re from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils.basic import load_platform_subclass, AnsibleModule try:
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) cmd.append('-N') if self.ssh_passphrase is not None: cmd.append(self.ssh_passphrase) else: cmd.append('') (rc, out, err) = self.execute_command(cmd)...
class User(object): cmd.append(self.ssh_comment) cmd.append('-f') cmd.append(ssh_key_file) if self.ssh_passphrase is not None: if self.module.check_mode: self.module.debug('In check mode, would have run: "%s"' % cmd) return (0, '', '') ...
Tests for L{twisted.web.twcgi}. """ import sys import os import json from io import BytesIO from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import cl...
Tests for L{twisted.web.twcgi}. """ import sys, os from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, resource from twisted...
print print "cgi output" ''' HEADER_OUTPUT_CGI = '''\ import json import os print("") print("") vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")} print(json.dumps(vals)) ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
print print "cgi output" ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
class CGITests(unittest.TestCase): return factory.deferred def test_noProxyPassthrough(self): """ The CGI script is never called with the Proxy header passed through. """ cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI) portnum = self.startServer(cgiFilename) ...
class CGITests(unittest.TestCase): return factory.deferred def test_duplicateHeaderCGI(self): """ If a CGI script emits two instances of the same header, both are sent in
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length', 'proxy'): envname = "HTTP_" + envname env[en...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length'): envname = "HTTP_" + envname env[envname] = ...
except ImportError: from ordereddict import OrderedDict from luigi import six class TaskClassException(Exception):
except ImportError: from ordereddict import OrderedDict from luigi import six import logging logger = logging.getLogger('luigi-interface') class TaskClassException(Exception):
from helpers import unittest import luigi import luigi.date_interval import luigi.notifications
from helpers import unittest import luigi import luigi.worker import luigi.date_interval import luigi.notifications
class InstanceTest(unittest.TestCase): self.assertNotEqual(dummy_1, dummy_2) self.assertEqual(dummy_1, dummy_1b) if __name__ == '__main__': unittest.main()
class InstanceTest(unittest.TestCase): self.assertNotEqual(dummy_1, dummy_2) self.assertEqual(dummy_1, dummy_1b) def test_unhashable_type(self): # See #857 class DummyTask(luigi.Task): x = luigi.Parameter() dummy = DummyTask(x={}) if __name__ == '__main__': ...
class AsyncHTTPClient(Configurable): return self._closed = True if self._instance_cache is not None: if self._instance_cache.get(self.io_loop) is not self: raise RuntimeError("inconsistent AsyncHTTPClient cache") del self._instance_cache[self.io_loop] ...
class AsyncHTTPClient(Configurable): return self._closed = True if self._instance_cache is not None: cached_val = self._instance_cache.pop(self.io_loop, None) # If there's an object other than self in the instance # cache for our IOLoop, something has gott...
import copy import threading import datetime from io import BytesIO import time import typing # noqa: F401 import unicodedata import unittest from tornado.escape import utf8, native_str from tornado import gen from tornado.httpclient import ( HTTPRequest,
import copy import threading import datetime from io import BytesIO import subprocess import sys import time import typing # noqa: F401 import unicodedata import unittest from tornado.escape import utf8, native_str, to_unicode from tornado import gen from tornado.httpclient import ( HTTPRequest,
class SyncHTTPClientTest(unittest.TestCase): self.assertEqual(assertion.exception.code, 404) class HTTPRequestTestCase(unittest.TestCase): def test_headers(self): request = HTTPRequest("http://example.com", headers={"foo": "bar"})
class SyncHTTPClientTest(unittest.TestCase): self.assertEqual(assertion.exception.code, 404) class SyncHTTPClientSubprocessTest(unittest.TestCase): def test_destructor_log(self): # Regression test for # https://github.com/tornadoweb/tornado/issues/2539 # # In the past, the ...
import ctypes import datetime as dt import decimal import io
import datetime as dt import decimal import io
def test_encode_surrogate_characters(): assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2 @pytest.mark.xfail( hasattr(sys, "pypy_version_info") and os.name == "nt", reason="This feature needs fixing! See #552", ) @pytest.mark.parametrize( "test_input, expected", ...
def test_encode_surrogate_characters(): assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2 @pytest.mark.parametrize( "test_input, expected", [
def test_encode_surrogate_characters(): ], ) def test_decode_surrogate_characters(test_input, expected): # FIXME Wrong output (combined char) on platforms with 16-bit wchar_t if test_input == '"\uD83D\uDCA9"' and ctypes.sizeof(ctypes.c_wchar) == 2: pytest.skip("Raw surrogate pairs are not supported ...
def test_encode_surrogate_characters(): ], ) def test_decode_surrogate_characters(test_input, expected): assert ujson.loads(test_input) == expected assert ujson.loads(test_input.encode("utf-8", "surrogatepass")) == expected
def dispatch_to_series(left, right, func, str_rep=None, axis=None): # in which case we specifically want to operate row-by-row assert right.index.equals(left.columns) def column_op(a, b): return {i: func(a.iloc[:, i], b.iloc[i]) for i in range(len(a.columns))} elif isinstance(r...
def dispatch_to_series(left, right, func, str_rep=None, axis=None): # in which case we specifically want to operate row-by-row assert right.index.equals(left.columns) if right.dtype == "timedelta64[ns]": # ensure we treat NaT values as the correct dtype # Note: we do not...
class TestFrameFlexArithmetic: class TestFrameArithmetic: def test_df_add_2d_array_rowlike_broadcasts(self): # GH#23000 arr = np.arange(6).reshape(3, 2)
class TestFrameFlexArithmetic: class TestFrameArithmetic: def test_td64_op_nat_casting(self): # Make sure we don't accidentally treat timedelta64(NaT) as datetime64 # when calling dispatch_to_series in DataFrame arithmetic ser = pd.Series(["NaT", "NaT"], dtype="timedelta64[ns]") d...
def get_next_comment(): def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. m = re.search(r'((\r\n|\r|\n)+) *$', token.value) if m is not None: return sq...
def get_next_comment(): def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. # Note: The actual value for a line break is replaced by \n # in SerializerUnicode which will...
def test_strip_comments_multi(self): res = sqlparse.format(sql, strip_comments=True) assert res == 'select (select 2)' def test_strip_ws(self): f = lambda sql: sqlparse.format(sql, strip_whitespace=True) s = 'select\n* from foo\n\twhere ( 1 = 2 )\n'
def test_strip_comments_multi(self): res = sqlparse.format(sql, strip_comments=True) assert res == 'select (select 2)' def test_strip_comments_preserves_linebreak(self): sql = 'select * -- a comment\r\nfrom foo' res = sqlparse.format(sql, strip_comments=True) assert res == '...
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat(frames, axis=1, join="outer", verify_integrity=True) return res.reindex(self.index, copy=False) else: ...
class DataFrame(NDFrame): # join indexes only using concat if can_concat: if how == "left": res = concat( frames, axis=1, join="outer", verify_integrity=True, sort=sort ) return res.reindex(self.i...
def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected)
def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected) @pytest.mark.parametrize("sort_kw", [True, False, None]) def test_suppress_future_warning_with_sort_kw(sort_kw): a = DataFrame({"col1": [1, 2]}, index=["c", "a"]) b = DataFrame({"col2": [4, 5]}, index=["b", "a"...
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb')) # When a variable_name key is specified for th...
def load_inputs_from_input_arg_string(inputs_str, input_exprs_str, input_examples = preprocess_input_examples_arg_string(input_examples_str) for input_tensor_key, (filename, variable_name) in inputs.items(): data = np.load(file_io.FileIO(filename, mode='rb'), allow_pickle=True) # When a variable_name key ...
} def reset_format_cache(): """Clear any cached formats.
} FORMAT_SETTINGS = frozenset([ 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'FIRST_DAY_OF_WEEK', 'MONTH_DAY_FORMAT', 'TIME_FORMAT', 'DATE_FORMAT', 'DATETIME_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'YEAR_MONTH_FORMAT', 'DATE_INPUT_FORMATS...
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language()
def get_format(format_type, lang=None, use_l10n=None): be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if format_type not in FORMAT_SETTINGS: return format_type if use_l10n or (use_l10n is None and settings.USE_L10N): if lang...
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) class MiscTests(SimpleTestCase):
def test_localized_as_text_as_hidden_input(self): '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47" />' ) def test_format_arbitrary_settings(self): self.assertEqual(get_format('DEBUG'), 'DEBUG') class MiscTests(SimpleTestCase):
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import exec_command from ansible.module_utils.network.ios.ios import load_config from ansible.module_utils.network.ios.ios import ios_argument_spec import re def map_obj_to_commands(updates, module):
commands: - string """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.ios.ios import get_config, load_config from ansible.module_utils.network.ios.ios import ios_argument_spec from re import search, M def map_obj_to_commands(updates, module):
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip() banner_cmd += '\n@' commands.append(banner_cmd)...
def map_obj_to_commands(updates, module): if want['text'] and (want['text'] != have.get('text')): banner_cmd = 'banner %s' % module.params['banner'] banner_cmd += ' @\n' banner_cmd += want['text'].strip('\n') banner_cmd += '\n@' commands.append(banner_...
def map_obj_to_commands(updates, module): def map_config_to_obj(module): rc, out, err = exec_command(module, 'show banner %s' % module.params['banner']) if rc == 0: output = out else: rc, out, err = exec_command(module, 'show running-config | begin banne...
def map_obj_to_commands(updates, module): def map_config_to_obj(module): """ This function gets the banner config without stripping any whitespaces, and then fetches the required banner from it. :param module: :return: banner config dict object. """ out = get_config(module, flags='| begin ...
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] if text: text = str(text).strip() return { 'banner': module.params['banner'], 'text': text,
def map_config_to_obj(module): def map_params_to_obj(module): text = module.params['text'] return { 'banner': module.params['banner'], 'text': text,
class TestIosBannerModule(TestIosModule): def setUp(self): super(TestIosBannerModule, self).setUp() self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command') self.exec_command = self.mock_exec_command.start() self.mock_load_config = patch('ansible.module...
class TestIosBannerModule(TestIosModule): def setUp(self): super(TestIosBannerModule, self).setUp() self.mock_get_config = patch('ansible.modules.network.ios.ios_banner.get_config') self.get_config = self.mock_get_config.start() self.mock_load_config = patch('ansible.modules.networ...
class TestIosBannerModule(TestIosModule): self.execute_module(changed=True, commands=commands) def test_ios_banner_nochange(self): banner_text = load_fixture('ios_banner_show_banner.txt').strip() set_module_args(dict(banner='login', text=banner_text)) self.execute_module() class T...
class TestIosBannerModule(TestIosModule): self.execute_module(changed=True, commands=commands) def test_ios_banner_nochange(self): banner_text = load_fixture('ios_banner_show_banner.txt') set_module_args(dict(banner='login', text=banner_text)) self.execute_module() class TestIosBa...
def _cat_compare_op(op): mask = (self._codes == -1) | (other_codes == -1) if mask.any(): # In other series, the leads to False, so do that here too ret[mask] = False return ret if is_scalar(other):
def _cat_compare_op(op): mask = (self._codes == -1) | (other_codes == -1) if mask.any(): # In other series, the leads to False, so do that here too if opname == "__ne__": ret[(self._codes == -1) & (other_codes == -1)] = True els...
class TestComparisonOps(base.BaseComparisonOpsTests): with pytest.raises(TypeError, match=msg): op(data, other) class TestParsing(base.BaseParsingTests): pass
class TestComparisonOps(base.BaseComparisonOpsTests): with pytest.raises(TypeError, match=msg): op(data, other) @pytest.mark.parametrize( "categories", [["a", "b"], [0, 1], [pd.Timestamp("2019"), pd.Timestamp("2020")]], ) def test_not_equal_with_na(self, categori...
class AdminReadonlyField: except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if f is None: if getattr(attr, 'boolean', False): result_repr = _boolean_icon(value)
class AdminReadonlyField: except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = self.empty_value_display else: if field in self.form.fields: widget = self.form[field].field.widget # This isn't elegant but suffices for contrib.auth'...
UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs)
UserModel = get_user_model() class ReadOnlyPasswordHashWidget(forms.Widget): template_name = 'auth/widgets/read_only_password_hash.html' read_only = True def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs)
from django.contrib.auth import ( from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import User from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login, redirect_to_login, ) from djang...
from django.contrib.auth import ( from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, SetPasswordForm, ) from django.contrib.auth.models import Permission, User from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, LoginView, logout_then_login, redirect_to_login, ...
class LogoutTest(AuthViewsTestCase): self.assertRedirects(response, '/logout/', fetch_redirect_response=False) # Redirect in test_user_change_password will fail if session auth hash # isn't updated after password change (#21649) @override_settings(ROOT_URLCONF='auth_tests.urls_admin')
class LogoutTest(AuthViewsTestCase): self.assertRedirects(response, '/logout/', fetch_redirect_response=False) def get_perm(Model, perm): ct = ContentType.objects.get_for_model(Model) return Permission.objects.get(content_type=ct, codename=perm) # Redirect in test_user_change_password will fail if s...
class ChangelistTests(AuthViewsTestCase): (_request, user), _kwargs = has_change_permission.call_args self.assertEqual(user.pk, self.admin.pk) @override_settings( AUTH_USER_MODEL='auth_tests.UUIDUser',
class ChangelistTests(AuthViewsTestCase): (_request, user), _kwargs = has_change_permission.call_args self.assertEqual(user.pk, self.admin.pk) def test_view_user_password_is_readonly(self): u = User.objects.get(username='testclient') u.is_superuser = False u.save() u...
# this is a package __version__ = "4.6.4" def get_include():
# this is a package __version__ = "4.6.5" def get_include():
from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import notna from pandas.core.arrays import Categorical from pandas.core.frame import DataFrame, _shared_docs from pandas.core.indexes.base import Index from pandas.core.reshape.concat import concat
from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import notna from pandas.core.arrays import Categorical import pandas.core.common as com from pandas.core.frame import DataFrame, _shared_docs from pandas.core.indexes.base import Index from pandas.core.reshape.concat import concat
def melt( else: # Check that `id_vars` are in frame id_vars = list(id_vars) missing = Index(np.ravel(id_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'id_vars' are not present"
def melt( else: # Check that `id_vars` are in frame id_vars = list(id_vars) missing = Index(com.flatten(id_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'id_vars' are not present"
def melt( else: value_vars = list(value_vars) # Check that `value_vars` are in frame missing = Index(np.ravel(value_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'value_vars' are not present in"
def melt( else: value_vars = list(value_vars) # Check that `value_vars` are in frame missing = Index(com.flatten(value_vars)).difference(cols) if not missing.empty: raise KeyError( "The following 'value_vars' are not present in"
class TestMelt: ): multi.melt(["A"], ["F"], col_level=0) class TestLreshape: def test_pairs(self):
class TestMelt: ): multi.melt(["A"], ["F"], col_level=0) def test_melt_mixed_int_str_id_vars(self): # GH 29718 df = DataFrame({0: ["foo"], "a": ["bar"], "b": [1], "d": [2]}) result = melt(df, id_vars=[0, "a"], value_vars=["b", "d"]) expected = DataFrame( ...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id"), object.pop("$db", None), object), position) ...
def _get_object(data, position, as_class, tz_aware, uuid_subtype): object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id", None), object.pop("$db", None), object), positi...
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
from bson.binary import Binary, UUIDLegacy, OLD_UUID_SUBTYPE, UUID_SUBTYPE from bson.code import Code from bson.dbref import DBRef from bson.objectid import ObjectId from bson.py3compat import b from bson.son import SON
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_as_class(self): c = self.db.test c.drop()
def test_bad_encode(self): self.assertRaises(InvalidDocument, c.save, {"x": c}) warnings.simplefilter("default") def test_bad_dbref(self): c = self.db.test c.drop() # Incomplete DBRefs. self.assertRaises( InvalidDocument, c.insert, {'ref': {'...
class RangeIndex(Int64Index): if self.step > 0: start, stop, step = self.start, self.stop, self.step else: # Work on reversed range for simplicity: start, stop, step = (self.stop - self.step, self.start + 1, -self.step) target_array = np.asarray(target) ...
class RangeIndex(Int64Index): if self.step > 0: start, stop, step = self.start, self.stop, self.step else: # GH 28678: work on reversed range for simplicity reverse = self._range[::-1] start, stop, step = reverse.start, reverse.stop, reverse.step ...
class TestRangeIndex(Numeric): expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) def test_join_outer(self): # join with Int64Index other = Int64Index(np.arange(25, 14, -1))
class TestRangeIndex(Numeric): expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("stop", [0, -1, -2]) def test_get_indexer_decreasing(self, stop): # GH 28678 index = RangeIndex(7, stop, -3) resu...
def _recursively_freeze(value): """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list): return tuple(_recursively_freeze(v) for v in value) return value class DictParameter(Parameter): """ ...
def _recursively_freeze(value): """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list) or isinstance(value, tuple): return tuple(_recursively_freeze(v) for v in value) return value class _DictPa...
class DictParameter(Parameter): tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related values (like a database connection config). """ class _DictParamEncoder(JSONEncoder): """ JSON encoder for :py:class:`~DictParameter`, whic...
class DictParameter(Parameter): tags, that are dynamically constructed outside Luigi), or you have a complex parameter containing logically related values (like a database connection config). """ def normalize(self, value): """ Ensure that dictionary parameter is converted to a _FrozenOr...
class DictParameter(Parameter): return json.loads(s, object_pairs_hook=_FrozenOrderedDict) def serialize(self, x): return json.dumps(x, cls=DictParameter._DictParamEncoder) class ListParameter(Parameter):
class DictParameter(Parameter): return json.loads(s, object_pairs_hook=_FrozenOrderedDict) def serialize(self, x): return json.dumps(x, cls=_DictParamEncoder) class ListParameter(Parameter):
class ListParameter(Parameter): """ def normalize(self, x): """ Ensure that list parameter is converted to a tuple so it can be hashed. :param str x: the value to parse. :return: the normalized (hashable/immutable) value.
class ListParameter(Parameter): """ def normalize(self, x): """ Ensure that struct is recursively converted to a tuple so it can be hashed. :param str x: the value to parse. :return: the normalized (hashable/immutable) value.
class ListParameter(Parameter): :param str x: the value to parse. :return: the parsed value. """ return list(json.loads(x)) def serialize(self, x): """
class ListParameter(Parameter): :param str x: the value to parse. :return: the parsed value. """ return list(json.loads(x, object_pairs_hook=_FrozenOrderedDict)) def serialize(self, x): """
class ListParameter(Parameter): :param x: the value to serialize. """ return json.dumps(x) class TupleParameter(Parameter): """ Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
class ListParameter(Parameter): :param x: the value to serialize. """ return json.dumps(x, cls=_DictParamEncoder) class TupleParameter(ListParameter): """ Parameter whose value is a ``tuple`` or ``tuple`` of tuples.
class TupleParameter(Parameter): $ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))' """ def parse(self, x): """ Parse an individual value from the input.
class TupleParameter(Parameter): $ luigi --module my_tasks MyTask --book_locations '((12,3),(4,15),(52,1))' """ def parse(self, x): """ Parse an individual value from the input.
class TupleParameter(Parameter): # Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x). # ast.literal_eval(t_str) == t try: return tuple(tuple(x) for x in json.loads(x)) # loop required to parse tuple of tuples except ValueError: return lite...
class TupleParameter(Parameter): # Therefore, if json.loads(x) returns a ValueError, try ast.literal_eval(x). # ast.literal_eval(t_str) == t try: # loop required to parse tuple of tuples return tuple(tuple(x) for x in json.loads(x, object_pairs_hook=_FrozenOrderedDict)) ...
class TestParametersHashability(LuigiTestCase): p = luigi.parameter.ListParameter() self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]')))) def test_tuple(self): class Foo(luigi.Task): args = luigi.parameter.TupleParameter()
class TestParametersHashability(LuigiTestCase): p = luigi.parameter.ListParameter() self.assertEqual(hash(Foo(args=[1, "hello"]).args), hash(p.normalize(p.parse('[1,"hello"]')))) def test_list_dict(self): class Foo(luigi.Task): args = luigi.parameter.ListParameter() p =...
class TestParametersHashability(LuigiTestCase): p = luigi.parameter.TupleParameter() self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")'))) def test_task(self): class Bar(luigi.Task): pass
class TestParametersHashability(LuigiTestCase): p = luigi.parameter.TupleParameter() self.assertEqual(hash(Foo(args=(1, "hello")).args), hash(p.parse('(1,"hello")'))) def test_tuple_dict(self): class Foo(luigi.Task): args = luigi.parameter.TupleParameter() p = luigi.par...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode() except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_brok...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exceptio...
import datetime import unittest from unittest import mock from urllib.parse import quote_plus
import datetime import sys import unittest from unittest import mock from urllib.parse import quote_plus
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_str, get_system_encoding, iri_to_uri, smart_bytes, smart_str, uri_to_iri, ) from django.utils.functional import Simple...
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_str, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_str, uri_to_iri, ) from django.util...
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested ...
class TestUtil(unittest.TestCase): self.assertEqual(unified_timestamp('25-09-2014'), 1411603200) self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200) self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None) def test_determine_ext(self): self.assertEqual(determ...
class TestUtil(unittest.TestCase): self.assertEqual(unified_timestamp('25-09-2014'), 1411603200) self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200) self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None) self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'...
def unified_timestamp(date_str, day_first=True): date_str = date_str.replace(',', ' ') pm_delta = datetime.timedelta(hours=12 if re.search(r'(?i)PM', date_str) else 0) timezone, date_str = extract_timezone(date_str) # Remove AM/PM + timezone
def unified_timestamp(date_str, day_first=True): date_str = date_str.replace(',', ' ') pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0 timezone, date_str = extract_timezone(date_str) # Remove AM/PM + timezone
def unified_timestamp(date_str, day_first=True): for expression in date_formats(day_first): try: dt = datetime.datetime.strptime(date_str, expression) - timezone + pm_delta return calendar.timegm(dt.timetuple()) except ValueError: pass timetuple = email.utils...
def unified_timestamp(date_str, day_first=True): for expression in date_formats(day_first): try: dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta) return calendar.timegm(dt.timetuple()) except ValueError: pass ...
class DistributionFiles: elif 'SteamOS' in data: debian_facts['distribution'] = 'SteamOS' # nothing else to do, SteamOS gets correct info from python functions elif path == '/etc/lsb-release' and 'Kali' in data: debian_facts['distribution'] = 'Kali' releas...
class DistributionFiles: elif 'SteamOS' in data: debian_facts['distribution'] = 'SteamOS' # nothing else to do, SteamOS gets correct info from python functions elif path in ('/etc/lsb-release', '/etc/os-release') and 'Kali' in data: # Kali does not provide /etc/lsb-re...
TESTSETS = [ 'os_family': 'Debian' } }, { "platform.dist": [ "neon",
TESTSETS = [ 'os_family': 'Debian' } }, { 'name': 'Kali 2020.2', 'input': { '/etc/os-release': ("PRETTY_NAME=\"Kali GNU/Linux Rolling\"\nNAME=\"Kali GNU/Linux\"\nID=kali\nVERSION=\"2020.2\"\n" "VERSION_ID=\"2020.2\"\nVERSION_CODENAM...
def page(self, title, contents): %s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div> </body></html>''' % (title, css_link, html_navbar(), contents) def filelink(self, url, path): return '<a href="getfile?key=%s">%s</a>' % (url, path) html = _HTMLDoc()
def page(self, title, contents): %s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div> </body></html>''' % (title, css_link, html_navbar(), contents) html = _HTMLDoc()