buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestSeriesGetitemSlices: class TestSeriesGetitemListLike: def test_getitem_intlist_intindex_periodvalues(self): ser = Series(period_range("2000-01-01", periods=10, freq="D"))
class TestSeriesGetitemSlices: class TestSeriesGetitemListLike: @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series]) def test_getitem_no_matches(self, box): # GH#33462 we expect the same behavior for list/ndarray/Index/Series ser = Series(["A", "B"]) key = Series(["C...
from .helper import on_ci @pytest.mark.parametrize( "test_file", ["Tests/images/crash_1.tif", "Tests/images/crash_2.tif"] ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Metadata warning")
from .helper import on_ci @pytest.mark.parametrize( "test_file", [ "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Metadata warni...
def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde for hlevel, level in zip(zipped, levels): to_concat = [] for key, index in zip(hlevel, indexes): try: i = level.get_loc(key) except KeyError as err: ...
def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde for hlevel, level in zip(zipped, levels): to_concat = [] for key, index in zip(hlevel, indexes): mask = level == key if not mask.any(): raise ValueError(f"...
def test_concat_multiindex_datetime_object_index(): ) result = concat([s, s2], axis=1) tm.assert_frame_equal(result, expected)
def test_concat_multiindex_datetime_object_index(): ) result = concat([s, s2], axis=1) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]]) def test_duplicate_keys(keys): # GH 33654 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) s1 = Se...
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...
Tests for L{twisted.web.twcgi}. """ import sys import os import json 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, res...
print print "cgi output" ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
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
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 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 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] = ...
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 Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a minimum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): min : the minimum of this `Categorical` """ self.check_for_ordered("min") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): Only ordered `Categoricals` have a maximum! .. versionchanged:: 1.0.0 Returns an NA value on empty arrays Raises ------ TypeError
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") good = self._codes != -1 if not good.all(): if skipna:
class Categorical(ExtensionArray, PandasObject): max : the maximum of this `Categorical` """ self.check_for_ordered("max") if not len(self._codes): return self.dtype.na_value good = self._codes != -1 if not good.all(): if skipna:
import pytest from pandas.compat import PYPY from pandas import Categorical, Index, Series from pandas.api.types import is_scalar import pandas.util.testing as tm class TestCategoricalAnalytics: def test_min_max(self): # unordered cats have no min/max cat = Categorical(["a", "b", "c", "d"], ord...
import pytest from pandas.compat import PYPY from pandas import Categorical, Index, NaT, Series, date_range from pandas.api.types import is_scalar import pandas.util.testing as tm class TestCategoricalAnalytics: @pytest.mark.parametrize("aggregation", ["min", "max"]) def test_min_max_not_ordered_raises(self...
class TestCategoricalAnalytics: assert _min == "d" assert _max == "a" @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_with_nan(self, skipna): # GH 25303
class TestCategoricalAnalytics: assert _min == "d" assert _max == "a" @pytest.mark.parametrize( "categories,expected", [ (list("ABC"), np.NaN), ([1, 2, 3], np.NaN), pytest.param( Series(date_range("2020-01-01", periods=3), dtype="c...
class Categorical(ExtensionArray, PandasObject): ) raise ValueError(msg) codes = np.asarray(codes) # #21767 if len(codes) and not is_integer_dtype(codes): raise ValueError("codes need to be array-like integers")
class Categorical(ExtensionArray, PandasObject): ) raise ValueError(msg) if is_extension_array_dtype(codes) and is_integer_dtype(codes): # Avoid the implicit conversion of Int to object if isna(codes).any(): raise ValueError("codes cannot contain ...
class TestCategoricalConstructors: with pytest.raises(ValueError, match=msg): Categorical.from_codes([0, 1]) @pytest.mark.parametrize("dtype", [None, "category"]) def test_from_inferred_categories(self, dtype): cats = ["a", "b"]
class TestCategoricalConstructors: with pytest.raises(ValueError, match=msg): Categorical.from_codes([0, 1]) def test_from_codes_with_nullable_int(self): codes = pd.array([0, 1], dtype="Int64") categories = ["a", "b"] result = Categorical.from_codes(codes, categories=ca...
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...
def do_client_test(options, conn): For example to delete the client XYZ in the realm ABC: {prog_name} -s http://example.com:8080 -p password client delete -r ABC -c XYZ where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are arguments to the delete action.
def do_client_test(options, conn): For example to delete the client XYZ in the realm ABC: echo password | {prog_name} -s http://example.com:8080 -P - client delete -r ABC -c XYZ where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are arguments to the delete action.
def main(): default='admin', help='admin user name (default: admin)') group.add_argument('-p', '--admin-password', required=True, help='admin password') group.add_argument('--admin-realm', defaul...
def main(): default='admin', help='admin user name (default: admin)') group.add_argument('-P', '--admin-password-file', type=argparse.FileType('rb'), help=('file containing admin password ' '(or...
def main(): if options.permit_insecure_transport: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' try: anonymous_conn = KeycloakAnonymousConnection(options.server, options.tls_verify)
def main(): if options.permit_insecure_transport: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # Get admin password options.admin_password = None # 1. Try password file if options.admin_password_file is not None: options.admin_password = options.keycloak_admin_password_file.read...
def text_to_word_sequence(text, if lower: text = text.lower() if sys.version_info < (3,) and isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) else: translate_map = maketrans(filters, split * len(filters)) text = text.translate(translate...
def text_to_word_sequence(text, if lower: text = text.lower() if sys.version_info < (3,): if isinstance(text, unicode): translate_map = dict((ord(c), unicode(split)) for c in filters) text = text.translate(translate_map) elif len(split) == 1: translat...
def test_text_to_word_sequence(): assert text_to_word_sequence(text) == ['hello', 'world'] def test_text_to_word_sequence_unicode(): text = u'ali! veli? kırk dokuz elli' assert text_to_word_sequence(text) == [u'ali', u'veli', u'kırk', u'dokuz', u'elli'] def test_tokenizer_unicode(): texts = [u'ali v...
def test_text_to_word_sequence(): assert text_to_word_sequence(text) == ['hello', 'world'] def test_text_to_word_sequence_multichar_split(): text = 'hello!stop?world!' assert text_to_word_sequence(text, split='stop') == ['hello', 'world'] def test_text_to_word_sequence_unicode(): text = u'ali! veli?...
def setup_remote_pydev_debug(): except: LOG.exception(_(error_msg)) raise
def setup_remote_pydev_debug(): except: LOG.exception(_(error_msg)) raise class LimitingReader(object): """Reader to limit the size of an incoming request.""" def __init__(self, data, limit): """ :param data: Underlying data object :param limit: maximum ...
def register_cli_int(*args, **kw): register_str('auth_admin_prefix', default='') register_str('policy_file', default='policy.json') register_str('policy_default_rule', default=None) #ssl options register_bool('enable', group='ssl', default=False)
def register_cli_int(*args, **kw): register_str('auth_admin_prefix', default='') register_str('policy_file', default='policy.json') register_str('policy_default_rule', default=None) #default max request size is 112k register_int('max_request_body_size', default=114688) #ssl options register_bool('enable', group='ssl',...
class Conflict(Error): title = 'Conflict' class UnexpectedError(Error): """An unexpected error prevented the server from fulfilling your request.
class Conflict(Error): title = 'Conflict' class RequestTooLarge(Error): """Request is too large.""" code = 413 title = 'Request is too large.' class UnexpectedError(Error): """An unexpected error prevented the server from fulfilling your request.
# License for the specific language governing permissions and limitations # under the License. from keystone.common import serializer from keystone.common import wsgi from keystone import config from keystone import exception
# License for the specific language governing permissions and limitations # under the License. import webob.dec from keystone.common import serializer from keystone.common import utils from keystone.common import wsgi from keystone import config from keystone import exception
def process_request(self, request): # Rewrites path to root if no path is given. elif not request.environ['PATH_INFO']: request.environ['PATH_INFO'] = '/'
def process_request(self, request): # Rewrites path to root if no path is given. elif not request.environ['PATH_INFO']: request.environ['PATH_INFO'] = '/' class RequestBodySizeLimiter(wsgi.Middleware): """Limit the size of an incoming request.""" def __init__(self, *args, **kwargs...
class FileBasedCache(BaseCache): self._delete(fname) def _createdir(self): os.makedirs(self._dir, 0o700, exist_ok=True) def _key_to_file(self, key, version=None): """
class FileBasedCache(BaseCache): self._delete(fname) def _createdir(self): # Set the umask because os.makedirs() doesn't apply the "mode" argument # to intermediate-level directories. old_umask = os.umask(0o077) try: os.makedirs(self._dir, 0o700, exist_ok=Tru...
import os import pickle import re import shutil import tempfile import threading import time import unittest from pathlib import Path from unittest import mock from django.conf import settings from django.core import management, signals
import os import pickle import re import shutil import sys import tempfile import threading import time import unittest from pathlib import Path from unittest import mock, skipIf from django.conf import settings from django.core import management, signals
class FileBasedCacheTests(BaseCacheTests, TestCase): # Returns the default instead of erroring. self.assertEqual(cache.get('foo', 'baz'), 'baz') def test_get_does_not_ignore_non_filenotfound_exceptions(self): with mock.patch('builtins.open', side_effect=OSError): with self.asser...
class FileBasedCacheTests(BaseCacheTests, TestCase): # Returns the default instead of erroring. self.assertEqual(cache.get('foo', 'baz'), 'baz') @skipIf( sys.platform == 'win32', 'Windows only partially supports umasks and chmod.', ) def test_cache_dir_permissions(self): ...
import logging from six.moves.urllib.parse import urljoin from scrapy.http import HtmlResponse from scrapy.utils.response import get_meta_refresh from scrapy.utils.python import to_native_str from scrapy.exceptions import IgnoreRequest, NotConfigured logger = logging.getLogger(__name__)
import logging from six.moves.urllib.parse import urljoin from w3lib.url import safe_url_string from scrapy.http import HtmlResponse from scrapy.utils.response import get_meta_refresh from scrapy.exceptions import IgnoreRequest, NotConfigured logger = logging.getLogger(__name__)
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response # HTTP header is ascii or latin1, redirected url will be percent-encoded utf-8 location = to_native_str(response.headers['location'].deco...
class RedirectMiddleware(BaseRedirectMiddleware): if 'Location' not in response.headers or response.status not in allowed_status: return response location = safe_url_string(response.headers['location']) redirected_url = urljoin(request.url, location)
class RedirectMiddlewareTest(unittest.TestCase): latin1_location = u'/ação'.encode('latin1') # HTTP historically supports latin1 resp = Response('http://scrapytest.org/first', headers={'Location': latin1_location}, status=302) req_result = self.mw.process_response(req, resp, self.spider) ...
class RedirectMiddlewareTest(unittest.TestCase): latin1_location = u'/ação'.encode('latin1') # HTTP historically supports latin1 resp = Response('http://scrapytest.org/first', headers={'Location': latin1_location}, status=302) req_result = self.mw.process_response(req, resp, self.spider) ...
from django.contrib.postgres.fields import JSONField from django.db.models.aggregates import Aggregate __all__ = [
from django.contrib.postgres.fields import JSONField from django.db.models import Value from django.db.models.aggregates import Aggregate __all__ = [
class JSONBAgg(Aggregate): class StringAgg(Aggregate): function = 'STRING_AGG' template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s')" def __init__(self, expression, delimiter, distinct=False, **extra): distinct = 'DISTINCT ' if distinct else '' super(StringAgg, self).__ini...
class JSONBAgg(Aggregate): class StringAgg(Aggregate): function = 'STRING_AGG' template = '%(function)s(%(distinct)s%(expressions)s)' def __init__(self, expression, delimiter, distinct=False, **extra): distinct = 'DISTINCT ' if distinct else '' delimiter_expr = Value(str(delimiter)) ...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi...
from PIL import Image "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", ], ) def test_crashes(test_file):
from PIL import Image "Tests/images/sgi_crash.bin", "Tests/images/crash-6b7f2244da6d0ae297ee0754a424213444e92778.sgi", "Tests/images/ossfuzz-5730089102868480.sgi", "Tests/images/crash-754d9c7ec485ffb76a90eeaab191ef69a2a3a3cd.sgi", "Tests/images/crash-465703f71a0f0094873a3e0e82c9f...
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: is_fmt_on = False for comment in list_comments(container.prefix, is_endmarker=False): if comment.value in FM...
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: if fmt_on(container): return # fix for fmt: on in children if contains_fmt_on_at_column(container, ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_paren...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff4(self) -> None: source, expected = read_data("fmtonoff4") actual = fs(source) ...
def test_colorbar_label(): cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar') assert cbar3.ax.get_xlabel() == 'horizontal cbar'
def test_colorbar_label(): cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar') assert cbar3.ax.get_xlabel() == 'horizontal cbar' @pytest.mark.parametrize("clim", [(-20000, 20000), (-32768, 0)]) def test_colorbar_int(clim): # Check that we cast to float early enough to not # ov...
def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): vmin, vmax = vmax, vmin swapped = True maxabsvalue = max(abs(vmin), abs(vmax)) if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny: vmin = -expander
def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True): vmin, vmax = vmax, vmin swapped = True # Expand vmin, vmax to float: if they were integer types, they can wrap # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow. vmin, vmax = map(float, [vmin, ...
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return str(name).replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') @unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.') def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied."""
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
else: def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, http_cookies.BaseCookie): try: c = SimpleCookie() c.load(cookie) except http_cookies.CookieError: # Invalid cookie return {} else: c = cookie...
else: def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} if six.PY2: cookie = force_str(cookie) for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: ...
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
from django.http import ( from django.test import SimpleTestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_str, force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_httponly_after_load(self): """ Test that we can use httponly attribute on cookies that we load
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_python_cookies(self): """ Test cases copied from Python's Lib/test/test_http_cookies.py """ self.assertEqual(parse_cookie('chips=ahoy; ...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, parse_cookie, ) from django.test import RequestFactory, SimpleTestCase, override_settings from d...
from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import ( HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError, ) from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client ...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_parse_cookie(self): self.assertEqual(parse_cookie('invalid@key=true'), {}) def test_httpr...
class RequestsTests(SimpleTestCase): request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") def test_httprequest_location(self): request = HttpRequest() self.assertEqual(request.build_abs...
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile: raise Impossible() obj = self.node.as_const(eval_ctx)
class Call(Expr): def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile or eval_ctx.environment.sandboxed: raise Impossible() obj = self.node.as_const(eval_ctx)
""" import types import operator from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, PY2 #: maximum number of items a range may produce
""" import types import operator from collections import Mapping from jinja2.environment import Environment from jinja2.exceptions import SecurityError from jinja2._compat import string_types, text_type, PY2 from jinja2.utils import Markup has_format = False if hasattr(text_type, 'format'): from markupsafe import ...
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) import warnings # make sure we don't warn in python 2.6 about stuff we don't care about
#: unsafe generator attirbutes. UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code']) #: unsafe attributes on coroutines UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code']) #: unsafe attributes on async generators UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame']) import warnings # make su...
) def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items.
) class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args...
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
def is_internal_attribute(obj, attr): elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occour during the rendering so the caller has to ensure that all exceptions are catched. """ sa...
class SandboxedEnvironment(Environment): attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught. """ sand...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" # the double prefixes are to avoid double keyword argument # e...
def unsafe_undefined(self, obj, attribute): obj.__class__.__name__ ), name=attribute, obj=obj, exc=SecurityError) def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. ...
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr)
def is_safe_attribute(self, obj, attr, value): if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value): return False return not modifies_known_mutable(obj, attr) if has_format: # This really is not a public API apparenlty. try: from _string import formatter_fi...
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
from jinja2 import Environment from jinja2.sandbox import SandboxedEnvironment, \ ImmutableSandboxedEnvironment, unsafe, has_format from jinja2 import Markup, escape from jinja2.exceptions import SecurityError, TemplateSyntaxError, \ TemplateRuntimeError
def disable_op(arg): pass else: assert False, 'expected runtime error'
def disable_op(arg): pass else: assert False, 'expected runtime error' @pytest.mark.sandbox @pytest.mark.skipif(not has_format, reason='No format support') class TestStringFormat(object): def test_basic_format_safety(self): env = SandboxedEnvironment() ...
def create_cloned_field(field: ModelField) -> ModelField: original_type.__name__, __config__=original_type.__config__ ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f use_type.__validators__ = original_type.__validators__ if PYDANTIC_1: ...
def create_cloned_field(field: ModelField) -> ModelField: original_type.__name__, __config__=original_type.__config__ ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field(f) use_type.__validators__ = original_type.__validators__ ...
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. """ def __init__(self,
class EarlyStopping(Callback): baseline: Baseline value for the monitored quantity to reach. Training will stop if the model doesn't show improvement over the baseline. restore_best_weights: whether to restore model weights from the epoch with the best value of the mo...
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None): super(EarlyStopping, self).__init__() self.monitor = monitor
class EarlyStopping(Callback): patience=0, verbose=0, mode='auto', baseline=None, restore_best_weights=False): super(EarlyStopping, self).__init__() self.monitor = monitor
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
class EarlyStopping(Callback): self.min_delta = min_delta self.wait = 0 self.stopped_epoch = 0 self.restore_best_weights = restore_best_weights self.best_weights = None if mode not in ['auto', 'min', 'max']: warnings.warn('EarlyStopping mode %s is unknown, '
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 else: self.wait += 1 if self.wait >= self.patience: self.stopped_epoch = epoch self.model.stop_trainin...
class EarlyStopping(Callback): if self.monitor_op(current - self.min_delta, self.best): self.best = current self.wait = 0 if self.restore_best_weights: self.best_weights = self.model.get_weights() else: self.wait += 1 if self.wa...
def test_EarlyStopping_patience(): def __init__(self): self.stop_training = False early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) early_stop.model = DummyModel()
def test_EarlyStopping_patience(): def __init__(self): self.stop_training = False def get_weights(self): return [] def set_weights(self, weights): pass early_stop = callbacks.EarlyStopping(monitor='val_loss', patience=2) early_stop.model = DummyMode...
def test_EarlyStopping_baseline(): def __init__(self): self.stop_training = False def baseline_tester(acc_levels): early_stop = callbacks.EarlyStopping(monitor='val_acc', baseline=0.75, patience=2) early_stop.model = DummyModel()
def test_EarlyStopping_baseline(): def __init__(self): self.stop_training = False def get_weights(self): return [] def set_weights(self, weights): pass def baseline_tester(acc_levels): early_stop = callbacks.EarlyStopping(monitor='val_acc', base...
def test_EarlyStopping_baseline(): assert baseline_not_met == 2 @keras_test def test_LearningRateScheduler(): np.random.seed(1337)
def test_EarlyStopping_baseline(): assert baseline_not_met == 2 @keras_test def test_EarlyStopping_final_weights(): class DummyModel(object): def __init__(self): self.stop_training = False self.weights = -1 def get_weights(self): return self.weights ...
def Ghostscript(tile, size, fp, scale=1): import tempfile, os, subprocess outfile = tempfile.mktemp() infile = tempfile.mktemp() with open(infile, 'wb') as f: fp.seek(offset)
def Ghostscript(tile, size, fp, scale=1): import tempfile, os, subprocess out_fd, outfile = tempfile.mkstemp() os.close(out_fd) in_fd, infile = tempfile.mkstemp() os.close(in_fd) with open(infile, 'wb') as f: fp.seek(offset)
class Image: self.readonly = 0 def _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format ...
class Image: self.readonly = 0 def _dump(self, file=None, format=None): import tempfile, os if not file: f, file = tempfile.mkstemp(format or '') os.close(f) self.load() if not format or format == "PPM": self.im.save_ppm(file)...
class IptcImageFile(ImageFile.ImageFile): self.fp.seek(offset) # Copy image data to temporary file outfile = tempfile.mktemp() o = open(outfile, "wb") if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header
class IptcImageFile(ImageFile.ImageFile): self.fp.seek(offset) # Copy image data to temporary file o_fd, outfile = tempfile.mkstemp(text=False) o = os.fdopen(o_fd) if encoding == "raw": # To simplify access to the extracted file, # prepend a PPM header
class JpegImageFile(ImageFile.ImageFile): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file)) try: self.im = Image.core.open_ppm(file) finally: ...
class JpegImageFile(ImageFile.ImageFile): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os f, path = tempfile.mkstemp() os.close(f) if os.path.exists(self.filename): os.system("djpeg '%s' >'%s'" % (self.filename, path)) else:...
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(None if ending_point == -1 else ending_point -...
def count_leading_spaces(s): def process_list_block(docstring, starting_point, section_end, leading_spaces, marker): ending_point = docstring.find('\n\n', starting_point) block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else sec...
y = layer(x) '''} def test_doc_lists(): docstring = autogen.process_docstring(test_doc1['doc']) assert markdown(docstring) == markdown(test_doc1['result']) dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*.
y = layer(x) '''} test_doc_with_arguments_as_last_block = { 'doc': """Base class for recurrent layers. # Arguments return_sequences: Boolean. Whether to return the last output in the output sequence, or the full sequence. return_state: Boolean. Whether to return the last state ...
class Index(IndexOpsMixin, PandasObject): return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs) # interval elif ( is_interval_dtype(data) or is_interval_dtype(dtype) ) and not is_object_dtype(dtype): closed = kwargs.get("closed", None) ...
class Index(IndexOpsMixin, PandasObject): return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs) # interval elif is_interval_dtype(data) or is_interval_dtype(dtype): closed = kwargs.pop("closed", None) if is_dtype_equal(_o_dtype, dtype): ...
class Index(IndexOpsMixin, PandasObject): else: return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_period_dtype(data) and not is_object_dtype(dtype): return PeriodIndex(data, copy=copy, name=name, **kwargs) # extension dtype ...
class Index(IndexOpsMixin, PandasObject): else: return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_period_dtype(data) or is_period_dtype(dtype): if is_dtype_equal(_o_dtype, dtype): return PeriodIndex(data, copy=False, name=na...
from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd from pandas import Index, Period, PeriodIndex, Series, date_range, offsets, period_range import pandas.core.indexes.period as period import pandas.util.testing as tm class TestPeriodIndex: def setup_method(self, method): pass def ...
from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd from pandas import Index, Period, PeriodIndex, Series, date_range, offsets, period_range from pandas.core.arrays import PeriodArray import pandas.util.testing as tm class TestPeriodIndex: def test_construction_base_constructor(self): #...
class TestPeriodIndex: pd.Index(np.array(arr)), pd.Index(np.array(arr), dtype=object) ) def test_constructor_use_start_freq(self): # GH #1118 p = Period("4/2/2012", freq="B")
class TestPeriodIndex: pd.Index(np.array(arr)), pd.Index(np.array(arr), dtype=object) ) def test_base_constructor_with_period_dtype(self): dtype = PeriodDtype("D") values = ["2011-01-01", "2012-03-04", "2014-05-01"] result = pd.Index(values, dtype=dtype) expecte...
class TestPeriodIndex: assert res.dtype == "period[M]" msg = "specified freq and dtype are different" with pytest.raises(period.IncompatibleFrequency, match=msg): PeriodIndex(["2011-01"], freq="M", dtype="period[D]") def test_constructor_empty(self):
class TestPeriodIndex: assert res.dtype == "period[M]" msg = "specified freq and dtype are different" with pytest.raises(IncompatibleFrequency, match=msg): PeriodIndex(["2011-01"], freq="M", dtype="period[D]") def test_constructor_empty(self):
class TestPeriodIndex: def test_constructor_incompat_freq(self): msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)" with pytest.raises(period.IncompatibleFrequency, match=msg): PeriodIndex( [Period("2011-01", freq="M"), pd.NaT, Period("2011-01", freq="D")] ...
class TestPeriodIndex: def test_constructor_incompat_freq(self): msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)" with pytest.raises(IncompatibleFrequency, match=msg): PeriodIndex( [Period("2011-01", freq="M"), pd.NaT, Period("2011-01", freq="D")] ...
class TestPeriodIndex: ) # first element is pd.NaT with pytest.raises(period.IncompatibleFrequency, match=msg): PeriodIndex( [pd.NaT, Period("2011-01", freq="M"), Period("2011-01", freq="D")] ) with pytest.raises(period.IncompatibleFrequency,...
class TestPeriodIndex: ) # first element is pd.NaT with pytest.raises(IncompatibleFrequency, match=msg): PeriodIndex( [pd.NaT, Period("2011-01", freq="M"), Period("2011-01", freq="D")] ) with pytest.raises(IncompatibleFrequency, match=msg): ...
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size def __len__(self): return int(np.ceil( (self.end_index - self.start_index) / (self.batch_size * self.stride))) def _empty_batch(self, num_rows):
class TimeseriesGenerator(Sequence): self.reverse = reverse self.batch_size = batch_size if self.start_index > self.end_index: raise ValueError('`start_index+length=%i > end_index=%i` ' 'is disallowed, as no part of the sequence ' ...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.arang...
class TimeseriesGenerator(Sequence): def __getitem__(self, index): if self.shuffle: rows = np.random.randint( self.start_index, self.end_index + 1, size=self.batch_size) else: i = self.start_index + self.batch_size * self.stride * index rows = np.a...
import numpy as np from numpy.testing import assert_allclose import pytest
from math import ceil import numpy as np from numpy.testing import assert_allclose, assert_raises import pytest
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert (np.allclose(data_gen[0][0], np.array([[[10], ...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 5 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2]...
def test_TimeseriesGenerator(): length=10, sampling_rate=2, start_index=10, end_index=30, batch_size=2) assert len(data_gen) == 6 assert np.allclose(data_gen[0][0], np.array( [np.array(data[10:19:2])...
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str from django.utils.regex_helper import _lazy_re_compile class BaseDatabaseOperations:
from django.db import NotSupportedError, transaction from django.db.backends import utils from django.utils import timezone from django.utils.encoding import force_str class BaseDatabaseOperations:
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None extract_trunc_lookup_pattern = _lazy_re_compile(r"[\w\-_()]+") def __init__(self, connection): self.connection = connection self._cache = None
class BaseDatabaseOperations: # Prefix for EXPLAIN queries, or None EXPLAIN isn't supported. explain_prefix = None def __init__(self, connection): self.connection = connection self._cache = None
class BaseDatabaseOperations: """ return "%s" def date_extract_sql(self, lookup_type, field_name): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that extracts a value from the given date field field_name.
class BaseDatabaseOperations: """ return "%s" def date_extract_sql(self, lookup_type, sql, params): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that extracts a value from the given date field field_name.
class BaseDatabaseOperations: "method" ) def date_trunc_sql(self, lookup_type, field_name, tzname=None): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that truncates the given date or datetime field field_name to a date object
class BaseDatabaseOperations: "method" ) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'year', 'month', or 'day', return the SQL that truncates the given date or datetime field field_name to a date object
class BaseDatabaseOperations: "method." ) def datetime_cast_date_sql(self, field_name, tzname): """ Return the SQL to cast a datetime value to date value. """
class BaseDatabaseOperations: "method." ) def datetime_cast_date_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to date value. """
class BaseDatabaseOperations: "datetime_cast_date_sql() method." ) def datetime_cast_time_sql(self, field_name, tzname): """ Return the SQL to cast a datetime value to time value. """
class BaseDatabaseOperations: "datetime_cast_date_sql() method." ) def datetime_cast_time_sql(self, sql, params, tzname): """ Return the SQL to cast a datetime value to time value. """
class BaseDatabaseOperations: "datetime_cast_time_sql() method" ) def datetime_extract_sql(self, lookup_type, field_name, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that extracts a value from the given
class BaseDatabaseOperations: "datetime_cast_time_sql() method" ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that extracts a value from the given
class BaseDatabaseOperations: "method" ) def datetime_trunc_sql(self, lookup_type, field_name, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that truncates the given datetime field
class BaseDatabaseOperations: "method" ) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that truncates the given datetime field
class BaseDatabaseOperations: "method" ) def time_trunc_sql(self, lookup_type, field_name, tzname=None): """ Given a lookup_type of 'hour', 'minute' or 'second', return the SQL that truncates the given time or datetime field field_name to a time
class BaseDatabaseOperations: "method" ) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): """ Given a lookup_type of 'hour', 'minute' or 'second', return the SQL that truncates the given time or datetime field field_name to a time