buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TruncTime(TruncBase): def as_sql(self, compiler, connection): # Cast to time rather than truncate to time. lhs, lhs_params = compiler.compile(self.lhs) tzname = self.get_tzname() sql = connection.ops.datetime_cast_time_sql(lhs, tzname) return sql, lhs_params class Tr...
class TruncTime(TruncBase): def as_sql(self, compiler, connection): # Cast to time rather than truncate to time. sql, params = compiler.compile(self.lhs) tzname = self.get_tzname() return connection.ops.datetime_cast_time_sql(sql, tuple(params), tzname) class TruncHour(TruncBase):
class SimpleDatabaseOperationTests(SimpleTestCase): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "date_extract_sql" ): self.ops.date_extract_sql(None, None) def test_time_extract_sql(self): with self.assertRaisesMessage( NotI...
class SimpleDatabaseOperationTests(SimpleTestCase): with self.assertRaisesMessage( NotImplementedError, self.may_require_msg % "date_extract_sql" ): self.ops.date_extract_sql(None, None, None) def test_time_extract_sql(self): with self.assertRaisesMessage( ...
class YearTransform(models.Transform): def as_sql(self, compiler, connection): lhs_sql, params = compiler.compile(self.lhs) return connection.ops.date_extract_sql("year", lhs_sql), params @property def output_field(self):
class YearTransform(models.Transform): def as_sql(self, compiler, connection): lhs_sql, params = compiler.compile(self.lhs) return connection.ops.date_extract_sql("year", lhs_sql, params) @property def output_field(self):
except ImportError: pytz = None from django.conf import settings from django.db.models import ( DateField, DateTimeField,
except ImportError: pytz = None from django.conf import settings from django.db import DataError, OperationalError from django.db.models import ( DateField, DateTimeField,
class DateFunctionTests(TestCase): self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) msg = "Invalid lookup_name: " with self.assertRaisesMessage(ValueError, msg): DTModel.objects.filter( start_datetime__year=Extra...
class DateFunctionTests(TestCase): self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaises((DataError, OperationalError, ValueError)): DTModel.objects.filter( start_datetime__year=Extract( ...
class DateFunctionTests(TestCase): end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) msg = "Invalid kind: " with self.assertRaisesMessage(ValueError, msg): DTModel.objec...
class DateFunctionTests(TestCase): end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) # Database backends raise an exception or don't return any results. try: exists = DT...
from openapi_python_client.cli import app if __name__ == "__main__": from .fastapi_app import generate_openapi_json generate_openapi_json() runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
from openapi_python_client.cli import app if __name__ == "__main__": runner = CliRunner() openapi_path = Path(__file__).parent / "fastapi_app" / "openapi.json" gm_path = Path(__file__).parent / "golden-master"
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str class Project: TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} project_name_override: Optional[str] = None package_name_override: Optional[str] = None
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{openapi.title.replace(' ', '-').low...
def __init__(self, *, openapi: GeneratorData) -> None: self.openapi: GeneratorData = openapi self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True) self.project_name: str = self.project_name_override or f"{utils.kebab_case(openapi.title).low...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): module_path = api_dir / f"{tag}.py" ...
def _build_api(self) -> None: endpoint_template = self.env.get_template("endpoint_module.pyi") async_endpoint_template = self.env.get_template("async_endpoint_module.pyi") for tag, collection in self.openapi.endpoint_collections_by_tag.items(): tag = utils.snake_case(tag) ...
import stringcase def snake_case(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return stringcase.snakecase(value) def pascal_case(value...
import stringcase def _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value) def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = mocker.MagicMock(autospec=str) tag_2 = mocker.MagicMock(autospec=str) collection_1 = mocker.MagicMock() ...
def test__build_api(self, mocker): from openapi_python_client import GeneratorData, Project openapi = mocker.MagicMock(autospec=GeneratorData, title="My Test API") tag_1 = "a_tag" tag_2 = "another_tag" collection_1 = mocker.MagicMock() collection_2 = mocker.MagicMock() ...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return en...
def env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "kebabcase": utils.kebab_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_spinal_case(): assert utils.spinal_case("keep_alive") == "keep-alive"
def test_snake_case_from_camel(): assert utils.snake_case("httpResponseLowerCamel") == "http_response_lower_camel" def test_kebab_case(): assert utils.kebab_case("keep_alive") == "keep-alive"
def to_categorical(y, num_classes=None): """ y = np.array(y, dtype='int') input_shape = y.shape y = y.ravel() if not num_classes: num_classes = np.max(y) + 1
def to_categorical(y, num_classes=None): """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1: input_shape = tuple(input_shape[:-1]) y = y.ravel() if not num_classes: num_classes = np.max(y) + 1
from keras.utils import to_categorical def test_to_categorical(): num_classes = 5 shapes = [(3,), (4, 3), (5, 4, 3)] labels = [np.random.randint(0, num_classes, shape) for shape in shapes] one_hots = [to_categorical(label, num_classes) for label in labels] for label, one_hot in zip(labels, one_hots...
from keras.utils import to_categorical def test_to_categorical(): num_classes = 5 shapes = [(3,), (4, 3), (5, 4, 3), (3, 1), (3, 2, 1)] expected_shapes = [(3, num_classes), (4, 3, num_classes), (5, 4, 3, num_classes), (3, num_classes)] ...
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', params={'value': value}) def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid', params={'value': value}) else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is...
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',...
def word_tokenize(self, s): return self._word_tokenizer_re().findall(s) _period_context_fmt = r""" \S* # some word material %(SentEndChars)s # a potential sentence ending (?=(?P<after_tok> %(NonWord)s # either other punct...
def word_tokenize(self, s): return self._word_tokenizer_re().findall(s) _period_context_fmt = r""" %(SentEndChars)s # a potential sentence ending (?=(?P<after_tok> %(NonWord)s # either other punctuation
def debug_decisions(self, text): See format_debug_decision() to help make this output readable. """ for match in self._lang_vars.period_context_re().finditer(text): decision_text = match.group() + match.group("after_tok") tokens = self._tokenize_words(decision_text) ...
def debug_decisions(self, text): See format_debug_decision() to help make this output readable. """ for match, decision_text in self._match_potential_end_contexts(text): tokens = self._tokenize_words(decision_text) tokens = list(self._annotate_first_pass(tokens)) ...
def sentences_from_text(self, text, realign_boundaries=True): """ return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] def _slices_from_text(self, text): last_break = 0 for match in self._lang_vars.period_context_re().finditer(text): context = matc...
def sentences_from_text(self, text, realign_boundaries=True): """ return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)] def _match_potential_end_contexts(self, text): """ Given a text, find the matches of potential sentence breaks, alongside the context...
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = assistant or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to the client, ...
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = (assistant and task.workers) or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to t...
class CentralPlannerTest(unittest.TestCase): self.assertEqual(list(running_tasks.keys()), ['A']) self.assertEqual(running_tasks['A']['worker_running'], 'Y') def test_task_fails_when_assistant_dies(self): self.setTime(0) self.sch.add_task(worker='X', task_id='A')
class CentralPlannerTest(unittest.TestCase): self.assertEqual(list(running_tasks.keys()), ['A']) self.assertEqual(running_tasks['A']['worker_running'], 'Y') def test_assistant_get_work_external_task(self): self.sch.add_task('X', task_id='A', runnable=False) self.assertTrue(self.sch....
from absl.testing import parameterized import numpy as np from tensorflow.python.dlpack import dlpack from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.platform import test from tensorflow.python.ops imp...
from absl.testing import parameterized import numpy as np from tensorflow.python.dlpack import dlpack from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.pla...
def UnsupportedComplex64(): self.assertRaisesRegex(Exception, ".* is not supported by dlpack", UnsupportedComplex64) if __name__ == "__main__": ops.enable_eager_execution()
def UnsupportedComplex64(): self.assertRaisesRegex(Exception, ".* is not supported by dlpack", UnsupportedComplex64) def testMustPassTensorArgumentToDLPack(self): with self.assertRaisesRegex( errors.InvalidArgumentError, "The argument to `to_dlpack` must be a TF ten...
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...
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value): # _strip_once was not able to detect more tags break value = new_value return value
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if value.count('<') == new_value.count('<'): # _strip_once wasn't able to detect more tags. break value = new_value return value
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ) for value, output in items: with self.subTest(value=value, output=output):
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'), ('X<<<<br>br>br>br>X', 'XX'),...
class Index(IndexOpsMixin, PandasObject): "unicode", "mixed", ]: return self._invalid_indexer("label", key) elif kind in ["loc"] and is_integer(key): if not self.holds_integer(): return self._inv...
class Index(IndexOpsMixin, PandasObject): "unicode", "mixed", ]: self._invalid_indexer("label", key) elif kind in ["loc"] and is_integer(key): if not self.holds_integer(): self._invalid_indexer("...
class CategoricalIndex(Index, accessor.PandasDelegate): @Appender(_index_shared_docs["_convert_scalar_indexer"]) def _convert_scalar_indexer(self, key, kind=None): if self.categories._defer_to_indexing: return self.categories._convert_scalar_indexer(key, kind=kind) return super()._...
class CategoricalIndex(Index, accessor.PandasDelegate): @Appender(_index_shared_docs["_convert_scalar_indexer"]) def _convert_scalar_indexer(self, key, kind=None): if kind == "loc": try: return self.categories._convert_scalar_indexer(key, kind=kind) except TypeEr...
from pandas import ( Index, Interval, Series, Timestamp, ) from pandas.api.types import CategoricalDtype as CDT import pandas.util.testing as tm
from pandas import ( Index, Interval, Series, Timedelta, Timestamp, conftest, ) from pandas.api.types import CategoricalDtype as CDT import pandas.util.testing as tm
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 def test_getitem_scalar(self): cats = Categorical([Timestamp("12-31-1999"), Timestamp("12-31-2000")])
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 msg = ( r"cannot do label indexing on <class 'pandas\.core\.indexes\.category" r"\.CategoricalIndex'> with these indexers \[1\] of <class 'int'>" ) with pytest...
class TestCategoricalIndex: output = cur_index.map(mapper) # Order of categories in output can be different tm.assert_index_equal(expected, output)
class TestCategoricalIndex: output = cur_index.map(mapper) # Order of categories in output can be different tm.assert_index_equal(expected, output) @pytest.mark.parametrize( "idx_values", [ # python types [1, 2, 3], [-1, -2, -3], ...
class TestFloatIndexers: idxr(s)[3.0] # label based can be a TypeError or KeyError if s.index.inferred_type in ["string", "unicode", "mixed"]: error = KeyError msg = r"^3$" else:
class TestFloatIndexers: idxr(s)[3.0] # label based can be a TypeError or KeyError if s.index.inferred_type in { "categorical", "string", "unicode", "mixed", }: ...
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): if self.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is deprecated; " "it w...
class Spider(object_ref): crawler.signals.connect(self.close, signals.spider_closed) def start_requests(self): cls = self.__class__ if cls.make_requests_from_url is not Spider.make_requests_from_url: warnings.warn( "Spider.make_requests_from_url method is depreca...
Sitemap: /sitemap-relative-url.xml 'http://www.example.com/sitemap-relative-url.xml']) class BaseSpiderDeprecationTest(unittest.TestCase): def test_basespider_is_deprecated(self): with warnings.catch_warnings(record=True) as w:
Sitemap: /sitemap-relative-url.xml 'http://www.example.com/sitemap-relative-url.xml']) class DeprecationTest(unittest.TestCase): def test_basespider_is_deprecated(self): with warnings.catch_warnings(record=True) as w:
class BaseSpiderDeprecationTest(unittest.TestCase): assert isinstance(CrawlSpider(name='foo'), Spider) assert isinstance(CrawlSpider(name='foo'), BaseSpider) if __name__ == '__main__': unittest.main()
class BaseSpiderDeprecationTest(unittest.TestCase): assert isinstance(CrawlSpider(name='foo'), Spider) assert isinstance(CrawlSpider(name='foo'), BaseSpider) def test_make_requests_from_url_deprecated(self): class MySpider4(Spider): name = 'spider1' start_urls = ['ht...
def read_json( dtype = True if convert_axes is None and orient != "table": convert_axes = True compression = _infer_compression(path_or_buf, compression) filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
def read_json( dtype = True if convert_axes is None and orient != "table": convert_axes = True if encoding is None: encoding = "utf-8" compression = _infer_compression(path_or_buf, compression) filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
def test_readjson_chunks_multiple_empty_lines(chunksize): tm.assert_frame_equal( orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize) )
def test_readjson_chunks_multiple_empty_lines(chunksize): tm.assert_frame_equal( orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize) ) def test_readjson_unicode(monkeypatch): with tm.ensure_clean("test.json") as path: monkeypatch.setattr("_bootlocale.getpreferredencoding",...
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msg_str(type_, yaml_str, filename=None): if yaml_str.strip() == '': msg_dict = {} else: msg_dict = yaml.safe_load(yaml_str) if not isinstance(msg_dict, dict): if filename: raise ValueError("yaml file [%s] does not contain a dictionary" % filename)
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
def yaml_msgs_str(type_, yaml_str, filename=None): @type filename: str """ import yaml yaml_doc = yaml.safe_load(yaml_str) msgs = [] for msg_dict in yaml_doc: if not isinstance(msg_dict, dict):
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(TestCase): ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal):
class TestNumberFormat(TestCase): ) 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'), ('9e...
import io import pytest from PIL import EpsImagePlugin, Image, features
import io import pytest from PIL import EpsImagePlugin, Image, features
def test_emptyline(): assert image.mode == "RGB" assert image.size == (460, 352) assert image.format == "EPS"
def test_emptyline(): assert image.mode == "RGB" assert image.size == (460, 352) assert image.format == "EPS" @pytest.mark.timeout(timeout=5) @pytest.mark.parametrize( "test_file", [ ("Tests/images/timeout-d675703545fee17acab56e5fec644c19979175de.eps") ], ) def test_timeout(test_file):...
class PSFile: self.fp.seek(offset, whence) def readline(self): s = self.char or b"" self.char = None c = self.fp.read(1) while c not in b"\r\n": s = s + c c = self.fp.read(1) self.char = self.fp.read(1)
class PSFile: self.fp.seek(offset, whence) def readline(self): s = [self.char or b""] self.char = None c = self.fp.read(1) while (c not in b"\r\n") and len(c): s.append(c) c = self.fp.read(1) self.char = self.fp.read(1)
class PSFile: if self.char in b"\r\n": self.char = None return s.decode("latin-1") def _accept(prefix):
class PSFile: if self.char in b"\r\n": self.char = None return b"".join(s).decode("latin-1") def _accept(prefix):
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, ...
import functools import http from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
import functools import hmac import http from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
def basic_auth_protocol_factory( if credentials is not None: if is_credentials(credentials): async def check_credentials(username: str, password: str) -> bool: return (username, password) == credentials elif isinstance(credentials, Iterable): credentials_li...
def basic_auth_protocol_factory( if credentials is not None: if is_credentials(credentials): credentials_list = [cast(Credentials, credentials)] elif isinstance(credentials, Iterable): credentials_list = list(credentials) if not all(is_credentials(item) for item ...
async def check_credentials(username: str, password: str) -> bool: ) return functools.partial( create_protocol, realm=realm, check_credentials=check_credentials )
async def check_credentials(username: str, password: str) -> bool: ) return functools.partial( create_protocol, realm=realm, check_credentials=check_credentials, )
import unittest import urllib.error
import hmac import unittest import urllib.error
def test_basic_auth_bad_multiple_credentials(self): ) async def check_credentials(username, password): return password == "iloveyou" create_protocol_check_credentials = basic_auth_protocol_factory( realm="auth-tests",
def test_basic_auth_bad_multiple_credentials(self): ) async def check_credentials(username, password): return hmac.compare_digest(password, "iloveyou") create_protocol_check_credentials = basic_auth_protocol_factory( realm="auth-tests",
def test_basic_auth_unsupported_credentials_details(self): self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n") @with_server(create_protocol=create_protocol) def test_basic_auth_invalid_credentials(self): with self.assertRaises(InvalidStatusCode) as raised: ...
def test_basic_auth_unsupported_credentials_details(self): self.assertEqual(raised.exception.read().decode(), "Unsupported credentials\n") @with_server(create_protocol=create_protocol) def test_basic_auth_invalid_username(self): with self.assertRaises(InvalidStatusCode) as raised: s...
import warnings from datetime import datetime from hashlib import sha256 from typing import List, Optional from unpaddedbase64 import encode_base64
import warnings from datetime import datetime from hashlib import sha256 from typing import List, Optional, Pattern from unpaddedbase64 import encode_base64
def read_config(self, config: dict, config_dir_path: str, **kwargs): fed_whitelist_entries = [] # Support globs (*) in whitelist values self.federation_certificate_verification_whitelist = [] # type: List[str] for entry in fed_whitelist_entries: try: ent...
def read_config(self, config: dict, config_dir_path: str, **kwargs): fed_whitelist_entries = [] # Support globs (*) in whitelist values self.federation_certificate_verification_whitelist = [] # type: List[Pattern] for entry in fed_whitelist_entries: try: ...
from synapse.events import EventBase from synapse.types import UserID from synapse.util.caches.lrucache import LruCache logger = logging.getLogger(__name__)
from synapse.events import EventBase from synapse.types import UserID from synapse.util import glob_to_regex, re_word_boundary from synapse.util.caches.lrucache import LruCache logger = logging.getLogger(__name__)
def _contains_display_name(self, display_name: str) -> bool: r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = _re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, ...
def _contains_display_name(self, display_name: str) -> bool: r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, T...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = _glob_to_re(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) exce...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = glob_to_regex(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) ex...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: return False def _glob_to_re(glob: str, word_boundary: bool) -> Pattern: """Generates regex for a given glob. Args: glob word_boundary: Whether to match against word boundaries or entire string. """ ...
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: return False def _flatten_dict( d: Union[EventBase, dict], prefix: Optional[List[str]] = None,
import json import logging import re import attr from frozendict import frozendict
import json import logging import re from typing import Pattern import attr from frozendict import frozendict
logger = logging.getLogger(__name__) def _reject_invalid_json(val): """Do not allow Infinity, -Infinity, or NaN values in JSON.""" raise ValueError("Invalid JSON value: '%s'" % val)
logger = logging.getLogger(__name__) _WILDCARD_RUN = re.compile(r"([\?\*]+)") def _reject_invalid_json(val): """Do not allow Infinity, -Infinity, or NaN values in JSON.""" raise ValueError("Invalid JSON value: '%s'" % val)
def log_failure(failure, msg, consumeErrors=True): return failure def glob_to_regex(glob): """Converts a glob to a compiled regex object. The regex is anchored at the beginning and end of the string. Args: glob (str) Returns: re.RegexObject """ res = "" for c in ...
def log_failure(failure, msg, consumeErrors=True): return failure def glob_to_regex(glob: str, word_boundary: bool = False) -> Pattern: """Converts a glob to a compiled regex object. Args: glob: pattern to match word_boundary: If True, the pattern will be allowed to match at word boun...
def test_block_ip_literals(self): self.assertFalse(server_matches_acl_event("[1:2::]", e)) self.assertTrue(server_matches_acl_event("1:2:3:4", e)) class StateQueryTests(unittest.FederatingHomeserverTestCase):
def test_block_ip_literals(self): self.assertFalse(server_matches_acl_event("[1:2::]", e)) self.assertTrue(server_matches_acl_event("1:2:3:4", e)) def test_wildcard_matching(self): e = _create_acl_event({"allow": ["good*.com"]}) self.assertTrue( server_matches_acl_event(...
# See the License for the specific language governing permissions and # limitations under the License. from synapse.api.room_versions import RoomVersions from synapse.events import FrozenEvent from synapse.push import push_rule_evaluator
# See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict from synapse.api.room_versions import RoomVersions from synapse.events import FrozenEvent from synapse.push import push_rule_evaluator
def test_display_name(self): # A display name with spaces should work fine. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar")) def test_no_body(self): """Not having a body shouldn't break the evaluator.""" evaluator = self._get_evaluator({})
def test_display_name(self): # A display name with spaces should work fine. self.assertTrue(evaluator.matches(condition, "@user:test", "foo bar")) def _assert_matches( self, condition: Dict[str, Any], content: Dict[str, Any], msg=None ) -> None: evaluator = self._get_evaluator(c...
def ret10_slice() -> Bytes[10]: assert c.ret10_slice() == b"A" def test_slice_convert(get_contract): # test slice of converting between bytes32 and Bytes code = """
def ret10_slice() -> Bytes[10]: assert c.ret10_slice() == b"A" def test_slice_equality(get_contract): # test for equality with dirty bytes code = """ @external def assert_eq() -> bool: dirty_bytes: String[4] = "abcd" dirty_bytes = slice(dirty_bytes, 0, 3) clean_bytes: String[4] = "abc" ret...
def test(a: uint256, b: String[50] = "foo") -> Bytes[100]: assert c.test(12345, "bar")[-3:] == b"bar" def test_string_equality(get_contract_with_gas_estimation): code = """ _compA: String[100] _compB: String[100] @external def equal_true() -> bool: compA: String[100] = "The quick brown fox jumps over the...
def test(a: uint256, b: String[50] = "foo") -> Bytes[100]: assert c.test(12345, "bar")[-3:] == b"bar" string_equality_tests = [ ( 100, "The quick brown fox jumps over the lazy dog", "The quick brown fox jumps over the lazy hog", ), # check <= 32 codepath (32, "abc", "abc\0"...
def compare_var_storage_not_equal_false() -> bool: assert c.storage_not_equal_true() is True assert c.storage_not_equal_false() is False a = "The quick brown fox jumps over the lazy dog" b = "The quick brown fox jumps over the lazy hog" assert c.string_compare_equal(a, a) is True assert c.strin...
def compare_var_storage_not_equal_false() -> bool: assert c.storage_not_equal_true() is True assert c.storage_not_equal_false() is False assert c.string_compare_equal(a, a) is True assert c.string_compare_equal(a, b) is False assert c.string_compare_not_equal(b, a) is True
def copy_bytes(dst, src, length, length_bound): with src.cache_when_complex("src") as (b1, src), length.cache_when_complex( "copy_bytes_count" ) as (b2, length,), dst.cache_when_complex("dst") as (b3, dst): # fast code for common case where num bytes is small # TODO expand this for mor...
def copy_bytes(dst, src, length, length_bound): with src.cache_when_complex("src") as (b1, src), length.cache_when_complex( "copy_bytes_count" ) as (b2, length), dst.cache_when_complex("dst") as (b3, dst): # fast code for common case where num bytes is small # TODO expand this for more...
from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE from vyper.codegen import external_call, self_call from vyper.codegen.core import ( LOAD, bytes_data_ptr, clamp_basetype, ensure_in_memory, get_dyn_array_count,
from vyper.address_space import DATA, IMMUTABLES, MEMORY, STORAGE from vyper.codegen import external_call, self_call from vyper.codegen.core import ( clamp_basetype, ensure_in_memory, get_dyn_array_count,
def parse_Compare(self): left = Expr(self.expr.left, self.context).ir_node right = Expr(self.expr.right, self.context).ir_node length_mismatch = left.typ.maxlen != right.typ.maxlen left_over_32 = left.typ.maxlen > 32 right_over_32 = right.typ.maxlen > 32 ...
def parse_Compare(self): left = Expr(self.expr.left, self.context).ir_node right = Expr(self.expr.right, self.context).ir_node left_keccak = keccak256_helper(self.expr, left, self.context) right_keccak = keccak256_helper(self.expr, right, self.context) if op...
from math import ceil from vyper.codegen.core import ensure_in_memory from vyper.codegen.ir_node import IRnode from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type from vyper.exceptions import CompilerPanic
from math import ceil from vyper.codegen.core import bytes_data_ptr, ensure_in_memory, get_bytearray_length from vyper.codegen.ir_node import IRnode from vyper.codegen.types import BaseType, ByteArrayLike, is_base_type from vyper.exceptions import CompilerPanic
def _gas_bound(num_words): return SHA3_BASE + num_words * SHA3_PER_WORD def keccak256_helper(expr, ir_arg, context): sub = ir_arg # TODO get rid of useless variable _check_byteslike(sub.typ, expr) # Can hash literals # TODO this is dead code. if isinstance(sub, bytes): return IRnode....
def _gas_bound(num_words): return SHA3_BASE + num_words * SHA3_PER_WORD def keccak256_helper(expr, to_hash, context): _check_byteslike(to_hash.typ, expr) # Can hash literals # TODO this is dead code. if isinstance(to_hash, bytes): return IRnode.from_list(bytes_to_int(keccak256(to_hash)), ...
import warnings import numpy as np from pandas._libs import NaT, algos as libalgos, lib, tslib, writers from pandas._libs.index import convert_scalar import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion
import warnings import numpy as np from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers from pandas._libs.index import convert_scalar import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion
class DatetimeLikeBlockMixin: # Override to return DatetimeArray and TimedeltaArray return self.array_values() class DatetimeBlock(DatetimeLikeBlockMixin, Block): __slots__ = ()
class DatetimeLikeBlockMixin: # Override to return DatetimeArray and TimedeltaArray return self.array_values() def iget(self, key): # GH#31649 we need to wrap scalars in Timestamp/Timedelta # TODO: this can be removed if we ever have 2D EA result = super().iget(key) ...
class TestDataFrameIndexingUInt64: df = result.set_index("foo") tm.assert_index_equal(df.index, idx)
class TestDataFrameIndexingUInt64: df = result.set_index("foo") tm.assert_index_equal(df.index, idx) def test_object_casting_indexing_wraps_datetimelike(): # GH#31649, check the indexing methods all the way down the stack df = pd.DataFrame( { "A": [1, 2], "B": ...
from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError,
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, str): exception_repr = message context = { 'request_path': quote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) class HandlerTests(SimpleTestCase):
from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) from django.utils.version import PY37 class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') ...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, ) if six.PY2: from urlparse import ( ParseResult, SplitRes...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def _is_safe_url(url, host): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.starts...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur...
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver...
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(...
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowExpire values: [] state: exact params: "{{ ldap_auth }}" """
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowExp...
modlist: """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native, to_bytes
modlist: """ import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native, to_bytes
def main(): module.fail_json( msg="Missing required 'ldap' module (pip install python-ldap)") # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): module.params.update(module.params['params']) ...
def main(): module.fail_json( msg="Missing required 'ldap' module (pip install python-ldap)") # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: modul...
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(params) parameter s...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. params: description: - List of options which allows to overwrite any of the task or the I(attributes) options. To remove an option, se...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. state: description: - The target state of the entry.
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent params: "{{ ldap_auth }}" """
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent args: "{{ ldap_au...
RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types
RETURN = """ """ import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import string_types
def main(): module.fail_json( msg="Missing required 'ldap' module (pip install python-ldap).") state = module.params['state'] # Check if objectClass is present when needed
def main(): module.fail_json( msg="Missing required 'ldap' module (pip install python-ldap).") # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: modu...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): for key, ...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Instantiate the LdapEntry object ldap = LdapEntry(module)