buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
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 posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'g...
def posix_pipe(fin, fout, delim='\n', buf_size=256, # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(?:\s*|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterab...
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
def test_main(): _SYS = sys.stdin, sys.argv with closing(StringIO()) as sys.stdin: sys.argv = ['', '--desc', 'Test CLI-delims', '--ascii', 'True', '--delim', r'\0', '--buf_size', '64'] sys.stdin.write('\0'.join(map(str, _range(int(1e3))))) sys.stdin.seek(0)
def check_required_arguments(argument_spec, module_parameters): missing.append(k) if missing: msg = "missing required arguments: %s" % ", ".join(missing) raise TypeError(to_native(msg)) return missing
def check_required_arguments(argument_spec, module_parameters): missing.append(k) if missing: msg = "missing required arguments: %s" % ", ".join(sorted(missing)) raise TypeError(to_native(msg)) return missing
def test_check_mutually_exclusive_found(mutually_exclusive_terms): 'fox': 'red', 'socks': 'blue', } expected = "TypeError('parameters are mutually exclusive: string1|string2, box|fox|socks',)" with pytest.raises(TypeError) as e: check_mutually_exclusive(mutually_exclusive_terms, par...
def test_check_mutually_exclusive_found(mutually_exclusive_terms): 'fox': 'red', 'socks': 'blue', } expected = "parameters are mutually exclusive: string1|string2, box|fox|socks" with pytest.raises(TypeError) as e: check_mutually_exclusive(mutually_exclusive_terms, params) asse...
def test_check_mutually_exclusive_none(): def test_check_mutually_exclusive_no_params(mutually_exclusive_terms): with pytest.raises(TypeError) as te: check_mutually_exclusive(mutually_exclusive_terms, None) assert "TypeError: 'NoneType' object is not iterable" in to_native(te.error)
def test_check_mutually_exclusive_none(): def test_check_mutually_exclusive_no_params(mutually_exclusive_terms): with pytest.raises(TypeError) as te: check_mutually_exclusive(mutually_exclusive_terms, None) assert "'NoneType' object is not iterable" in to_native(te.value)
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string) # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) # Host patterns
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string) # IP patterns ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) # Host pa...
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is included in Python 3.9.5...
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # validate_ipv6_address uses django.utils.ipv6, which # is tested in much greater detail in its own testcase (validate_ipv6_address, 'fe80::1', None),
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv4_address, '000.000.000.000', ValidationError), (validate_ipv4_address, '016.016.016.0...
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '12', None), (validate_comma_separated_integer_list, '1,2', None),
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv46_address, '000.000.000.000', ValidationError), (validate_ipv46_address, '016.016.016.016',...
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) StrBytesIntFloat = Union[str, bytes, int, float]
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) # slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 MAX_NUMBER = int(3e20) StrBytesIntFloat = Union[str, by...
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: while abs(seconds) > MS_WATERSHED: seconds /= 1000 dt = EPOCH + timedelta(seconds=seconds)
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: if seconds > MAX_NUMBER: return datetime.max elif seconds < -MAX_NUMBER: return datetime.min while abs(seconds) > MS_WATERSHED: seconds /...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ], ) def test_date_parsing(value, result): if result == errors.DateError: with ...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ('infinity', date(9999, 12, 31)), ('inf', date(9999, 12, 31)), (float('...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", }
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", } def test_nan(): class Model(BaseModel): dt: datetime d: date with pytest.raises(ValidationError) as exc_info: Model(dt='n...
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models.aggregates import Aggregate from django.utils.functional import cached_property
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models import Value from django.db.models.aggregates import Aggregate from django.utils.functional import cached_property
class GeoAggregate(Aggregate): ) def as_oracle(self, compiler, connection, **extra_context): tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))' return self.as_s...
class GeoAggregate(Aggregate): ) def as_oracle(self, compiler, connection, **extra_context): if not self.is_extent: tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) clone = self.copy() clone.set_source_expressions([ *sel...
class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tol = self.extra.get('tolerance', self.tolerance) return self.as_sql( compiler, connection, template="%%(function)s(%%(expressions)s, %s)" % tol, **extra_...
class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tolerance = Value(self._handle_param( self.extra.get('tolerance', self.tolerance), 'tolerance', NUMERIC_TYPES, )) clone = self.copy() clon...
class DistanceFunctionsTests(FuncTestMixin, TestCase): ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @skipIfDBFeature("supports_distance_geodetic") @skipUnlessDBFeature("has_Distance_function") def test_distance_function_raw_result_d_lookup(self):
class DistanceFunctionsTests(FuncTestMixin, TestCase): ).filter(d=D(m=1)) self.assertTrue(qs.exists()) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_distance_function_tolerance_escaping(self): qs = Interstate....
import tempfile from io import StringIO from django.contrib.gis import gdal
import tempfile import unittest from io import StringIO from django.contrib.gis import gdal
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import NotSupportedError, connection from django.test import TestCase, skipUnlessDBFeature from ..utils import (
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, NotSupportedError, connection from django.test import TestCase, skipUnlessDBFeature from ..utils import (
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery)
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_unionagg_tolerance(self): ...
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "templates/utf8.html", "test.crt", "test.key",
setup( "options_test.cfg", "static/robots.txt", "static/dir/index.html", "static_foo.txt", "templates/utf8.html", "test.crt", "test.key",
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) @wsgi_safe class StaticDefaultFilenameTest(WebTestCase):
class StaticFileTest(WebTestCase): response = self.get_and_head('/static/blarg') self.assertEqual(response.code, 404) def test_path_traversal_protection(self): with ExpectLog(gen_log, ".*not in root static directory"): response = self.get_and_head('/static/../static_foo.txt') ...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ root = os.path.abspath(root) # os.path.abspath strips a trailing / # it needs to be temporarily added back for requests to root/ if not (absolute_path + os.path.sep).startswith(root): raise HT...
class StaticFileHandler(RequestHandler): .. versionadded:: 3.1 """ # os.path.abspath strips a trailing /. # We must add it back to `root` so that we only match files # in a directory named `root` instead of files starting with # that prefix. root = os.path.abspat...
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other, func, fill_value=None, level=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
class DataFrame(NDFrame): # ---------------------------------------------------------------------- # Arithmetic / combination related def _combine_frame(self, other: "DataFrame", func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None:
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
class DataFrame(NDFrame): return new_data def _combine_match_index(self, other: Series, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func):
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values with np.errstate(all="ignore"): new_data = func(self.values.T, other.values).T return new_data def _construct_result(sel...
class DataFrame(NDFrame): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values other_vals = other.values.reshape(-1, 1) with np.errstate(all="ignore"): new_data = func(self.values, other_vals) ...
def mask_zero_div_zero(x, y, result): return result if zmask.any(): shape = result.shape # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = (zmask & (x == 0)).ravel() with np.errstate(invalid="ignor...
def mask_zero_div_zero(x, y, result): return result if zmask.any(): # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask nan_mask = zmask & (x == 0) with np.errstate(invalid="ignore"): neginf_mask = (zpos_ma...
class TestFrameFlexComparisons: class TestFrameFlexArithmetic: def test_df_add_td64_columnwise(self): # GH 22534 Check that column-wise addition broadcasts correctly dti = pd.date_range("2016-01-01", periods=10)
class TestFrameFlexComparisons: class TestFrameFlexArithmetic: def test_floordiv_axis0(self): # make sure we df.floordiv(ser, axis=0) matches column-wise result arr = np.arange(3) ser = pd.Series(arr) df = pd.DataFrame({"A": ser, "B": ser}) result = df.floordiv(ser, axis=0...
import json import yaml from urllib.request import urlopen from yaml import Loader, SafeLoader import csv from csv import register_dialect, Dialect, QUOTE_MINIMAL
import json import yaml from urllib.request import urlopen from yaml import SafeLoader import csv from csv import register_dialect, Dialect, QUOTE_MINIMAL
def increase_indent(self, flow=False, indentless=False): def construct_yaml_str(self, node): return self.construct_scalar(node) Loader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
def increase_indent(self, flow=False, indentless=False): def construct_yaml_str(self, node): return self.construct_scalar(node) SafeLoader.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str)
def load_yaml(yaml_str): :param unicode yaml_str: :rtype: dict | list """ return yaml.load(yaml_str) def load_yamlf(fpath, encoding):
def load_yaml(yaml_str): :param unicode yaml_str: :rtype: dict | list """ return yaml.safe_load(yaml_str) def load_yamlf(fpath, encoding):
def load_yamlf(fpath, encoding): :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.load(f) def load_csvf(fpath, fieldnames, encoding):
def load_yamlf(fpath, encoding): :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.safe_load(f) def load_csvf(fpath, fieldnames, encoding):
from __future__ import division, absolute_import, unicode_literals from owlmixin import util class TestReplaceKeys: def test_need_not_snake(self):
from __future__ import division, absolute_import, unicode_literals from yaml.constructor import ConstructorError from owlmixin import util import pytest class TestReplaceKeys: def test_need_not_snake(self):
def test_docopt(self): assert util.to_snake("<file_list>") == "file_list" assert util.to_snake("-o") == "o" assert util.to_snake("--detail-option") == "detail_option"
def test_docopt(self): assert util.to_snake("<file_list>") == "file_list" assert util.to_snake("-o") == "o" assert util.to_snake("--detail-option") == "detail_option" class TestLoadYaml: def test(self): actual = util.load_yaml(''' id: 1 names: - tadashi - aikawa ''') ...
def add_special_arithmetic_methods(cls): def f(self, other): result = method(self, other) # this makes sure that we are aligned like the input # we are updating inplace so we want to ignore is_copy self._update_inplace(
def add_special_arithmetic_methods(cls): def f(self, other): result = method(self, other) # Delete cacher self._reset_cacher() # this makes sure that we are aligned like the input # we are updating inplace so we want to ignore is_copy self...
class TestDataFrameSelectReindex: result = df2.reindex(midx) expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) tm.assert_frame_equal(result, expected)
class TestDataFrameSelectReindex: result = df2.reindex(midx) expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "operation", ["__iadd__", "__isub__", "__imul__", "__ipow__"] ) @pytest...
def _normalize(table, normalize, margins, margins_name="All"): table = table.fillna(0) elif margins is True: column_margin = table.loc[:, margins_name].drop(margins_name) index_margin = table.loc[margins_name, :].drop(margins_name) table = table.drop(margins_name, axis=1).drop(marg...
def _normalize(table, normalize, margins, margins_name="All"): table = table.fillna(0) elif margins is True: # keep index and column of pivoted table table_index = table.index table_columns = table.columns # check if margin name is in (for MI cases) or equal to last ...
def _normalize(table, normalize, margins, margins_name="All"): column_margin = column_margin / column_margin.sum() table = concat([table, column_margin], axis=1) table = table.fillna(0) elif normalize == "index": index_margin = index_margin / index_margin.sum() ...
def _normalize(table, normalize, margins, margins_name="All"): column_margin = column_margin / column_margin.sum() table = concat([table, column_margin], axis=1) table = table.fillna(0) table.columns = table_columns elif normalize == "index": index_ma...
def _normalize(table, normalize, margins, margins_name="All"): table = table.append(index_margin) table = table.fillna(0) else: raise ValueError("Not a valid normalize argument") table.index.names = table_index_names table.columns.names = table_columns_name...
def _normalize(table, normalize, margins, margins_name="All"): table = table.append(index_margin) table = table.fillna(0) table.index = table_index table.columns = table_columns else: raise ValueError("Not a valid normalize argument") else: ...
class TestCrosstab: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns ) tm.assert_frame_equal(result, expected)
class TestCrosstab: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns ) tm.assert_frame_equal(result, expected) def test_margin_normalize(self): # GH 27500 df = pd.DataFrame( { "A": ["foo", "foo", "foo", "foo", "foo", "bar", "b...
class Task(object): exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs) # Fill in the positional arguments positional_params = [(n, p) for n, p in params if p.significant] for i, arg in enumerate(args): if i >= len(positional_params): raise parame...
class Task(object): exc_desc = '%s[args=%s, kwargs=%s]' % (task_name, args, kwargs) # Fill in the positional arguments positional_params = [(n, p) for n, p in params if not p.is_global] for i, arg in enumerate(args): if i >= len(positional_params): raise para...
class ParameterTest(unittest.TestCase): t1 = InsignificantParameterTask(foo='x', bar='y') self.assertEqual(t1.task_id, 'InsignificantParameterTask(bar=y)') t2 = InsignificantParameterTask('z') self.assertEqual(t2.foo, 'foo_default') self.assertEqual(t2.bar, 'z') self.ass...
class ParameterTest(unittest.TestCase): t1 = InsignificantParameterTask(foo='x', bar='y') self.assertEqual(t1.task_id, 'InsignificantParameterTask(bar=y)') t2 = InsignificantParameterTask('u', 'z') self.assertEqual(t2.foo, 'u') self.assertEqual(t2.bar, 'z') self.assertEq...
class TestRemoveGlobalParameters(unittest.TestCase): self.assertTrue(run_exit_status) return run_exit_status def test_use_config_class_1(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 99)
class TestRemoveGlobalParameters(unittest.TestCase): self.assertTrue(run_exit_status) return run_exit_status def test_use_config_class_1(self): self.run_and_check(['--MyConfig-mc-p', '99', '--mc-r', '55', 'NoopTask']) self.assertEqual(MyConfig().mc_p, 99)
class TestRemoveGlobalParameters(unittest.TestCase): self.assertEqual(Dogs().n_dogs, 654) self.assertEqual(CatsWithoutSection().n_cats, 321) class TestParamWithDefaultFromConfig(unittest.TestCase):
class TestRemoveGlobalParameters(unittest.TestCase): self.assertEqual(Dogs().n_dogs, 654) self.assertEqual(CatsWithoutSection().n_cats, 321) def test_global_significant_param(self): """ We don't want any kind of global param to be positional """ class MyTask(luigi.Task): ...
def assert_series_equal( check_exact=False, check_datetimelike_compat=False, check_categorical=True, obj="Series", ): """
def assert_series_equal( check_exact=False, check_datetimelike_compat=False, check_categorical=True, check_category_order=True, obj="Series", ): """
def assert_series_equal( Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion...
def assert_series_equal( Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_category_order : bool, default True Whether to compare category order of internal Categoricals .. vers...
def assert_series_equal( if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal(left.values, right.values, obj=f"{obj} category") # This could be refactored to use the NDFrame.equals method
def assert_series_equal( if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal( left.values, right.values, obj=f"{obj} category", check_category_order=check_category_order, ...
class Categorical(ExtensionArray, PandasObject): """ inplace = validate_bool_kwarg(inplace, "inplace") cat = self if inplace else self.copy() if to_replace in cat.categories: if isna(value): cat.remove_categories(to_replace, inplace=True) else: ...
class Categorical(ExtensionArray, PandasObject): """ inplace = validate_bool_kwarg(inplace, "inplace") cat = self if inplace else self.copy() # build a dict of (to replace -> value) pairs if is_list_like(to_replace): # if to_replace is list-like and value is scalar ...
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): str_number = '{:f}'.format(number) else: str_number = str(number) if str_number[0] == '-':
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', # sign sign = '' if isinstance(number, Decimal): # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponen...
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal):
class TestNumberFormat(SimpleTestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') # Very large & small numbers. tests = [ ('9e9999', None, '9e+9999'), ('9e9999', 3, '9.000e+9999'), ...
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", "Tests/images/crash-1152ec2d1a1a71395b6f2ce6721c38924d025bf3.tif", "Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif", ], ) @pytest.mark.fil...
from .helper import on_ci "Tests/images/crash_1.tif", "Tests/images/crash_2.tif", "Tests/images/crash-2020-10-test.tif", "Tests/images/crash-0c7e0e8e11ce787078f00b5b0ca409a167f070e0.tif", "Tests/images/crash-0e16d3bfb83be87356d026d66919deaefca44dac.tif", "Tests/images/cra...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", ], ) @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF da...
from .helper import on_ci "Tests/images/crash-4f085cc12ece8cde18758d42608bed6a2a2cfb1c.tif", "Tests/images/crash-86214e58da443d2b80820cff9677a38a33dcbbca.tif", "Tests/images/crash-f46f5b2f43c370fe65706c11449f567ecc345e74.tif", "Tests/images/crash-63b1dffefc8c075ddc606c0a2f5fdc15ece78863....
def request_httprepr(request): parsed = urlparse_cached(request) path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, '')) s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n" s += b"Host: " + to_bytes(parsed.hostname) + b"\r\n" if request.headers: s...
def request_httprepr(request): parsed = urlparse_cached(request) path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, '')) s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n" s += b"Host: " + to_bytes(parsed.hostname or b'') + b"\r\n" if request.headers: ...
class UtilsRequestTest(unittest.TestCase): r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body") self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body') if __name__ == "__m...
class UtilsRequestTest(unittest.TestCase): r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body") self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body') def test_reques...
class Index(IndexOpsMixin, PandasObject): multi_join_idx = multi_join_idx.remove_unused_levels() return multi_join_idx, lidx, ridx jl = list(overlap)[0]
class Index(IndexOpsMixin, PandasObject): multi_join_idx = multi_join_idx.remove_unused_levels() if return_indexers: return multi_join_idx, lidx, ridx else: return multi_join_idx jl = list(overlap)[0]
def test_join_multi_wrong_order(): midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"]) join_idx, lidx, ridx = midx1.join(midx2, return_indexers=False) exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp) tm....
def test_join_multi_wrong_order(): midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"]) join_idx, lidx, ridx = midx1.join(midx2, return_indexers=True) exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp) tm.a...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd(): return '''ERROR: unknown command "instatl" - maybe you meant "install"''' @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recomm...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' @pytest.fixture def broken(): return 'instatl' @pytest.fixture def suggested(): return 'install' @pytest.fixture def pip_unknown_cmd(broken, suggested): return 'ERRO...
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) def test_get_new_command(pip_unknown_cmd): assert get_new_command(Command('pip instatl', pip_unknown_cmd)) == 'pip install'
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) @pytest.mark.parametrize('script, broken, suggested, new_cmd', [ ('pip un+install thefuck', 'un+install', 'uninstall', 'pip uninstall thefuck'), ('pip instatl', 'instatl', 'inst...
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command \"([a-z]+)\"', command.output)[0] new_cmd = re.findall(r'maybe you meant \"([a-z]+)\"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command "([^"]+)"', command.output)[0] new_cmd = re.findall(r'maybe you meant "([^"]+)"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): outlen = backend._ffi.new("size_t *", buf_size) buf = backend._ffi.new("unsigned char[]", buf_size) res = crypt(pkey_ctx, buf, outlen, data, len(data)) if res <= 0: _handle_rsa_enc_dec_error(backend, key) return backend....
def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): outlen = backend._ffi.new("size_t *", buf_size) buf = backend._ffi.new("unsigned char[]", buf_size) # Everything from this line onwards is written with the goal of being as # constant-time as is practical given the constraints of Pyt...
class TestYoutubeChapters(unittest.TestCase): for description, duration, expected_chapters in self._TEST_CASES: ie = YoutubeIE() expect_value( self, ie._extract_chapters(description, duration), expected_chapters, None)
class TestYoutubeChapters(unittest.TestCase): for description, duration, expected_chapters in self._TEST_CASES: ie = YoutubeIE() expect_value( self, ie._extract_chapters_from_description(description, duration), expected_chapters, None)
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id @staticmethod def _extract_chapters(description, duration): if not description: return None chapter_lines = re.findall(
class YoutubeIE(YoutubeBaseInfoExtractor): video_id = mobj.group(2) return video_id def _extract_chapters_from_json(self, webpage, video_id, duration): if not webpage: return player = self._parse_json( self._search_regex( r'RELATED_PLAYER_ARGS...
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {})
class YoutubeIE(YoutubeBaseInfoExtractor): }) return chapters def _extract_chapters(self, webpage, description, video_id, duration): return (self._extract_chapters_from_json(webpage, video_id, duration) or self._extract_chapters_from_description(description, duration)) ...
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(description_original, video_duration) # Look for the DASH manifest ...
class YoutubeIE(YoutubeBaseInfoExtractor): errnote='Unable to download video annotations', fatal=False, data=urlencode_postdata({xsrf_field_name: xsrf_token})) chapters = self._extract_chapters(video_webpage, description_original, video_id, video_duration) # Loo...
class BracketTracker: bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict) delimiters: Dict[LeafID, Priority] = Factory(dict) previous: Optional[Leaf] = None _for_loop_variable: int = 0 _lambda_arguments: int = 0 def mark(self, leaf: Leaf) -> None: """Mark `leaf` with brack...
class BracketTracker: bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict) delimiters: Dict[LeafID, Priority] = Factory(dict) previous: Optional[Leaf] = None _for_loop_depths: List[int] = Factory(list) _lambda_argument_depths: List[int] = Factory(list) def mark(self, leaf: Leaf) ->...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "for": self.depth += 1 self._for_loop_variable += 1 return True return False def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool: """See `maybe_increment_for...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "for": self.depth += 1 self._for_loop_depths.append(self.depth) return True return False def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool: """See `maybe_i...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "lambda": self.depth += 1 self._lambda_arguments += 1 return True return False def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool: """See `maybe_increment_la...
class BracketTracker: """ if leaf.type == token.NAME and leaf.value == "lambda": self.depth += 1 self._lambda_argument_depths.append(self.depth) return True return False def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool: """See...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) def test_report_verbose(self) -> None: report = black.Report(verbose=True) out_lines = []
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) @patch("black.dump_to_file", dump_to_stderr) def test_bracket_match(self) -> None: source, expected = read_data("bracketmatch") actual = fs(source)...
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False ) as f: for lines in output: f.write(lines)
def dump_to_file(*output: str) -> str: import tempfile with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8" ) as f: for lines in output: f.write(lines)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file) as f: actual = f.read() finally: os.unlink(tmp_file)
class BlackTestCase(unittest.TestCase): tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file, encoding="utf8") as f: actual = f.read() finally: os.unlink(tmp_file)
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('8/7/2009'), '20090708') self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') def test_find_xpath_attr(self): testxml = u'''<root>
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('8/7/2009'), '20090708') self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') self.assertEqual(unified_strdate('1968-12-10'), '19681210'...
def unified_strdate(date_str): """Return a string with the date in the format YYYYMMDD""" upload_date = None #Replace commas date_str = date_str.replace(',',' ') # %z (UTC offset) is only supported in python>=3.2 date_str = re.sub(r' ?(\+|-)[0-9:]*$', '', date_str) format_expressions = [ ...
def unified_strdate(date_str): """Return a string with the date in the format YYYYMMDD""" upload_date = None #Replace commas date_str = date_str.replace(',', ' ') # %z (UTC offset) is only supported in python>=3.2 date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str) format_express...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): output_dim = self.cell.state_size[0] else: output_dim = self.cell.state_size if self.return_sequences: output_shape = (input_shape[0], input_shape[1], out...
class RNN(Layer): input_shape = input_shape[0] if hasattr(self.cell.state_size, '__len__'): state_size = self.cell.state_size else: state_size = [self.cell.state_size] output_dim = state_size[0] if self.return_sequences: output_shape = (i...
class RNN(Layer): output_shape = (input_shape[0], output_dim) if self.return_state: state_shape = [(input_shape[0], output_dim) for _ in self.states] return [output_shape] + state_shape else: return output_shape
class RNN(Layer): output_shape = (input_shape[0], output_dim) if self.return_state: state_shape = [(input_shape[0], dim) for dim in state_size] return [output_shape] + state_shape else: return output_shape
def test_stacked_rnn_attributes(): assert layer.get_losses_for(x) == [y] @rnn_test def test_batch_size_equal_one(layer_class): inputs = Input(batch_shape=(1, timesteps, embedding_dim))
def test_stacked_rnn_attributes(): assert layer.get_losses_for(x) == [y] @keras_test def test_stacked_rnn_compute_output_shape(): cells = [recurrent.LSTMCell(3), recurrent.LSTMCell(6)] layer = recurrent.RNN(cells, return_state=True, return_sequences=True) output_shape = layer.compute_outp...
class Parameter(object): return [str(v) for v in x] return str(x) def parse_from_input(self, param_name, x): """ Parses the parameter value from input ``x``, handling defaults and is_list.
class Parameter(object): return [str(v) for v in x] return str(x) def parse_from_input(self, param_name, x, task_name=None): """ Parses the parameter value from input ``x``, handling defaults and is_list.
class Parameter(object): :raises MissingParameterException: if x is false-y and no default is specified. """ if not x: if self.has_value: return self.value elif self.is_bool: return False elif self.is_list:
class Parameter(object): :raises MissingParameterException: if x is false-y and no default is specified. """ if not x: if self.has_task_value(param_name=param_name, task_name=task_name): return self.task_value(param_name=param_name, task_name=task_name) el...
class Parameter(object): description.append('for all instances of class %s' % task_name) elif self.description: description.append(self.description) if self.has_value: description.append(" [default: %s]" % (self.value,)) if self.is_list: action = ...
class Parameter(object): description.append('for all instances of class %s' % task_name) elif self.description: description.append(self.description) if self.has_task_value(param_name=param_name, task_name=task_name): value = self.task_value(param_name=param_name, task...
class Parameter(object): dest = self.parser_dest(param_name, task_name, glob=False) if dest is not None: value = getattr(args, dest, None) params[param_name] = self.parse_from_input(param_name, value) def set_global_from_args(self, param_name, task_name, args, is_without_sec...
class Parameter(object): dest = self.parser_dest(param_name, task_name, glob=False) if dest is not None: value = getattr(args, dest, None) params[param_name] = self.parse_from_input(param_name, value, task_name=task_name) def set_global_from_args(self, param_name, task_name,...
class Parameter(object): if dest is not None: value = getattr(args, dest, None) if value: self.set_global(self.parse_from_input(param_name, value)) else: # either False (bools) or None (everything else) self.reset_global()
class Parameter(object): if dest is not None: value = getattr(args, dest, None) if value: self.set_global(self.parse_from_input(param_name, value, task_name=task_name)) else: # either False (bools) or None (everything else) self.reset_global()...
class TestRemoveGlobalParameters(unittest.TestCase): class TestParamWithDefaultFromConfig(unittest.TestCase): def testNoSection(self): self.assertRaises(ParameterException, lambda: luigi.Parameter(config_path=dict(section="foo", name="bar")).value)
class TestRemoveGlobalParameters(unittest.TestCase): class TestParamWithDefaultFromConfig(unittest.TestCase): def run_and_check(self, args): run_exit_status = luigi.run(['--local-scheduler', '--no-lock'] + args) return run_exit_status def testNoSection(self): self.assertRaises(Paramet...
class TestParamWithDefaultFromConfig(unittest.TestCase): self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back) self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back) class OverrideEnvStuff(unittest.TestCase):
class TestParamWithDefaultFromConfig(unittest.TestCase): self.assertEqual(123, luigi.tools.range.RangeDaily(of=A).days_back) self.assertEqual(70, luigi.tools.range.RangeDaily(of=A, days_back=70).days_back) @with_config({"MyClass": {"p_not_global": "123"}}) def testCommandLineWithDefault(self): ...
class _MergeOperation: ) ] else: left_keys = [self.left.index.values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class _MergeOperation: ) ] else: left_keys = [self.left.index._values] if left_drop: self.left = self.left._drop_labels_or_levels(left_drop)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected)
class TestAsOfMerge: result = pd.merge_asof(left, right, on="a", tolerance=10) tm.assert_frame_equal(result, expected) def test_merge_index_column_tz(self): # GH 29864 index = pd.date_range("2019-10-01", freq="30min", periods=5, tz="UTC") left = pd.DataFrame([0.9, 0.8, 0.7,...
setup( name="waitress", version="1.3.1", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
setup( name="waitress", version="1.4.0", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
import re from io import BytesIO from waitress.compat import ( tostr, urlparse, unquote_bytes_to_wsgi, ) from waitress.buffers import OverflowableBuffer from waitress.receiver import ( FixedStreamReceiver, ChunkedReceiver, ) from waitress.utilities import ( find_double_newline, RequestEn...
import re from io import BytesIO from waitress.buffers import OverflowableBuffer from waitress.compat import tostr, unquote_bytes_to_wsgi, urlparse from waitress.receiver import ChunkedReceiver, FixedStreamReceiver from waitress.utilities import ( BadRequest, RequestEntityTooLarge, RequestHeaderFieldsTooLa...
class ParsingError(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
class ParsingError(Exception): pass class TransferEncodingNotImplemented(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
def received(self, data): """ if self.completed: return 0 # Can't consume any more. datalen = len(data) br = self.body_rcv if br is None: # In header. s = self.header_plus + data index = find_double_newline(s) if index ...
def received(self, data): """ if self.completed: return 0 # Can't consume any more. datalen = len(data) br = self.body_rcv if br is None: # In header. max_header = self.adj.max_request_header_size s = self.header_plus + data ...
def received(self, data): except ParsingError as e: self.error = BadRequest(e.args[0]) self.completed = True else: if self.body_rcv is None: # no content-length header and not a t-...
def received(self, data): except ParsingError as e: self.error = BadRequest(e.args[0]) self.completed = True except TransferEncodingNotImplemented as e: self.error = ServerNotImplemented(e.args[0]) ...
def received(self, data): elif br.completed: # The request (with the body) is ready to use. self.completed = True if self.chunked: # We've converted the chunked transfer encoding request # body into a normal request body...
def received(self, data): elif br.completed: # The request (with the body) is ready to use. self.completed = True if self.chunked: # We've converted the chunked transfer encoding request # body into a normal request bod...
def received(self, data): # appear to the client to be an entirely non-chunked HTTP # request with a valid content-length. self.headers["CONTENT_LENGTH"] = str(br.__len__()) return consumed def parse_header(self, header_plus):
def received(self, data): # appear to the client to be an entirely non-chunked HTTP # request with a valid content-length. self.headers["CONTENT_LENGTH"] = str(br.__len__()) return consumed def parse_header(self, header_plus):
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 1 :] ...
def parse_header(self, header_plus): Parses the header_plus block of text (the headers plus the first line of the request). """ index = header_plus.find(b"\r\n") if index >= 0: first_line = header_plus[:index].rstrip() header = header_plus[index + 2 :] ...
def parse_header(self, header_plus): index = line.find(b":") if index > 0: key = line[:index] if b"_" in key: continue value = line[index + 1 :].strip()
def parse_header(self, header_plus): index = line.find(b":") if index > 0: key = line[:index] if key != key.strip(): raise ParsingError("Invalid whitespace after field-name") if b"_" in key: continue ...
def parse_header(self, header_plus): # should not see the HTTP_TRANSFER_ENCODING header; we pop it # here te = headers.pop("TRANSFER_ENCODING", "") if te.lower() == "chunked": self.chunked = True buf = OverflowableBuffer(self.adj.inbuf_over...
def parse_header(self, header_plus): # should not see the HTTP_TRANSFER_ENCODING header; we pop it # here te = headers.pop("TRANSFER_ENCODING", "") encodings = [encoding.strip().lower() for encoding in te.split(",") if encoding] for encoding in encodings: ...
def parse_header(self, header_plus): try: cl = int(headers.get("CONTENT_LENGTH", 0)) except ValueError: cl = 0 self.content_length = cl if cl > 0: buf = OverflowableBuffer(self.adj.inbuf_overflow)
def parse_header(self, header_plus): try: cl = int(headers.get("CONTENT_LENGTH", 0)) except ValueError: raise ParsingError("Content-Length is invalid") self.content_length = cl if cl > 0: buf = OverflowableBuffer(self.adj.i...
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\n") for line in lines: if line.startswith((b" ", b"\t")): if not r: # https://corte.si/posts/code/pathod/pythonservers/index.html
def get_header_lines(header): Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\r\n") for line in lines: if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line)) if ...
"""Data Chunk Receiver """ from waitress.utilities import find_double_newline from waitress.utilities import BadRequest class FixedStreamReceiver(object):
"""Data Chunk Receiver """ from waitress.utilities import BadRequest, find_double_newline class FixedStreamReceiver(object):