language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/copy_to_device_test.py
{ "start": 1732, "end": 22995 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.graph_only_combinations()) def testCopyToDevice(self): host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) self.assertEqual([], next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceHostOptimizations(self): host_dataset = dataset_ops.Dataset.range(10) host_dataset = host_dataset.apply(testing.assert_next(["MapAndBatch"])) host_dataset = host_dataset.map(lambda x: x*x).batch(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): self.assertAllEqual([x*x for x in range(10)], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceInt32(self): host_dataset = dataset_ops.Dataset.from_tensors([0, 1, 2, 3]) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int32, next_element.dtype) self.assertEqual((4,), next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): self.assertAllEqual([0, 1, 2, 3], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToSameDevice(self): host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:0")) with ops.device("/cpu:0"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) self.assertEqual([], next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceWithPrefetch(self): host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")).prefetch(1) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) self.assertEqual([], next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyDictToDevice(self): host_dataset = dataset_ops.Dataset.range(10).map(lambda x: {"a": x}) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element["a"].dtype) self.assertEqual([], next_element["a"].shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): self.assertEqual({"a": i}, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyDictToDeviceWithPrefetch(self): host_dataset = dataset_ops.Dataset.range(10).map(lambda x: {"a": x}) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")).prefetch(1) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element["a"].dtype) self.assertEqual([], next_element["a"].shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): self.assertEqual({"a": i}, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopySparseTensorsToDevice(self): def make_tensor(i): return sparse_tensor.SparseTensorValue( indices=[[0, 0]], values=(i * [1]), dense_shape=[2, 2]) host_dataset = dataset_ops.Dataset.range(10).map(make_tensor) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): actual = self.evaluate(next_element) self.assertAllEqual([i], actual.values) self.assertAllEqual([[0, 0]], actual.indices) self.assertAllEqual([2, 2], actual.dense_shape) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopySparseTensorsToDeviceWithPrefetch(self): def make_tensor(i): return sparse_tensor.SparseTensorValue( indices=[[0, 0]], values=(i * [1]), dense_shape=[2, 2]) host_dataset = dataset_ops.Dataset.range(10).map(make_tensor) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")).prefetch(1) with ops.device("/cpu:1"): iterator = dataset_ops.make_one_shot_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): for i in range(10): actual = self.evaluate(next_element) self.assertAllEqual([i], actual.values) self.assertAllEqual([[0, 0]], actual.indices) self.assertAllEqual([2, 2], actual.dense_shape) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.default_test_combinations()) def testCopyToDeviceGpu(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): self.assertDatasetProduces(device_dataset, list(range(10))) @combinations.generate(test_base.default_test_combinations()) def testCopyToDeviceGpuWithPrefetch(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")).prefetch(1) with ops.device("/gpu:0"): self.assertDatasetProduces(device_dataset, list(range(10))) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuWithMap(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") def generator(): for i in range(10): yield i, float(i), str(i) host_dataset = dataset_ops.Dataset.from_generator( generator, output_types=(dtypes.int32, dtypes.float32, dtypes.string)) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) def gpu_map_func(x, y, z): return math_ops.square(x), math_ops.square(y), z device_dataset = device_dataset.apply( prefetching_ops.map_on_gpu(gpu_map_func)) options = options_lib.Options() options.autotune.enabled = False device_dataset = device_dataset.with_options(options) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) for i in range(10): x, y, z = self.evaluate(next_element) self.assertEqual(i**2, x) self.assertEqual(float(i**2), y) self.assertEqual(util_compat.as_bytes(str(i)), z) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuInt32(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.from_tensors([0, 1, 2, 3]) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) self.assertAllEqual([0, 1, 2, 3], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuInt32AndPrefetch(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.from_tensors([0, 1, 2, 3]) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")).prefetch(1) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) self.assertAllEqual([0, 1, 2, 3], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuStrings(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.from_tensors(["a", "b", "c"]) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) self.assertAllEqual([b"a", b"b", b"c"], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuStringsAndPrefetch(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.from_tensors(["a", "b", "c"]) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) self.assertAllEqual([b"a", b"b", b"c"], self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDevicePingPongCPUGPU(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0", source_device="/cpu:0")) back_to_cpu_dataset = device_dataset.apply( prefetching_ops.copy_to_device("/cpu:0", source_device="/gpu:0")) with ops.device("/cpu:0"): iterator = dataset_ops.make_initializable_iterator(back_to_cpu_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceWithReInit(self): host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")) with ops.device("/cpu:1"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) self.assertEqual([], next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): self.evaluate(iterator.initializer) for i in range(5): self.assertEqual(i, self.evaluate(next_element)) self.evaluate(iterator.initializer) for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceWithReInitAndPrefetch(self): host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/cpu:1")).prefetch(1) with ops.device("/cpu:1"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() self.assertTrue( structure.are_compatible( dataset_ops.get_structure(host_dataset), dataset_ops.get_structure(device_dataset))) self.assertEqual(dtypes.int64, next_element.dtype) self.assertEqual([], next_element.shape) worker_config = config_pb2.ConfigProto(device_count={"CPU": 2}) with self.test_session(config=worker_config): self.evaluate(iterator.initializer) for i in range(5): self.assertEqual(i, self.evaluate(next_element)) self.evaluate(iterator.initializer) for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuWithReInit(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) for i in range(5): self.assertEqual(i, self.evaluate(next_element)) self.evaluate(iterator.initializer) for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testCopyToDeviceGpuWithReInitAndPrefetch(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(10) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")).prefetch(1) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_element = iterator.get_next() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): self.evaluate(iterator.initializer) for i in range(5): self.assertEqual(i, self.evaluate(next_element)) self.evaluate(iterator.initializer) for i in range(10): self.assertEqual(i, self.evaluate(next_element)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element) @combinations.generate(test_base.graph_only_combinations()) def testIteratorGetNextAsOptionalOnGPU(self): if not test_util.is_gpu_available(): self.skipTest("No GPU available") host_dataset = dataset_ops.Dataset.range(3) device_dataset = host_dataset.apply( prefetching_ops.copy_to_device("/gpu:0")) with ops.device("/gpu:0"): iterator = dataset_ops.make_initializable_iterator(device_dataset) next_elem = iterator_ops.get_next_as_optional(iterator) elem_has_value_t = next_elem.has_value() elem_value_t = next_elem.get_value() with self.cached_session( config=config_pb2.ConfigProto(allow_soft_placement=False)): # Before initializing the iterator, evaluating the optional fails with # a FailedPreconditionError. with self.assertRaises(errors.FailedPreconditionError): self.evaluate(elem_has_value_t) with self.assertRaises(errors.FailedPreconditionError): self.evaluate(elem_value_t) # For each element of the dataset, assert that the optional evaluates to # the expected value. self.evaluate(iterator.initializer) for i in range(3): elem_has_value, elem_value = self.evaluate( [elem_has_value_t, elem_value_t]) self.assertTrue(elem_has_value) self.assertEqual(i, elem_value) # After exhausting the iterator, `next_elem.has_value()` will evaluate to # false, and attempting to get the value will fail. for _ in range(2): self.assertFalse(self.evaluate(elem_has_value_t)) with self.assertRaises(errors.InvalidArgumentError): self.evaluate(elem_value_t) if __name__ == "__main__": test.main()
CopyToDeviceTest
python
readthedocs__readthedocs.org
readthedocs/invitations/tests/test_signals.py
{ "start": 285, "end": 1243 }
class ____(TestCase): def setUp(self): self.user = get(User) self.project = get(Project, users=[self.user]) self.organization = get( Organization, owners=[self.user], projects=[self.project] ) self.team = get(Team, organization=self.organization) self.another_user = get(User) for obj in [self.project, self.organization, self.team]: Invitation.objects.invite( from_user=self.user, obj=obj, to_user=self.another_user, ) def test_delete_related_object(self): self.assertEqual(Invitation.objects.all().count(), 3) self.project.delete() self.assertEqual(Invitation.objects.all().count(), 2) self.team.delete() self.assertEqual(Invitation.objects.all().count(), 1) self.organization.delete() self.assertEqual(Invitation.objects.all().count(), 0)
TestSignals
python
openai__openai-python
src/openai/resources/evals/evals.py
{ "start": 23721, "end": 24494 }
class ____: def __init__(self, evals: AsyncEvals) -> None: self._evals = evals self.create = _legacy_response.async_to_raw_response_wrapper( evals.create, ) self.retrieve = _legacy_response.async_to_raw_response_wrapper( evals.retrieve, ) self.update = _legacy_response.async_to_raw_response_wrapper( evals.update, ) self.list = _legacy_response.async_to_raw_response_wrapper( evals.list, ) self.delete = _legacy_response.async_to_raw_response_wrapper( evals.delete, ) @cached_property def runs(self) -> AsyncRunsWithRawResponse: return AsyncRunsWithRawResponse(self._evals.runs)
AsyncEvalsWithRawResponse
python
nedbat__coveragepy
tests/test_process.py
{ "start": 47679, "end": 48267 }
class ____(CoverageTest): """Test that empty files produce the proper fail_under exit status.""" def test_report(self) -> None: self.make_file(".coveragerc", "[report]\nfail_under = 99\n") self.make_file("empty.py", "") st, _ = self.run_command_status("coverage run empty.py") assert st == 0 st, _ = self.run_command_status("coverage report") # An empty file is marked as 100% covered, so this is ok. assert st == 0 @pytest.mark.skipif(env.WINDOWS, reason="Windows can't delete the directory in use.")
FailUnderEmptyFilesTest
python
django__django
tests/admin_inlines/admin.py
{ "start": 5034, "end": 5138 }
class ____(admin.StackedInline): model = Inner5Stacked classes = ("collapse",)
Inner5StackedInline
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 4448, "end": 4603 }
class ____(BaseModel): data: RunStep """Represents a step in execution of a run.""" event: Literal["thread.run.step.failed"]
ThreadRunStepFailed
python
Textualize__textual
docs/examples/guide/actions/actions07.py
{ "start": 196, "end": 1288 }
class ____(App): BINDINGS = [ ("n", "next", "Next"), ("p", "previous", "Previous"), ] CSS_PATH = "actions06.tcss" page_no = reactive(0, bindings=True) # (1)! def compose(self) -> ComposeResult: with HorizontalScroll(id="page-container"): for page_no in range(PAGES_COUNT): yield Placeholder(f"Page {page_no}", id=f"page-{page_no}") yield Footer() def action_next(self) -> None: self.page_no += 1 self.query_one(f"#page-{self.page_no}").scroll_visible() def action_previous(self) -> None: self.page_no -= 1 self.query_one(f"#page-{self.page_no}").scroll_visible() def check_action(self, action: str, parameters: tuple[object, ...]) -> bool | None: """Check if an action may run.""" if action == "next" and self.page_no == PAGES_COUNT - 1: return None # (2)! if action == "previous" and self.page_no == 0: return None # (3)! return True if __name__ == "__main__": app = PagesApp() app.run()
PagesApp
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 28187, "end": 30021 }
class ____(Mapping[str | AppKey[Any], Any]): __slots__ = ("_maps",) def __init__(self, maps: Iterable[Mapping[str | AppKey[Any], Any]]) -> None: self._maps = tuple(maps) def __init_subclass__(cls) -> None: raise TypeError( f"Inheritance class {cls.__name__} from ChainMapProxy is forbidden" ) @overload # type: ignore[override] def __getitem__(self, key: AppKey[_T]) -> _T: ... @overload def __getitem__(self, key: str) -> Any: ... def __getitem__(self, key: str | AppKey[_T]) -> Any: for mapping in self._maps: try: return mapping[key] except KeyError: pass raise KeyError(key) @overload # type: ignore[override] def get(self, key: AppKey[_T], default: _S) -> _T | _S: ... @overload def get(self, key: AppKey[_T], default: None = ...) -> _T | None: ... @overload def get(self, key: str, default: Any = ...) -> Any: ... def get(self, key: str | AppKey[_T], default: Any = None) -> Any: try: return self[key] except KeyError: return default def __len__(self) -> int: # reuses stored hash values if possible return len(set().union(*self._maps)) def __iter__(self) -> Iterator[str | AppKey[Any]]: d: dict[str | AppKey[Any], Any] = {} for mapping in reversed(self._maps): # reuses stored hash values if possible d.update(mapping) return iter(d) def __contains__(self, key: object) -> bool: return any(key in m for m in self._maps) def __bool__(self) -> bool: return any(self._maps) def __repr__(self) -> str: content = ", ".join(map(repr, self._maps)) return f"ChainMapProxy({content})"
ChainMapProxy
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_query.py
{ "start": 65741, "end": 69639 }
class ____(fixtures.TablesTest): """round trip tests related to using HSTORE in UPDATE statements with PG-specific features """ __only_on__ = "postgresql" __backend__ = True __requires__ = ("native_hstore",) @classmethod def define_tables(cls, metadata): Table( "t", metadata, Column("id", Integer, primary_key=True), Column("h", HSTORE), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables["t"].insert(), [ {"id": 1, "h": {"k1": "v1", "k2": "v2"}}, {"id": 2, "h": {"k3": "v3", "k4": "v4"}}, ], ) @testing.only_on("postgresql>=14") def test_hstore_element_update_basic(self, connection): """Test updating individual HSTORE elements with subscript syntax test #12948 """ t = self.tables["t"] # Insert test data with HSTORE connection.execute( t.insert(), [ { "id": 10, "h": {"name": "Alice", "status": "active"}, }, { "id": 11, "h": {"name": "Bob", "status": "inactive"}, }, ], ) # Update specific elements using HSTORE subscript syntax # This tests the new HSTORE subscripting feature from issue #12948 connection.execute( t.update() .values({t.c.h["name"]: "Alice Updated"}) .where(t.c.id == 10) ) connection.execute( t.update().values({t.c.h["status"]: "active"}).where(t.c.id == 11) ) results = connection.execute( t.select().where(t.c.id.in_([10, 11])).order_by(t.c.id) ) eq_( [row.h for row in results], [ {"name": "Alice Updated", "status": "active"}, {"name": "Bob", "status": "active"}, ], ) @testing.only_on("postgresql>=14") def test_hstore_element_update_multiple_keys(self, connection): """Test updating multiple HSTORE elements in a single statement test #12948 """ t = self.tables["t"] connection.execute( t.insert(), { "id": 20, "h": { "config_theme": "dark", "config_lang": "en", "version": "1", }, }, ) # Update multiple elements at once connection.execute( t.update() .values({t.c.h["config_theme"]: "light", t.c.h["version"]: "2"}) .where(t.c.id == 20) ) # Verify the updates row = connection.execute(t.select().where(t.c.id == 20)).one() eq_( row.h, {"config_theme": "light", "config_lang": "en", "version": "2"}, ) @testing.only_on("postgresql>=14") def test_hstore_element_update_new_key(self, connection): """Test adding new keys to HSTORE using subscript syntax test #12948 """ t = self.tables["t"] # Insert test data connection.execute( t.insert(), { "id": 30, "h": {"existing_key": "existing_value"}, }, ) # Add a new key using subscript syntax connection.execute( t.update() .values({t.c.h["new_key"]: "new_value"}) .where(t.c.id == 30) ) # Verify the update row = connection.execute(t.select().where(t.c.id == 30)).fetchone() eq_( row.h, {"existing_key": "existing_value", "new_key": "new_value"}, )
HstoreUpdateTest
python
readthedocs__readthedocs.org
readthedocs/organizations/views/private.py
{ "start": 3332, "end": 4280 }
class ____(ListOrganization): template_name = "organizations/organization_choose.html" def get(self, request, *args, **kwargs): self.next_name = self.kwargs["next_name"] self.next_querystring = self.request.GET.get("next_querystring") # Check if user has exactly 1 organization and automatically redirect in this case organizations = self.get_queryset() if organizations.count() == 1: redirect_url = reverse(self.next_name, kwargs={"slug": organizations[0].slug}) if self.next_querystring: redirect_url += "?" + urlencode(self.next_querystring) return redirect(redirect_url) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): c = super().get_context_data(**kwargs) c["next_name"] = self.next_name c["next_querystring"] = self.next_querystring return c
ChooseOrganization
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 44832, "end": 45242 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("invitation_id", "client_mutation_id") invitation_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="invitationId" ) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
AcceptEnterpriseAdministratorInvitationInput
python
numba__numba
numba/core/typing/builtins.py
{ "start": 16293, "end": 16602 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws ptr, idx, val = args if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer): return signature(types.none, ptr, normalize_1d_index(idx), ptr.dtype) @infer_global(len)
SetItemCPointer
python
simplejson__simplejson
simplejson/tests/test_separators.py
{ "start": 75, "end": 942 }
class ____(TestCase): def test_separators(self): h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False} ] expect = textwrap.dedent("""\ [ [ "blorpie" ] , [ "whoops" ] , [] , "d-shtaeou" , "d-nthiouh" , "i-vhbjkhnth" , { "nifty" : 87 } , { "field" : "yes" , "morefield" : false } ]""") d1 = json.dumps(h) d2 = json.dumps(h, indent=' ', sort_keys=True, separators=(' ,', ' : ')) h1 = json.loads(d1) h2 = json.loads(d2) self.assertEqual(h1, h) self.assertEqual(h2, h) self.assertEqual(d2, expect)
TestSeparators
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 11056, "end": 11327 }
class ____(LinalgTestCase): def test_sq_cases(self): self.check_cases(require={"square"}, exclude={"generalized", "size-0"}) def test_empty_sq_cases(self): self.check_cases(require={"square", "size-0"}, exclude={"generalized"})
LinalgSquareTestCase
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-groups-with-increasing-length.py
{ "start": 78, "end": 1329 }
class ____(object): def maxIncreasingGroups(self, usageLimits): """ :type usageLimits: List[int] :rtype: int """ def inplace_counting_sort(nums, reverse=False): # Time: O(n) if not nums: return count = [0]*(max(nums)+1) for num in nums: count[num] += 1 for i in xrange(1, len(count)): count[i] += count[i-1] for i in reversed(xrange(len(nums))): # inplace but unstable sort while nums[i] >= 0: count[nums[i]] -= 1 j = count[nums[i]] nums[i], nums[j] = nums[j], ~nums[i] for i in xrange(len(nums)): nums[i] = ~nums[i] # restore values if reverse: # unstable sort nums.reverse() usageLimits = [min(x, len(usageLimits)) for x in usageLimits] inplace_counting_sort(usageLimits) result = curr = 0 for x in usageLimits: curr += x if curr >= result+1: curr -= result+1 result += 1 return result # Time: O(nlogn) # Space: O(1) # constructive algorithms, sort, greedy
Solution
python
ray-project__ray
python/ray/tests/test_actor_advanced.py
{ "start": 15203, "end": 15280 }
class ____: def foo(self): return "bar" @ray.remote
NonDetachedActor
python
getsentry__sentry
tests/sentry/integrations/models/test_integrationfeature.py
{ "start": 213, "end": 1090 }
class ____(TestCase): def setUp(self) -> None: self.sentry_app = self.create_sentry_app() self.integration_feature = IntegrationFeature.objects.get( target_id=self.sentry_app.id, target_type=IntegrationTypes.SENTRY_APP.value ) def test_feature_str(self) -> None: assert self.integration_feature.feature_str() == "integrations-api" def test_description(self) -> None: assert ( self.integration_feature.description == "%s can **utilize the Sentry API** to pull data or update resources in Sentry (with permissions granted, of course)." % self.sentry_app.name ) self.integration_feature.user_description = "Custom description" self.integration_feature.save() assert self.integration_feature.description == "Custom description"
IntegrationFeatureTest
python
tensorflow__tensorflow
tensorflow/python/client/session_partial_run_test.py
{ "start": 1198, "end": 11282 }
class ____(test_util.TensorFlowTestCase): def RunTestPartialRun(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(r1, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) self.assertEqual(3, res) temp = res * 17 res = sess.partial_run(h, r2, feed_dict={c: temp}) self.assertEqual(153, res) # Call again on the same graph. h2 = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h2, r1, feed_dict={a: 1, b: 2}) self.assertEqual(3, res) temp = res * 18 res = sess.partial_run(h2, r2, feed_dict={c: temp}) self.assertEqual(162, res) def RunTestPartialRunIncomplete(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(r1, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) self.assertEqual(3, res) def RunTestConcurrentPartialRun(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(r1, c) h1 = sess.partial_run_setup([r1], [a, b, c]) h2 = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h1, r1, feed_dict={a: 1, b: 2}) self.assertEqual(3, res) temp = res * 19 res = sess.partial_run(h2, r1, feed_dict={a: temp, b: 9}) self.assertEqual(66, res) res = sess.partial_run(h2, r2, feed_dict={c: 7}) self.assertEqual(462, res) def RunTestManyPartialRun(self, sess): steps = 200 inputs = [] outputs = [] a = constant_op.constant(2.0, dtypes.float32) for i in range(steps): inputs.append(array_ops.placeholder(dtypes.float32, shape=[])) a = math_ops.multiply(a, inputs[i]) outputs.append(a) h = sess.partial_run_setup(outputs, inputs) for i in range(steps): res = sess.partial_run(h, outputs[i], feed_dict={inputs[i]: 1.0}) self.assertEqual(2.0, res) feed_dict = {} for i in range(steps): feed_dict[inputs[i]] = 1.0 res = sess.run(outputs, feed_dict) self.assertEqual(steps, len(res)) self.assertEqual(2.0, res[-1]) def RunTestRunAndPartialRun(self, sess): a = constant_op.constant(2.0, dtypes.float32) b = a * 2 c = b * 3 r1 = self.evaluate([b, c]) h = sess.partial_run_setup([b, c], []) r2 = sess.partial_run(h, [b, c]) self.assertEqual(r1, r2) def RunTestPartialRunMissingPlaceholderFeedException(self, sess): x = array_ops.placeholder(dtypes.float32, shape=()) fetches = [x * 2, x * 3] handle = sess.partial_run_setup(fetches=fetches, feeds=[]) with self.assertRaisesRegex(errors.InvalidArgumentError, 'You must feed a value for placeholder'): sess.partial_run(handle, fetches[0]) def RunTestPartialRunUnspecifiedFeed(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) h = sess.partial_run_setup([r1], [a, b]) with self.assertRaisesRegex(errors.InvalidArgumentError, 'was not specified in partial_run_setup.$'): sess.partial_run(h, r1, feed_dict={a: 1, b: 2, c: 3}) def RunTestPartialRunUnspecifiedFetch(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(a, c) h = sess.partial_run_setup([r1], [a, b, c]) with self.assertRaisesRegex(errors.InvalidArgumentError, 'was not specified in partial_run_setup.$'): sess.partial_run(h, r2, feed_dict={a: 1, c: 3}) def RunTestPartialRunAlreadyFed(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(a, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) with self.assertRaisesRegex(errors.InvalidArgumentError, 'has already been fed.$'): sess.partial_run(h, r2, feed_dict={a: 1, c: 3}) def RunTestPartialRunAlreadyFetched(self, sess): a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(a, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) with self.assertRaisesRegex(errors.InvalidArgumentError, 'has already been fetched.$'): sess.partial_run(h, r1, feed_dict={c: 3}) def RunTestPartialRunEmptyFetches(self, sess): a = array_ops.placeholder(dtypes.float32) b = a * 2.0 h = sess.partial_run_setup(fetches=[b], feeds=[a]) sess.partial_run(h, [], {a: 3.0}) r = sess.partial_run(h, [b], {}) self.assertEqual([6.0], r) @test_util.run_deprecated_v1 def testInvalidPartialRunSetup(self): sess = session.Session() x = array_ops.placeholder(dtypes.float32, shape=[]) with self.assertRaisesRegex( errors.InvalidArgumentError, 'specify at least one target to fetch or execute.'): sess.partial_run_setup(fetches=[], feeds=[x]) @test_util.run_deprecated_v1 def testPartialRunSetupNoFeedsPassed(self): sess = session.Session() r1 = constant_op.constant([6.0]) h = sess.partial_run_setup([r1]) result1 = sess.partial_run(h, r1) self.assertEqual([6.0], result1) @test_util.run_deprecated_v1 def testPartialRunDirect(self): self.RunTestPartialRun(session.Session()) @test_util.run_deprecated_v1 def testPartialRunIncompleteDirect(self): self.RunTestPartialRunIncomplete(session.Session()) @test_util.run_deprecated_v1 def testConcurrentPartialRunDirect(self): self.RunTestConcurrentPartialRun(session.Session()) @test_util.run_deprecated_v1 def testManyPartialRunDirect(self): self.RunTestManyPartialRun(session.Session()) @test_util.run_deprecated_v1 def testRunAndPartialRunDirect(self): self.RunTestRunAndPartialRun(session.Session()) @test_util.run_deprecated_v1 def testPartialRunMissingPlaceholderFeedExceptionDirect(self): self.RunTestPartialRunMissingPlaceholderFeedException(session.Session()) @test_util.run_deprecated_v1 def testPartialRunUnspecifiedFeedDirect(self): self.RunTestPartialRunUnspecifiedFeed(session.Session()) @test_util.run_deprecated_v1 def testPartialRunUnspecifiedFetchDirect(self): self.RunTestPartialRunUnspecifiedFetch(session.Session()) @test_util.run_deprecated_v1 def testPartialRunAlreadyFedDirect(self): self.RunTestPartialRunAlreadyFed(session.Session()) @test_util.run_deprecated_v1 def testPartialRunAlreadyFetchedDirect(self): self.RunTestPartialRunAlreadyFetched(session.Session()) @test_util.run_deprecated_v1 def testPartialRunEmptyFetchesDirect(self): self.RunTestPartialRunEmptyFetches(session.Session()) @test_util.run_deprecated_v1 def testPartialRunDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRun(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunIncompleteDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunIncomplete(session.Session(server.target)) @test_util.run_deprecated_v1 def testConcurrentPartialRunDist(self): server = server_lib.Server.create_local_server() self.RunTestConcurrentPartialRun(session.Session(server.target)) @test_util.run_deprecated_v1 def testManyPartialRunDist(self): server = server_lib.Server.create_local_server() self.RunTestManyPartialRun(session.Session(server.target)) @test_util.run_deprecated_v1 def testRunAndPartialRunDist(self): server = server_lib.Server.create_local_server() self.RunTestRunAndPartialRun(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunMissingPlaceholderFeedExceptionDist(self): self.skipTest('Flaky test. Short term b/278768411, long term b/280102873') server = server_lib.Server.create_local_server() self.RunTestPartialRunMissingPlaceholderFeedException( session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunUnspecifiedFeedDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunUnspecifiedFeed(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunUnspecifiedFetchDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunUnspecifiedFetch(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunAlreadyFedDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunAlreadyFed(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunAlreadyFetchedDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunAlreadyFetched(session.Session(server.target)) @test_util.run_deprecated_v1 def testPartialRunEmptyFetchesDist(self): server = server_lib.Server.create_local_server() self.RunTestPartialRunEmptyFetches(session.Session(server.target)) if __name__ == '__main__': googletest.main()
PartialRunTest
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_generator_stop.py
{ "start": 1537, "end": 2412 }
class ____(__TestCase): def test_stopiteration_wrapping(self): def f(): raise StopIteration def g(): yield f() with self.assertRaisesRegex(RuntimeError, "generator raised StopIteration"): next(g()) def test_stopiteration_wrapping_context(self): def f(): raise StopIteration def g(): yield f() try: next(g()) except RuntimeError as exc: self.assertIs(type(exc.__cause__), StopIteration) self.assertIs(type(exc.__context__), StopIteration) self.assertTrue(exc.__suppress_context__) else: self.fail('__cause__, __context__, or __suppress_context__ ' 'were not properly set') if __name__ == "__main__": run_tests()
TestPEP479
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/unitofwork.py
{ "start": 4904, "end": 16948 }
class ____: """Manages the internal state of a unit of work flush operation.""" session: Session transaction: SessionTransaction attributes: Dict[str, Any] deps: util.defaultdict[Mapper[Any], Set[_DependencyProcessor]] mappers: util.defaultdict[Mapper[Any], Set[InstanceState[Any]]] def __init__(self, session: Session): self.session = session # dictionary used by external actors to # store arbitrary state information. self.attributes = {} # dictionary of mappers to sets of # DependencyProcessors, which are also # set to be part of the sorted flush actions, # which have that mapper as a parent. self.deps = util.defaultdict(set) # dictionary of mappers to sets of InstanceState # items pending for flush which have that mapper # as a parent. self.mappers = util.defaultdict(set) # a dictionary of Preprocess objects, which gather # additional states impacted by the flush # and determine if a flush action is needed self.presort_actions = {} # dictionary of PostSortRec objects, each # one issues work during the flush within # a certain ordering. self.postsort_actions = {} # a set of 2-tuples, each containing two # PostSortRec objects where the second # is dependent on the first being executed # first self.dependencies = set() # dictionary of InstanceState-> (isdelete, listonly) # tuples, indicating if this state is to be deleted # or insert/updated, or just refreshed self.states = {} # tracks InstanceStates which will be receiving # a "post update" call. Keys are mappers, # values are a set of states and a set of the # columns which should be included in the update. self.post_update_states = util.defaultdict(lambda: (set(), set())) @property def has_work(self): return bool(self.states) def was_already_deleted(self, state): """Return ``True`` if the given state is expired and was deleted previously. """ if state.expired: try: state._load_expired(state, attributes.PASSIVE_OFF) except orm_exc.ObjectDeletedError: self.session._remove_newly_deleted([state]) return True return False def is_deleted(self, state): """Return ``True`` if the given state is marked as deleted within this uowtransaction.""" return state in self.states and self.states[state][0] def memo(self, key, callable_): if key in self.attributes: return self.attributes[key] else: self.attributes[key] = ret = callable_() return ret def remove_state_actions(self, state): """Remove pending actions for a state from the uowtransaction.""" isdelete = self.states[state][0] self.states[state] = (isdelete, True) def get_attribute_history( self, state, key, passive=attributes.PASSIVE_NO_INITIALIZE ): """Facade to attributes.get_state_history(), including caching of results.""" hashkey = ("history", state, key) # cache the objects, not the states; the strong reference here # prevents newly loaded objects from being dereferenced during the # flush process if hashkey in self.attributes: history, state_history, cached_passive = self.attributes[hashkey] # if the cached lookup was "passive" and now # we want non-passive, do a non-passive lookup and re-cache if ( not cached_passive & attributes.SQL_OK and passive & attributes.SQL_OK ): impl = state.manager[key].impl history = impl.get_history( state, state.dict, attributes.PASSIVE_OFF | attributes.LOAD_AGAINST_COMMITTED | attributes.NO_RAISE, ) if history and impl.uses_objects: state_history = history.as_state() else: state_history = history self.attributes[hashkey] = (history, state_history, passive) else: impl = state.manager[key].impl # TODO: store the history as (state, object) tuples # so we don't have to keep converting here history = impl.get_history( state, state.dict, passive | attributes.LOAD_AGAINST_COMMITTED | attributes.NO_RAISE, ) if history and impl.uses_objects: state_history = history.as_state() else: state_history = history self.attributes[hashkey] = (history, state_history, passive) return state_history def has_dep(self, processor): return (processor, True) in self.presort_actions def register_preprocessor(self, processor, fromparent): key = (processor, fromparent) if key not in self.presort_actions: self.presort_actions[key] = _Preprocess(processor, fromparent) def register_object( self, state: InstanceState[Any], isdelete: bool = False, listonly: bool = False, cancel_delete: bool = False, operation: Optional[str] = None, prop: Optional[MapperProperty] = None, ) -> bool: if not self.session._contains_state(state): # this condition is normal when objects are registered # as part of a relationship cascade operation. it should # not occur for the top-level register from Session.flush(). if not state.deleted and operation is not None: util.warn( "Object of type %s not in session, %s operation " "along '%s' will not proceed" % (orm_util.state_class_str(state), operation, prop) ) return False if state not in self.states: mapper = state.manager.mapper if mapper not in self.mappers: self._per_mapper_flush_actions(mapper) self.mappers[mapper].add(state) self.states[state] = (isdelete, listonly) else: if not listonly and (isdelete or cancel_delete): self.states[state] = (isdelete, False) return True def register_post_update(self, state, post_update_cols): mapper = state.manager.mapper.base_mapper states, cols = self.post_update_states[mapper] states.add(state) cols.update(post_update_cols) def _per_mapper_flush_actions(self, mapper): saves = _SaveUpdateAll(self, mapper.base_mapper) deletes = _DeleteAll(self, mapper.base_mapper) self.dependencies.add((saves, deletes)) for dep in mapper._dependency_processors: dep.per_property_preprocessors(self) for prop in mapper.relationships: if prop.viewonly: continue dep = prop._dependency_processor dep.per_property_preprocessors(self) @util.memoized_property def _mapper_for_dep(self): """return a dynamic mapping of (Mapper, DependencyProcessor) to True or False, indicating if the DependencyProcessor operates on objects of that Mapper. The result is stored in the dictionary persistently once calculated. """ return util.PopulateDict( lambda tup: tup[0]._props.get(tup[1].key) is tup[1].prop ) def filter_states_for_dep(self, dep, states): """Filter the given list of InstanceStates to those relevant to the given DependencyProcessor. """ mapper_for_dep = self._mapper_for_dep return [s for s in states if mapper_for_dep[(s.manager.mapper, dep)]] def states_for_mapper_hierarchy(self, mapper, isdelete, listonly): checktup = (isdelete, listonly) for mapper in mapper.base_mapper.self_and_descendants: for state in self.mappers[mapper]: if self.states[state] == checktup: yield state def _generate_actions(self): """Generate the full, unsorted collection of PostSortRecs as well as dependency pairs for this UOWTransaction. """ # execute presort_actions, until all states # have been processed. a presort_action might # add new states to the uow. while True: ret = False for action in list(self.presort_actions.values()): if action.execute(self): ret = True if not ret: break # see if the graph of mapper dependencies has cycles. self.cycles = cycles = topological.find_cycles( self.dependencies, list(self.postsort_actions.values()) ) if cycles: # if yes, break the per-mapper actions into # per-state actions convert = { rec: set(rec.per_state_flush_actions(self)) for rec in cycles } # rewrite the existing dependencies to point to # the per-state actions for those per-mapper actions # that were broken up. for edge in list(self.dependencies): if ( None in edge or edge[0].disabled or edge[1].disabled or cycles.issuperset(edge) ): self.dependencies.remove(edge) elif edge[0] in cycles: self.dependencies.remove(edge) for dep in convert[edge[0]]: self.dependencies.add((dep, edge[1])) elif edge[1] in cycles: self.dependencies.remove(edge) for dep in convert[edge[1]]: self.dependencies.add((edge[0], dep)) return { a for a in self.postsort_actions.values() if not a.disabled }.difference(cycles) def execute(self) -> None: postsort_actions = self._generate_actions() postsort_actions = sorted( postsort_actions, key=lambda item: item.sort_key, ) # sort = topological.sort(self.dependencies, postsort_actions) # print "--------------" # print "\ndependencies:", self.dependencies # print "\ncycles:", self.cycles # print "\nsort:", list(sort) # print "\nCOUNT OF POSTSORT ACTIONS", len(postsort_actions) # execute if self.cycles: for subset in topological.sort_as_subsets( self.dependencies, postsort_actions ): set_ = set(subset) while set_: n = set_.pop() n.execute_aggregate(self, set_) else: for rec in topological.sort(self.dependencies, postsort_actions): rec.execute(self) def finalize_flush_changes(self) -> None: """Mark processed objects as clean / deleted after a successful flush(). This method is called within the flush() method after the execute() method has succeeded and the transaction has been committed. """ if not self.states: return states = set(self.states) isdel = { s for (s, (isdelete, listonly)) in self.states.items() if isdelete } other = states.difference(isdel) if isdel: self.session._remove_newly_deleted(isdel) if other: self.session._register_persistent(other)
UOWTransaction
python
networkx__networkx
networkx/classes/tests/test_graph.py
{ "start": 28519, "end": 31105 }
class ____: """Unit tests for the :meth:`Graph.edge_subgraph` method.""" def setup_method(self): # Create a path graph on five nodes. G = nx.path_graph(5) # Add some node, edge, and graph attributes. for i in range(5): G.nodes[i]["name"] = f"node{i}" G.edges[0, 1]["name"] = "edge01" G.edges[3, 4]["name"] = "edge34" G.graph["name"] = "graph" # Get the subgraph induced by the first and last edges. self.G = G self.H = G.edge_subgraph([(0, 1), (3, 4)]) def test_correct_nodes(self): """Tests that the subgraph has the correct nodes.""" assert [0, 1, 3, 4] == sorted(self.H.nodes()) def test_correct_edges(self): """Tests that the subgraph has the correct edges.""" assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name")) def test_add_node(self): """Tests that adding a node to the original graph does not affect the nodes of the subgraph. """ self.G.add_node(5) assert [0, 1, 3, 4] == sorted(self.H.nodes()) def test_remove_node(self): """Tests that removing a node in the original graph does affect the nodes of the subgraph. """ self.G.remove_node(0) assert [1, 3, 4] == sorted(self.H.nodes()) def test_node_attr_dict(self): """Tests that the node attribute dictionary of the two graphs is the same object. """ for v in self.H: assert self.G.nodes[v] == self.H.nodes[v] # Making a change to G should make a change in H and vice versa. self.G.nodes[0]["name"] = "foo" assert self.G.nodes[0] == self.H.nodes[0] self.H.nodes[1]["name"] = "bar" assert self.G.nodes[1] == self.H.nodes[1] def test_edge_attr_dict(self): """Tests that the edge attribute dictionary of the two graphs is the same object. """ for u, v in self.H.edges(): assert self.G.edges[u, v] == self.H.edges[u, v] # Making a change to G should make a change in H and vice versa. self.G.edges[0, 1]["name"] = "foo" assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"] self.H.edges[3, 4]["name"] = "bar" assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"] def test_graph_attr_dict(self): """Tests that the graph attribute dictionary of the two graphs is the same object. """ assert self.G.graph is self.H.graph
TestEdgeSubgraph
python
eventlet__eventlet
tests/greendns_test.py
{ "start": 17084, "end": 19872 }
class ____(tests.LimitedTestCase): def setUp(self): base_resolver = _make_mock_base_resolver() base_resolver.rr.target = 'cname.example.com' self._old_resolver = greendns.resolver greendns.resolver = base_resolver() def tearDown(self): greendns.resolver = self._old_resolver def test_success(self): cname = greendns.resolve_cname('alias.example.com') assert cname == 'cname.example.com' def test_timeout(self): greendns.resolver.raises = greendns.dns.exception.Timeout with tests.assert_raises(socket.gaierror): greendns.resolve_cname('alias.example.com') def test_nodata(self): greendns.resolver.raises = greendns.dns.exception.DNSException with tests.assert_raises(socket.gaierror): greendns.resolve_cname('alias.example.com') def test_no_answer(self): greendns.resolver.raises = greendns.dns.resolver.NoAnswer assert greendns.resolve_cname('host.example.com') == 'host.example.com' def _make_mock_resolve(): """A stubbed out resolve function This monkeypatches the greendns.resolve() function with a mock. You must give it answers by calling .add(). """ class MockAnswer(list): pass class MockResolve: def __init__(self): self.answers = {} def __call__(self, name, family=socket.AF_INET, raises=True, _proxy=None, use_network=True): qname = dns.name.from_text(name) try: rrset = self.answers[name][family] except KeyError: if raises: raise greendns.dns.resolver.NoAnswer() rrset = dns.rrset.RRset(qname, 1, 1) ans = MockAnswer() ans.qname = qname ans.rrset = rrset ans.extend(rrset.items) return ans def add(self, name, addr): """Add an address to a name and family""" try: rdata = dns.rdtypes.IN.A.A(dns.rdataclass.IN, dns.rdatatype.A, addr) family = socket.AF_INET except (OSError, dns.exception.SyntaxError): rdata = dns.rdtypes.IN.AAAA.AAAA(dns.rdataclass.IN, dns.rdatatype.AAAA, addr) family = socket.AF_INET6 family_dict = self.answers.setdefault(name, {}) rrset = family_dict.get(family) if not rrset: family_dict[family] = rrset = dns.rrset.RRset( dns.name.from_text(name), rdata.rdclass, rdata.rdtype) rrset.add(rdata) resolve = MockResolve() return resolve
TestResolveCname
python
huggingface__transformers
src/transformers/models/gpt_oss/modular_gpt_oss.py
{ "start": 10911, "end": 13695 }
class ____(Qwen2Attention): def __init__(self, config: GptOssConfig, layer_idx: int): super().__init__(config, layer_idx) self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) self.sinks = nn.Parameter(torch.empty(config.num_attention_heads)) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: cache_kwargs = {"cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=self.sliding_window, position_ids=position_ids, s_aux=self.sinks, # diff with Llama **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
GptOssAttention
python
google__jax
jax/_src/pallas/mosaic/tpu_info.py
{ "start": 852, "end": 1137 }
class ____(ChipVersionBase, enum.Enum): TPU_V2 = "v2" TPU_V3 = "v3" TPU_V4I = "v4i" TPU_V4 = "v4" TPU_V5E = "v5e" TPU_V5P = "v5p" TPU_V6E = "v6e" TPU_7X = "7x" def __str__(self) -> str: return self.value @dataclasses.dataclass(frozen=True, kw_only=True)
ChipVersion
python
pytorch__pytorch
torch/_dynamo/replay_record.py
{ "start": 1267, "end": 1955 }
class ____: code: CodeType closure: tuple[CellType] globals: dict[str, Any] = field(default_factory=dict) locals: dict[str, Any] = field(default_factory=dict) builtins: dict[str, Any] = field(default_factory=dict) code_options: dict[str, Any] = field(default_factory=dict) def dump(self, f: Union[IO[str], BufferedWriter]) -> None: assert dill is not None, "replay_record requires `pip install dill`" dill.dump(self, f) @classmethod def load(cls, f: Union[IO[bytes], BufferedReader]) -> Self: assert dill is not None, "replay_record requires `pip install dill`" return dill.load(f) @dataclasses.dataclass
ExecutionRecord
python
pytorch__pytorch
test/distributed/fsdp/test_wrap.py
{ "start": 14440, "end": 35587 }
class ____(TestCase): def setUp(self) -> None: super().setUp() # For all the tests here, we use a fake group self.process_group = DummyProcessGroup(rank=0, size=1) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") @parametrize("wrap_method", [WrapMethod.FSDP_CTOR, WrapMethod.WRAP_API]) def test_wrap(self, wrap_method): if wrap_method == WrapMethod.WRAP_API: with enable_wrap(wrapper_cls=FSDP, process_group=self.process_group): layer = wrap(nn.Linear(5, 5)) else: assert wrap_method == WrapMethod.FSDP_CTOR layer = FSDP( nn.Linear(5, 5), process_group=self.process_group, auto_wrap_policy=functools.partial( size_based_auto_wrap_policy, min_num_params=1 ), ) self.assertTrue(isinstance(layer, FSDP)) self.assertEqual(layer.rank, self.process_group.rank()) self.assertEqual(layer.world_size, self.process_group.size()) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_wrap_disabled_outside_context(self): pg = self.process_group class MyModel(nn.Module): def __init__(self) -> None: super().__init__() self.lin = wrap(nn.Linear(5, 5), process_group=pg) model = MyModel() with enable_wrap(wrapper_cls=FSDP, process_group=pg): model = wrap(model) self.assertTrue(isinstance(model, FSDP)) self.assertFalse(isinstance(model.lin, FSDP)) self.assertTrue(isinstance(model.lin, nn.Linear)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_wrap_override_defaults(self): new_process_group = DummyProcessGroup(rank=0, size=2) with enable_wrap(wrapper_cls=FSDP, process_group=self.process_group): layer = wrap(nn.Linear(5, 5), process_group=new_process_group) self.assertTrue(isinstance(layer, FSDP)) self.assertTrue(layer.process_group is new_process_group) self.assertEqual(layer.rank, 0) self.assertEqual(layer.world_size, 2) @unittest.skipIf(not TEST_CUDA and not TEST_XPU, "Test Requires CUDA or XPU") def test_always_wrap(self): """ Test to ensure that if `always_wrap_policy` is passed into FSDP, all submodules are wrapped. """ seq = TestFSDPWrap.NestedSequentialModel.get_model(device=True) model = FSDP( seq, process_group=self.process_group, auto_wrap_policy=always_wrap_policy ) TestFSDPWrap.NestedSequentialModel.verify_model_all_wrapped(self, model) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_transformer_auto_wrap_policy(self): """Tests the ``transformer_auto_wrap_policy``.""" auto_wrap_policy = functools.partial( transformer_auto_wrap_policy, transformer_layer_cls={TransformerEncoderLayer, TransformerDecoderLayer}, ) self._test_transformer_wrapping(auto_wrap_policy) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_module_wrap_policy(self): """Tests the ``ModuleWrapPolicy``.""" auto_wrap_policy = ModuleWrapPolicy( {TransformerEncoderLayer, TransformerDecoderLayer} ) self._test_transformer_wrapping(auto_wrap_policy) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_module_wrap_policy_callable(self): """Tests the ``ModuleWrapPolicy`` as a ``Callable``.""" auto_wrap_policy = ModuleWrapPolicy( {TransformerEncoderLayer, TransformerDecoderLayer} ) callable_policy = functools.partial(_or_policy, policies=[auto_wrap_policy]) self._test_transformer_wrapping(callable_policy) def _test_transformer_wrapping(self, auto_wrap_policy: Union[Callable, _Policy]): fsdp_kwargs = {"auto_wrap_policy": auto_wrap_policy} fsdp_model = TransformerWithSharedParams.init( self.process_group, FSDPInitMode.RECURSIVE, DEVICEInitMode.DEVICE_BEFORE, fsdp_kwargs, ) modules = list(fsdp_model.modules()) encoder_layers = set(fsdp_model.module.transformer.encoder.layers) decoder_layers = set(fsdp_model.module.transformer.decoder.layers) for module in modules: if ( module is fsdp_model or module in encoder_layers or module in decoder_layers ): self.assertTrue(isinstance(module, FSDP)) else: self.assertFalse(isinstance(module, FSDP)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_custom_policy(self): """ Tests ``CustomPolicy`` with both a lambda function that uses uniform kwargs (so only returns ``False`` or ``True``) and a lambda function that uses non-uniform kwargs (so returns a dict to override the root kwargs). """ for use_uniform_kwargs in [False, True]: self._test_custom_policy(use_uniform_kwargs) def _test_custom_policy(self, use_uniform_kwargs: bool): print(f"use_uniform_kwargs={use_uniform_kwargs}") model = TransformerWithSharedParams.init( self.process_group, FSDPInitMode.NO_FSDP, DEVICEInitMode.DEVICE_BEFORE, {}, ) if use_uniform_kwargs: def lambda_fn(module: nn.Module): if module is model.bn: return True elif isinstance( module, (TransformerEncoderLayer, TransformerDecoderLayer) ): return True return False else: def lambda_fn(module: nn.Module): if module is model.bn: return {"sharding_strategy": ShardingStrategy.NO_SHARD} elif isinstance(module, TransformerEncoderLayer): return True elif isinstance(module, TransformerDecoderLayer): return { "sharding_strategy": ShardingStrategy.SHARD_GRAD_OP, "backward_prefetch": BackwardPrefetch.BACKWARD_POST, } return False policy = CustomPolicy(lambda_fn) # Use a size-2 dummy PG to avoid clamping the sharding strategy to # `NO_SHARD` as for a size-1 PG process_group = DummyProcessGroup(rank=0, size=2) fp16_mp = MixedPrecision(param_dtype=torch.float16) fp32_mp = MixedPrecision() model = FSDP( model, process_group=process_group, auto_wrap_policy=policy, mixed_precision=fp16_mp, ) encoder_layers = set(model.module.transformer.encoder.layers) decoder_layers = set(model.module.transformer.decoder.layers) bn = model.module.bn bn_strategy = ( ShardingStrategy.FULL_SHARD if use_uniform_kwargs else ShardingStrategy.NO_SHARD ) bn_prefetch = BackwardPrefetch.BACKWARD_PRE encoder_strategy = root_strategy = ShardingStrategy.FULL_SHARD encoder_prefetch = root_prefetch = BackwardPrefetch.BACKWARD_PRE decoder_strategy = ( ShardingStrategy.FULL_SHARD if use_uniform_kwargs else ShardingStrategy.SHARD_GRAD_OP ) decoder_prefetch = ( BackwardPrefetch.BACKWARD_PRE if use_uniform_kwargs else BackwardPrefetch.BACKWARD_POST ) for module in model.modules(): if module is bn: self.assertTrue(isinstance(module, FSDP)) self.assertEqual(module.sharding_strategy, bn_strategy) self.assertEqual(module.backward_prefetch, bn_prefetch) # We currently override batch norm modules to use fp32 self.assertEqual(module.mixed_precision, fp32_mp) elif module in encoder_layers: self.assertTrue(isinstance(module, FSDP)) self.assertEqual(module.sharding_strategy, encoder_strategy) self.assertEqual(module.backward_prefetch, encoder_prefetch) self.assertEqual(module.mixed_precision, fp16_mp) elif module in decoder_layers: self.assertTrue(isinstance(module, FSDP)) self.assertEqual(module.sharding_strategy, decoder_strategy) self.assertEqual(module.backward_prefetch, decoder_prefetch) self.assertEqual(module.mixed_precision, fp16_mp) elif module is model: self.assertTrue(isinstance(module, FSDP)) self.assertEqual(module.sharding_strategy, root_strategy) self.assertEqual(module.backward_prefetch, root_prefetch) self.assertEqual(module.mixed_precision, fp16_mp) else: self.assertFalse(isinstance(module, FSDP)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_auto_wrap_api(self): """ Test to ensure with auto wrap, we wrap child modules correctly based on the min_num_params. ``nn.Linear(5, 5)`` does not exceed the bucket size, but combined they do. """ sequential = TestFSDPWrap.NestedSequentialModel.get_model(device=False) my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40 ) model = FSDP( sequential, process_group=self.process_group, auto_wrap_policy=my_auto_wrap_policy, ) TestFSDPWrap.NestedSequentialModel.verify_model(self, model) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_auto_wrap_preset_exclude_wrap(self): """ Test to ensure excluded modules are not wrapped, regardless if the total param size is greater than the min_num_params. the size_based_auto_wrap_policy excludes wrapping for {nn.ModuleList, nn.ModuleDict} """ sequential = nn.ModuleList([nn.Linear(5, 5), nn.Linear(5, 5)]) my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40 ) model = FSDP( sequential, process_group=self.process_group, auto_wrap_policy=my_auto_wrap_policy, ) self.assertTrue(isinstance(model, FSDP)) self.assertTrue(isinstance(model[0], nn.Linear)) self.assertTrue(isinstance(model[1], nn.Linear)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_auto_wrap_preset_exclude_wrap_include_children(self): """ Test to ensure excluded modules are not wrapped, but children are if param size is greater than min_num_params """ sequential = nn.ModuleList([nn.Linear(10, 10)]) my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40 ) model = FSDP( sequential, process_group=self.process_group, auto_wrap_policy=my_auto_wrap_policy, ) self.assertTrue(isinstance(model, FSDP)) self.assertTrue(isinstance(model[0], FSDP)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_auto_wrap_preset_force_leaf(self): """ Test to ensure force-leaf modules are not wrapped, and children are not wrapped. The size_based_auto_wrap_policy forces leaf modules of type {nn.MultiheadAttention} to not be wrapped """ sequential = nn.Sequential(nn.Linear(10, 10), nn.MultiheadAttention(100, 1)) my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40 ) model = FSDP( sequential, process_group=self.process_group, auto_wrap_policy=my_auto_wrap_policy, ) self.assertTrue(isinstance(model.module[0], FSDP)) # Assert children of multihead attention are not wrapped self.assertTrue(isinstance(model.module[1], nn.MultiheadAttention)) self.assertTrue(isinstance(model.module[1].out_proj, nn.Linear)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_auto_wrap_preset_force_leaf_custom(self): """ Test to ensure force-leaf modules are not wrapped. """ my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40, force_leaf_modules=size_based_auto_wrap_policy.FORCE_LEAF_MODULES.union( {nn.Linear} ), ) sequential = nn.Sequential( nn.Linear(10, 10), nn.ModuleList([nn.Linear(10, 10)]) ) model = FSDP( sequential, process_group=self.process_group, auto_wrap_policy=my_auto_wrap_policy, ) # Model was wrapped in FSDP as no inner modules were wrapped. self.assertTrue(isinstance(model, FSDP)) self.assertTrue(isinstance(model.module[0], nn.Linear)) self.assertTrue(isinstance(model.module[1], nn.ModuleList)) @unittest.skipIf(not TEST_CUDA and not TEST_XPU, "Test Requires CUDA or XPU") @parametrize( "device_init_mode", [DEVICEInitMode.DEVICE_BEFORE, DEVICEInitMode.DEVICE_AFTER] ) @parametrize( "cpu_offload", [CPUOffload(offload_params=False), CPUOffload(offload_params=True)], ) @parametrize("use_device_id", [True, False]) def test_auto_wrap_smoke_test(self, device_init_mode, cpu_offload, use_device_id): # CPU offload and CUDA after don't work together as expected. if ( cpu_offload.offload_params and device_init_mode == DEVICEInitMode.DEVICE_AFTER ): return device = torch.device(device_type) torch.accelerator.set_device_index(0) device_id = ( torch.device(device_type, torch.accelerator.current_device_index()) if use_device_id else None ) # Random port in case the next test run quickly, same port would cause conflict. os.environ["MASTER_ADDR"] = "localhost" os.environ["MASTER_PORT"] = str(find_free_port()) file_name = tempfile.NamedTemporaryFile(delete=False).name torch.distributed.init_process_group( backend=backend, init_method=f"{FILE_SCHEMA}_{file_name}", rank=0, world_size=1, ) # NOTE: We move model to GPU after init with FSDP to simulate real use # cases where full model cannot be loaded onto GPU, but their shards can. device_after_init = device_init_mode == DEVICEInitMode.DEVICE_AFTER try: sequential = TestFSDPWrap.NestedSequentialModel.get_model( device=(not device_after_init) ) my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40 ) model = FSDP( sequential, cpu_offload=cpu_offload, auto_wrap_policy=my_auto_wrap_policy, device_id=device_id, ) TestFSDPWrap.NestedSequentialModel.verify_model(self, model) if device_after_init: model = model.to(device=device_type) input = torch.rand((1, 5), dtype=torch.float).to(device) output = model(input) loss = F.mse_loss(input, output) loss.backward() finally: torch.distributed.destroy_process_group() try: os.remove(file_name) except FileNotFoundError: pass @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") @parametrize("wrap_method", [WrapMethod.FSDP_CTOR, WrapMethod.WRAP_API]) def test_always_wrap_with_ignored_modules(self, wrap_method: WrapMethod): sequential = TestFSDPWrap.NestedSequentialModel.get_model(device=False) ignored_modules = [sequential[1], sequential[2][0]] fsdp_kwargs = { "process_group": self.process_group, "auto_wrap_policy": always_wrap_policy, "ignored_modules": ignored_modules, } if wrap_method == WrapMethod.FSDP_CTOR: model = FSDP(sequential, **fsdp_kwargs) elif wrap_method == WrapMethod.WRAP_API: with enable_wrap(wrapper_cls=FSDP, **fsdp_kwargs): model = wrap(sequential) else: assert 0, f"Unsupported wrap method: {wrap_method}" # All non-ignored modules should be wrapped with FSDP self.assertTrue(isinstance(model, FSDP)) self.assertTrue(isinstance(model.module[0], FSDP)) self.assertTrue(isinstance(model.module[1], nn.Linear)) self.assertTrue(isinstance(model.module[2], FSDP)) self.assertTrue(isinstance(model.module[2].module[0], nn.Linear)) self.assertTrue(isinstance(model.module[2].module[1], FSDP)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") @parametrize("wrap_method", [WrapMethod.FSDP_CTOR, WrapMethod.WRAP_API]) def test_auto_wrap_with_ignored_modules(self, wrap_method: WrapMethod): sequential = TestFSDPWrap.NestedSequentialModel.get_model(device=False) ignored_modules = [sequential[1], sequential[2][0]] my_auto_wrap_policy = functools.partial( size_based_auto_wrap_policy, min_num_params=40, ) fsdp_kwargs = { "process_group": self.process_group, "auto_wrap_policy": my_auto_wrap_policy, "ignored_modules": ignored_modules, } if wrap_method == WrapMethod.FSDP_CTOR: model = FSDP(sequential, **fsdp_kwargs) elif wrap_method == WrapMethod.WRAP_API: with enable_wrap(wrapper_cls=FSDP, **fsdp_kwargs): model = wrap(sequential) else: assert 0, f"Unsupported wrap method: {wrap_method}" # Since the 2nd linear (`sequential[1]`) is ignored, the wrapping # policy does not exceed the parameter threshold before the inner # sequential (`sequential[2]`) anymore; hence, it flattens # `sequential[0]` and `sequential[2][0]` into `model` and leaves # `sequential[1]` and `sequential[2][1]` as-is since they are ignored self.assertTrue(isinstance(model, FSDP)) self.assertTrue(isinstance(model.module[0], nn.Linear)) self.assertTrue(isinstance(model.module[1], nn.Linear)) self.assertTrue(isinstance(model.module[2], nn.Sequential)) self.assertTrue(isinstance(model.module[2][0], nn.Linear)) self.assertTrue(isinstance(model.module[2][1], nn.Linear)) @unittest.skipIf(not TEST_MULTIGPU, "Requires at least 2 GPUs") def test_frozen_params(self): """ Tests that mixing frozen/non-frozen parameters in an FSDP instance raises for ``use_orig_params=False`` and warns for ``True``. """ module_classes = (LoraAttention, LoraMLP, LoraDecoder) module_wrap_policy = ModuleWrapPolicy(module_classes) def lambda_fn_uniform(module: nn.Module): return isinstance(module, module_classes) def lambda_fn_nonuniform(module: nn.Module): if isinstance(module, LoraAttention): return {"sharding_strategy": ShardingStrategy.SHARD_GRAD_OP} elif isinstance(module, module_classes): return True return False lambda_wrap_policy_uniform = CustomPolicy(lambda_fn_uniform) lambda_wrap_policy_nonuniform = CustomPolicy(lambda_fn_nonuniform) for use_orig_params, policy in itertools.product( [True, False], [ module_wrap_policy, lambda_wrap_policy_uniform, lambda_wrap_policy_nonuniform, ], ): self._test_frozen_params(use_orig_params, policy) def _test_frozen_params(self, use_orig_params: bool, policy: _Policy): model = LoraModel().to(device=device_type) msg = "layers.0.attn has both parameters with requires_grad=True and False. " if use_orig_params: msg += "We do not recommend wrapping such modules" ctx = self.assertWarnsRegex(UserWarning, msg) else: msg += "FSDP does not support wrapping such modules when use_orig_params=False." ctx = self.assertRaisesRegex(ValueError, msg) with ctx: FSDP( model, process_group=self.process_group, auto_wrap_policy=policy, use_orig_params=use_orig_params, )
TestAutoWrap
python
py-pdf__pypdf
pypdf/generic/_base.py
{ "start": 7021, "end": 8388 }
class ____(PdfObject): def clone( self, pdf_dest: PdfWriterProtocol, force_duplicate: bool = False, ignore_fields: Optional[Sequence[Union[str, int]]] = (), ) -> "NullObject": """Clone object into pdf_dest.""" return cast( "NullObject", self._reference_clone(NullObject(), pdf_dest, force_duplicate) ) def hash_bin(self) -> int: """ Used to detect modified object. Returns: Hash considering type and value. """ return hash((self.__class__,)) def write_to_stream( self, stream: StreamType, encryption_key: Union[None, str, bytes] = None ) -> None: if encryption_key is not None: # deprecated deprecation_no_replacement( "the encryption_key parameter of write_to_stream", "5.0.0" ) stream.write(b"null") @staticmethod def read_from_stream(stream: StreamType) -> "NullObject": nulltxt = stream.read(4) if nulltxt != b"null": raise PdfReadError("Could not read Null object") return NullObject() def __repr__(self) -> str: return "NullObject" def __eq__(self, other: object) -> bool: return isinstance(other, NullObject) def __hash__(self) -> int: return self.hash_bin()
NullObject
python
streamlit__streamlit
lib/streamlit/dataframe_util.py
{ "start": 4746, "end": 5231 }
class ____(Protocol[V_co]): """Technically not a GenericAlias, but serves the same purpose in OptionSequence below, in that it is a type which admits DataFrame, but is generic. This allows OptionSequence to be a fully generic type, significantly increasing its usefulness. We can't use types.GenericAlias, as it is only available from python>=3.9, and isn't easily back-ported. """ @property def iloc(self) -> _iLocIndexer: ...
DataFrameGenericAlias
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 47237, "end": 47790 }
class ____: def test_rewrite_python_files_contain_subdirs(self, pytester: Pytester) -> None: pytester.makepyfile( **{ "tests/file.py": """ def test_simple_failure(): assert 1 + 1 == 3 """ } ) pytester.makeini( """ [pytest] python_files = tests/**.py """ ) result = pytester.runpytest() result.stdout.fnmatch_lines(["*E*assert (1 + 1) == 3"])
TestIssue2121
python
gevent__gevent
src/gevent/libev/watcher.py
{ "start": 7085, "end": 7790 }
class ____(_base.ChildMixin, watcher): _watcher_type = 'child' def close(self): # Capture the properties we defer to our _watcher, because # we're about to discard it. closed_watcher = _ClosedWatcher(self._watcher) super(child, self).close() self._watcher = closed_watcher @property def pid(self): return self._watcher.pid @property def rpid(self): return self._watcher.rpid @rpid.setter def rpid(self, value): self._watcher.rpid = value @property def rstatus(self): return self._watcher.rstatus @rstatus.setter def rstatus(self, value): self._watcher.rstatus = value
child
python
getsentry__sentry
src/sentry/stacktraces/processing.py
{ "start": 1435, "end": 3100 }
class ____: def __init__(self, frame, idx, processor, stacktrace_info, processable_frames): self.frame = frame self.idx = idx self.processor = processor self.stacktrace_info = stacktrace_info self.data = None self.cache_key = None self.cache_value = None self.processable_frames = processable_frames def __repr__(self) -> str: return "<ProcessableFrame {!r} #{!r} at {!r}>".format( self.frame.get("function") or "unknown", self.idx, self.frame.get("instruction_addr"), ) def __contains__(self, key): return key in self.frame def __getitem__(self, key): return self.frame[key] def get(self, key, default=None): return self.frame.get(key, default) def close(self): # manually break circular references self.closed = True self.processable_frames = None self.stacktrace_info = None self.processor = None @property def previous_frame(self): last_idx = len(self.processable_frames) - self.idx - 1 - 1 if last_idx < 0: return return self.processable_frames[last_idx] def set_cache_value(self, value): if self.cache_key is not None: cache.set(self.cache_key, value, 3600) return True return False def set_cache_key_from_values(self, values): if values is None: self.cache_key = None return h = hash_values(values, seed=self.processor.__class__.__name__) self.cache_key = rv = "pf:%s" % h return rv
ProcessableFrame
python
getsentry__sentry
src/sentry/issues/endpoints/project_stacktrace_link.py
{ "start": 3983, "end": 8467 }
class ____(ProjectEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } """ Returns valid links for source code providers so that users can go from the file in the stack trace to the provider of their choice. `file`: The file path from the stack trace `commitId` (optional): The commit_id for the last commit of the release associated to the stack trace's event `sdkName` (optional): The sdk.name associated with the event `absPath` (optional): The abs_path field value of the relevant stack frame `module` (optional): The module field value of the relevant stack frame `package` (optional): The package field value of the relevant stack frame `groupId` (optional): The Issue's id. """ owner = ApiOwner.ISSUES def get(self, request: Request, project: Project) -> Response: ctx = generate_context(request.GET) filepath = ctx["file"] if not filepath: return Response({"detail": "Filepath is required"}, status=400) integrations = integration_service.get_integrations(organization_id=project.organization_id) # TODO(meredith): should use get_provider.has_feature() instead once this is # no longer feature gated and is added as an IntegrationFeature serializer = IntegrationSerializer() serialized_integrations = [ serialize(i, request.user, serializer) for i in integrations if i.has_feature(IntegrationFeatures.STACKTRACE_LINK) ] configs = get_sorted_code_mapping_configs(project) if not configs: return Response( { "config": None, "sourceUrl": None, "integrations": serialized_integrations, "error": "no_code_mappings_for_project", } ) attempted_url = None error = None serialized_config = None scope = Scope.get_isolation_scope() set_top_tags(scope, project, ctx, len(configs) > 0) result = get_stacktrace_config(configs, ctx) error = result["error"] src_path = result["src_path"] # Post-processing before exiting scope context if result["current_config"]: # Use the provider key to split up stacktrace-link metrics by integration type serialized_config = serialize(result["current_config"]["config"], request.user) provider = serialized_config["provider"]["key"] scope.set_tag("integration_provider", provider) # e.g. github if not result["source_url"]: error = result["current_config"]["outcome"].get("error") # When no code mapping have been matched we have not attempted a URL if result["current_config"]["outcome"].get("attemptedUrl"): attempted_url = result["current_config"]["outcome"]["attemptedUrl"] try: set_tags(scope, result, serialized_integrations) except Exception: logger.exception("Failed to set tags.") if result["current_config"] and serialized_config: analytics.record( IntegrationStacktraceLinkEvent( provider=serialized_config["provider"]["key"], config_id=serialized_config["id"], project_id=project.id, organization_id=project.organization_id, filepath=filepath, status=error or "success", link_fetch_iterations=result["iteration_count"], platform=ctx["platform"], ) ) return Response( { "error": error, "config": serialized_config, "sourcePath": src_path, "sourceUrl": result["source_url"], "attemptedUrl": attempted_url, "integrations": serialized_integrations, } ) return Response( { "error": error, "config": serialized_config, "sourcePath": src_path, "sourceUrl": None, "attemptedUrl": attempted_url, "integrations": serialized_integrations, } )
ProjectStacktraceLinkEndpoint
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_pie02.py
{ "start": 315, "end": 1273 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_pie02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "pie"}) data = [ [2, 4, 6], [60, 30, 10], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$3", "values": "=Sheet1!$B$1:$B$3", } ) chart.set_legend({"font": {"bold": 1, "italic": 1, "baseline": -1}}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 7124, "end": 9667 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): Contrastive loss for speech-text similarity. speech_ids (`torch.LongTensor`, *optional*): speech_ids (or speech candidates) generated by the `ClvpForCausalLM` model. logits_per_speech (`torch.FloatTensor` of shape `(speech_batch_size, text_batch_size)`): The scaled dot product scores between `speech_embeds` and `text_embeds`. This represents the speech-text similarity scores. logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, speech_batch_size)`): The scaled dot product scores between `text_embeds` and `speech_embeds`. This represents the text-speech similarity scores. text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of the text encoder model. speech_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`): The speech embeddings obtained by applying the projection layer to the pooled output of the speech encoder model. text_model_output (`BaseModelOutputWithPooling`): The pooled output of the `last_hidden_state` of the text encoder Model. speech_model_output (`BaseModelOutputWithPooling`): The pooled output of the `last_hidden_state` of the speech encoder Model. decoder_hidden_states (`torch.FloatTensor`, *optional*): The hidden states of the decoder model. text_encoder_hidden_states (`torch.FloatTensor`, *optional*): The hidden states of the text encoder model. speech_encoder_hidden_states (`torch.FloatTensor`, *optional*): The hidden states of the speech encoder model. """ loss: Optional[torch.FloatTensor] = None speech_ids: Optional[torch.LongTensor] = None logits_per_speech: Optional[torch.FloatTensor] = None logits_per_text: Optional[torch.FloatTensor] = None text_embeds: Optional[torch.FloatTensor] = None speech_embeds: Optional[torch.FloatTensor] = None text_model_output: BaseModelOutputWithPooling = None speech_model_output: BaseModelOutputWithPooling = None decoder_hidden_states: Optional[torch.FloatTensor] = None text_encoder_hidden_states: Optional[torch.FloatTensor] = None speech_encoder_hidden_states: Optional[torch.FloatTensor] = None # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Clvp
ClvpOutput
python
walkccc__LeetCode
solutions/1218. Longest Arithmetic Subsequence of Given Difference/1218.py
{ "start": 0, "end": 243 }
class ____: def longestSubsequence(self, arr: list[int], difference: int) -> int: ans = 0 lengthAt = {} for a in arr: lengthAt[a] = lengthAt.get(a - difference, 0) + 1 ans = max(ans, lengthAt[a]) return ans
Solution
python
sqlalchemy__sqlalchemy
test/dialect/mysql/test_query.py
{ "start": 11794, "end": 15426 }
class ____(fixtures.MappedTest): __only_on__ = "mysql >= 5.7", "mariadb" __backend__ = True @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column("id", Integer, primary_key=True), Column("name", String(32)), Column("age_int", Integer), ) @classmethod def setup_classes(cls): class User(cls.Comparable): pass @classmethod def insert_data(cls, connection): users = cls.tables.users connection.execute( users.insert(), [ dict(id=1, name="john", age_int=25), dict(id=2, name="jack", age_int=47), dict(id=3, name="jill", age_int=29), dict(id=4, name="jane", age_int=37), ], ) @classmethod def setup_mappers(cls): User = cls.classes.User users = cls.tables.users cls.mapper_registry.map_imperatively( User, users, properties={ "age": users.c.age_int, }, ) def test_update_limit_orm_select(self): User = self.classes.User s = fixture_session() with self.sql_execution_asserter() as asserter: s.execute( update(User) .where(User.name.startswith("j")) .ext(limit(2)) .values({"age": User.age + 3}) ) asserter.assert_( CompiledSQL( "UPDATE users SET age_int=(users.age_int + %s) " "WHERE (users.name LIKE concat(%s, '%%')) " "LIMIT __[POSTCOMPILE_param_1]", [{"age_int_1": 3, "name_1": "j", "param_1": 2}], dialect="mysql", ), ) def test_delete_limit_orm_select(self): User = self.classes.User s = fixture_session() with self.sql_execution_asserter() as asserter: s.execute( delete(User).where(User.name.startswith("j")).ext(limit(2)) ) asserter.assert_( CompiledSQL( "DELETE FROM users WHERE (users.name LIKE concat(%s, '%%')) " "LIMIT __[POSTCOMPILE_param_1]", [{"name_1": "j", "param_1": 2}], dialect="mysql", ), ) def test_update_limit_legacy_query(self): User = self.classes.User s = fixture_session() with self.sql_execution_asserter() as asserter: s.query(User).where(User.name.startswith("j")).ext( limit(2) ).update({"age": User.age + 3}) asserter.assert_( CompiledSQL( "UPDATE users SET age_int=(users.age_int + %s) " "WHERE (users.name LIKE concat(%s, '%%')) " "LIMIT __[POSTCOMPILE_param_1]", [{"age_int_1": 3, "name_1": "j", "param_1": 2}], dialect="mysql", ), ) def test_delete_limit_legacy_query(self): User = self.classes.User s = fixture_session() with self.sql_execution_asserter() as asserter: s.query(User).where(User.name.startswith("j")).ext( limit(2) ).delete() asserter.assert_( CompiledSQL( "DELETE FROM users WHERE (users.name LIKE concat(%s, '%%')) " "LIMIT __[POSTCOMPILE_param_1]", [{"name_1": "j", "param_1": 2}], dialect="mysql", ), )
LimitORMTest
python
django__django
django/contrib/sessions/exceptions.py
{ "start": 171, "end": 272 }
class ____(SuspiciousOperation): """The session may be tampered with""" pass
SuspiciousSession
python
scikit-learn__scikit-learn
sklearn/tests/test_base.py
{ "start": 18678, "end": 26710 }
class ____(BaseEstimator): def __init__(self, attribute_pickled=5): self.attribute_pickled = attribute_pickled self._attribute_not_pickled = None def __getstate__(self): state = super().__getstate__() state["_attribute_not_pickled"] = None return state def test_pickling_works_when_getstate_is_overwritten_in_the_child_class(): estimator = SingleInheritanceEstimator() estimator._attribute_not_pickled = "this attribute should not be pickled" serialized = pickle.dumps(estimator) estimator_restored = pickle.loads(serialized) assert estimator_restored.attribute_pickled == 5 assert estimator_restored._attribute_not_pickled is None def test_tag_inheritance(): # test that changing tags by inheritance is not allowed nan_tag_est = NaNTag() no_nan_tag_est = NoNaNTag() assert nan_tag_est.__sklearn_tags__().input_tags.allow_nan assert not no_nan_tag_est.__sklearn_tags__().input_tags.allow_nan redefine_tags_est = OverrideTag() assert not redefine_tags_est.__sklearn_tags__().input_tags.allow_nan diamond_tag_est = DiamondOverwriteTag() assert diamond_tag_est.__sklearn_tags__().input_tags.allow_nan inherit_diamond_tag_est = InheritDiamondOverwriteTag() assert inherit_diamond_tag_est.__sklearn_tags__().input_tags.allow_nan def test_raises_on_get_params_non_attribute(): class MyEstimator(BaseEstimator): def __init__(self, param=5): pass def fit(self, X, y=None): return self est = MyEstimator() msg = "'MyEstimator' object has no attribute 'param'" with pytest.raises(AttributeError, match=msg): est.get_params() def test_repr_mimebundle_(): # Checks the display configuration flag controls the json output tree = DecisionTreeClassifier() output = tree._repr_mimebundle_() assert "text/plain" in output assert "text/html" in output with config_context(display="text"): output = tree._repr_mimebundle_() assert "text/plain" in output assert "text/html" not in output def test_repr_html_wraps(): # Checks the display configuration flag controls the html output tree = DecisionTreeClassifier() output = tree._repr_html_() assert "<style>" in output with config_context(display="text"): msg = "_repr_html_ is only defined when" with pytest.raises(AttributeError, match=msg): output = tree._repr_html_() def test_n_features_in_validation(): """Check that `_check_n_features` validates data when reset=False""" est = MyEstimator() X_train = [[1, 2, 3], [4, 5, 6]] _check_n_features(est, X_train, reset=True) assert est.n_features_in_ == 3 msg = "X does not contain any features, but MyEstimator is expecting 3 features" with pytest.raises(ValueError, match=msg): _check_n_features(est, "invalid X", reset=False) def test_n_features_in_no_validation(): """Check that `_check_n_features` does not validate data when n_features_in_ is not defined.""" est = MyEstimator() _check_n_features(est, "invalid X", reset=True) assert not hasattr(est, "n_features_in_") # does not raise _check_n_features(est, "invalid X", reset=False) def test_feature_names_in(): """Check that feature_name_in are recorded by `_validate_data`""" pd = pytest.importorskip("pandas") iris = datasets.load_iris() X_np = iris.data df = pd.DataFrame(X_np, columns=iris.feature_names) class NoOpTransformer(TransformerMixin, BaseEstimator): def fit(self, X, y=None): validate_data(self, X) return self def transform(self, X): validate_data(self, X, reset=False) return X # fit on dataframe saves the feature names trans = NoOpTransformer().fit(df) assert_array_equal(trans.feature_names_in_, df.columns) # fit again but on ndarray does not keep the previous feature names (see #21383) trans.fit(X_np) assert not hasattr(trans, "feature_names_in_") trans.fit(df) msg = "The feature names should match those that were passed" df_bad = pd.DataFrame(X_np, columns=iris.feature_names[::-1]) with pytest.raises(ValueError, match=msg): trans.transform(df_bad) # warns when fitted on dataframe and transforming a ndarray msg = ( "X does not have valid feature names, but NoOpTransformer was " "fitted with feature names" ) with pytest.warns(UserWarning, match=msg): trans.transform(X_np) # warns when fitted on a ndarray and transforming dataframe msg = "X has feature names, but NoOpTransformer was fitted without feature names" trans = NoOpTransformer().fit(X_np) with pytest.warns(UserWarning, match=msg): trans.transform(df) # fit on dataframe with all integer feature names works without warning df_int_names = pd.DataFrame(X_np) trans = NoOpTransformer() with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) trans.fit(df_int_names) # fit on dataframe with no feature names or all integer feature names # -> do not warn on transform Xs = [X_np, df_int_names] for X in Xs: with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) trans.transform(X) # fit on dataframe with feature names that are mixed raises an error: df_mixed = pd.DataFrame(X_np, columns=["a", "b", 1, 2]) trans = NoOpTransformer() msg = re.escape( "Feature names are only supported if all input features have string names, " "but your input has ['int', 'str'] as feature name / column name types. " "If you want feature names to be stored and validated, you must convert " "them all to strings, by using X.columns = X.columns.astype(str) for " "example. Otherwise you can remove feature / column names from your input " "data, or convert them all to a non-string data type." ) with pytest.raises(TypeError, match=msg): trans.fit(df_mixed) # transform on feature names that are mixed also raises: with pytest.raises(TypeError, match=msg): trans.transform(df_mixed) def test_validate_data_skip_check_array(): """Check skip_check_array option of _validate_data.""" pd = pytest.importorskip("pandas") iris = datasets.load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) y = pd.Series(iris.target) class NoOpTransformer(TransformerMixin, BaseEstimator): pass no_op = NoOpTransformer() X_np_out = validate_data(no_op, df, skip_check_array=False) assert isinstance(X_np_out, np.ndarray) assert_allclose(X_np_out, df.to_numpy()) X_df_out = validate_data(no_op, df, skip_check_array=True) assert X_df_out is df y_np_out = validate_data(no_op, y=y, skip_check_array=False) assert isinstance(y_np_out, np.ndarray) assert_allclose(y_np_out, y.to_numpy()) y_series_out = validate_data(no_op, y=y, skip_check_array=True) assert y_series_out is y X_np_out, y_np_out = validate_data(no_op, df, y, skip_check_array=False) assert isinstance(X_np_out, np.ndarray) assert_allclose(X_np_out, df.to_numpy()) assert isinstance(y_np_out, np.ndarray) assert_allclose(y_np_out, y.to_numpy()) X_df_out, y_series_out = validate_data(no_op, df, y, skip_check_array=True) assert X_df_out is df assert y_series_out is y msg = "Validation should be done on X, y or both." with pytest.raises(ValueError, match=msg): validate_data(no_op) def test_clone_keeps_output_config(): """Check that clone keeps the set_output config.""" ss = StandardScaler().set_output(transform="pandas") config = _get_output_config("transform", ss) ss_clone = clone(ss) config_clone = _get_output_config("transform", ss_clone) assert config == config_clone
SingleInheritanceEstimator
python
doocs__leetcode
solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/Solution.py
{ "start": 0, "end": 268 }
class ____: def minimumSwap(self, s1: str, s2: str) -> int: xy = yx = 0 for a, b in zip(s1, s2): xy += a < b yx += a > b if (xy + yx) % 2: return -1 return xy // 2 + yx // 2 + xy % 2 + yx % 2
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 655918, "end": 656656 }
class ____(sgqlc.types.relay.Connection): """The connection type for Environment.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("EnvironmentEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("Environment"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
EnvironmentConnection
python
bokeh__bokeh
src/bokeh/models/widgets/sliders.py
{ "start": 6659, "end": 8253 }
class ____(NumericalSlider): """ Slider-based date selection widget. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @property def value_as_datetime(self) -> datetime | None: ''' Convenience property to retrieve the value as a datetime object. Added in version 2.0 ''' if self.value is None: return None if isinstance(self.value, numbers.Number): return datetime.fromtimestamp(self.value / 1000, tz=timezone.utc) return self.value @property def value_as_date(self) -> date | None: ''' Convenience property to retrieve the value as a date object. Added in version 2.0 ''' if self.value is None: return None if isinstance(self.value, numbers.Number): dt = datetime.fromtimestamp(self.value / 1000, tz=timezone.utc) return date(*dt.timetuple()[:3]) return self.value value = Required(Datetime, help=""" Initial or selected value. """) value_throttled = Readonly(Required(Datetime), help=""" Initial or selected value, throttled to report only on mouseup. """) start = Required(Datetime, help=""" The minimum allowable value. """) end = Required(Datetime, help=""" The maximum allowable value. """) step = Int(default=1, help=""" The step between consecutive values, in units of days. """) format = Override(default="%d %b %Y")
DateSlider
python
charliermarsh__ruff
crates/ruff_benchmark/resources/pydantic/types.py
{ "start": 12475, "end": 15571 }
class ____(abc.ABC, Generic[SecretType]): _error_kind: str def __init__(self, secret_value: SecretType) -> None: self._secret_value: SecretType = secret_value def get_secret_value(self) -> SecretType: return self._secret_value @classmethod def __get_pydantic_core_schema__(cls, **_kwargs: Any) -> core_schema.FunctionSchema: validator = SecretFieldValidator(cls) if issubclass(cls, SecretStr): # Use a lambda here so that `apply_metadata` can be called on the validator before the override is generated override = lambda: core_schema.str_schema( # noqa E731 min_length=validator.min_length, max_length=validator.max_length, ) elif issubclass(cls, SecretBytes): override = lambda: core_schema.bytes_schema( # noqa E731 min_length=validator.min_length, max_length=validator.max_length, ) else: override = None metadata = build_metadata_dict( update_cs_function=validator.__pydantic_update_schema__, js_metadata=JsonSchemaMetadata(core_schema_override=override), ) return core_schema.function_after_schema( core_schema.union_schema( core_schema.is_instance_schema(cls), cls._pre_core_schema(), strict=True, custom_error_type=cls._error_kind, ), validator, metadata=metadata, serialization=core_schema.function_plain_ser_schema(cls._serialize, json_return_type='str'), ) @classmethod def _serialize( cls, value: SecretField[SecretType], info: core_schema.SerializationInfo ) -> str | SecretField[SecretType]: if info.mode == 'json': # we want the output to always be string without the `b'` prefix for byties, # hence we just use `secret_display` return secret_display(value) else: return value @classmethod @abc.abstractmethod def _pre_core_schema(cls) -> core_schema.CoreSchema: ... @classmethod def __pydantic_modify_json_schema__(cls, field_schema: dict[str, Any]) -> None: update_not_none( field_schema, type='string', writeOnly=True, format='password', ) def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value() def __hash__(self) -> int: return hash(self.get_secret_value()) def __len__(self) -> int: return len(self._secret_value) @abc.abstractmethod def _display(self) -> SecretType: ... def __str__(self) -> str: return str(self._display()) def __repr__(self) -> str: return f'{self.__class__.__name__}({self._display()!r})' def secret_display(secret_field: SecretField[Any]) -> str: return '**********' if secret_field.get_secret_value() else ''
SecretField
python
milvus-io__pymilvus
pymilvus/orm/schema.py
{ "start": 3208, "end": 16746 }
class ____: def __init__( self, fields: List, description: str = "", struct_fields: Optional[List] = None, functions: Optional[List] = None, **kwargs, ): self._kwargs = copy.deepcopy(kwargs) self._fields = [] self._struct_fields = [] self._description = description # if "enable_dynamic_field" is not in kwargs, we keep None here self._enable_dynamic_field = self._kwargs.get("enable_dynamic_field", None) self._primary_field = None self._partition_key_field = None self._clustering_key_field = None self._functions = [] if functions: if not isinstance(functions, list): raise FunctionsTypeException(message=ExceptionsMessage.FunctionsType) for function in functions: if not isinstance(function, Function): raise SchemaNotReadyException(message=ExceptionsMessage.FunctionIncorrectType) self._functions = functions if not isinstance(fields, list): raise FieldsTypeException(message=ExceptionsMessage.FieldsType) for field in fields: if not isinstance(field, FieldSchema): raise FieldTypeException(message=ExceptionsMessage.FieldType) self._fields = [copy.deepcopy(field) for field in fields] if struct_fields is not None: for struct in struct_fields: if not isinstance(struct, StructFieldSchema): raise FieldTypeException(message=ExceptionsMessage.FieldType) self._struct_fields = [copy.deepcopy(struct) for struct in struct_fields] self._mark_output_fields() self._check_kwargs() if kwargs.get("check_fields", True): self._check_fields() def _check_kwargs(self): primary_field_name = self._kwargs.get("primary_field", None) partition_key_field_name = self._kwargs.get("partition_key_field", None) clustering_key_field_name = self._kwargs.get("clustering_key_field_name", None) if primary_field_name is not None and not isinstance(primary_field_name, str): raise PrimaryKeyException(message=ExceptionsMessage.PrimaryFieldType) if partition_key_field_name is not None and not isinstance(partition_key_field_name, str): raise PartitionKeyException(message=ExceptionsMessage.PartitionKeyFieldType) if clustering_key_field_name is not None and not isinstance(clustering_key_field_name, str): raise ClusteringKeyException(message=ExceptionsMessage.ClusteringKeyFieldType) if "auto_id" in self._kwargs and not isinstance(self._kwargs["auto_id"], bool): raise AutoIDException(0, ExceptionsMessage.AutoIDType) def _check_fields(self): primary_field_name = self._kwargs.get("primary_field", None) partition_key_field_name = self._kwargs.get("partition_key_field", None) clustering_key_field_name = self._kwargs.get("clustering_key_field", None) for field in self._fields: if primary_field_name and primary_field_name == field.name: field.is_primary = True if partition_key_field_name and partition_key_field_name == field.name: field.is_partition_key = True if field.is_primary: if primary_field_name is not None and primary_field_name != field.name: msg = ExceptionsMessage.PrimaryKeyOnlyOne % (primary_field_name, field.name) raise PrimaryKeyException(message=msg) self._primary_field = field primary_field_name = field.name if field.is_partition_key: if partition_key_field_name is not None and partition_key_field_name != field.name: msg = ExceptionsMessage.PartitionKeyOnlyOne % ( partition_key_field_name, field.name, ) raise PartitionKeyException(message=msg) self._partition_key_field = field partition_key_field_name = field.name if clustering_key_field_name and clustering_key_field_name == field.name: field.is_clustering_key = True if field.is_clustering_key: if ( clustering_key_field_name is not None and clustering_key_field_name != field.name ): msg = ExceptionsMessage.ClusteringKeyOnlyOne % ( clustering_key_field_name, field.name, ) raise ClusteringKeyException(message=msg) self._clustering_key_field = field clustering_key_field_name = field.name validate_primary_key(self._primary_field) validate_partition_key( partition_key_field_name, self._partition_key_field, self._primary_field.name ) validate_clustering_key(clustering_key_field_name, self._clustering_key_field) auto_id = self._kwargs.get("auto_id", False) if auto_id: self._primary_field.auto_id = auto_id def _check_functions(self): for function in self._functions: for output_field_name in function.output_field_names: output_field = next( (field for field in self._fields if field.name == output_field_name), None ) if output_field is None: raise ParamError( message=f"{ExceptionsMessage.FunctionMissingOutputField}: {output_field_name}" ) if output_field is not None and ( output_field.is_primary or output_field.is_partition_key or output_field.is_clustering_key ): raise ParamError(message=ExceptionsMessage.FunctionInvalidOutputField) for input_field_name in function.input_field_names: input_field = next( (field for field in self._fields if field.name == input_field_name), None ) if input_field is None: raise ParamError( message=f"{ExceptionsMessage.FunctionMissingInputField}: {input_field_name}" ) function.verify(self) def _mark_output_fields(self): for function in self._functions: for output_field_name in function.output_field_names: output_field = next( (field for field in self._fields if field.name == output_field_name), None ) if output_field is not None: output_field.is_function_output = True def _check(self): self._check_kwargs() self._check_fields() self._check_functions() def __repr__(self) -> str: return str(self.to_dict()) def __len__(self) -> int: return len(self.fields) def __eq__(self, other: object): """The order of the fields of schema must be consistent.""" return self.to_dict() == other.to_dict() @classmethod def construct_from_dict(cls, raw: Dict): fields = [FieldSchema.construct_from_dict(field_raw) for field_raw in raw["fields"]] struct_fields = None if raw.get("struct_fields"): struct_fields = [] for struct_field_raw in raw["struct_fields"]: struct_fields.append(StructFieldSchema.construct_from_dict(struct_field_raw)) elif raw.get("struct_array_fields"): converted_struct_fields = convert_struct_fields_to_user_format( raw["struct_array_fields"] ) struct_fields = [] for struct_field_dict in converted_struct_fields: struct_fields.append(StructFieldSchema.construct_from_dict(struct_field_dict)) if "functions" in raw: functions = [ Function.construct_from_dict(function_raw) for function_raw in raw["functions"] ] else: functions = [] enable_dynamic_field = raw.get("enable_dynamic_field", False) return CollectionSchema( fields, struct_fields=struct_fields, description=raw.get("description", ""), functions=functions, enable_dynamic_field=enable_dynamic_field, ) @property def primary_field(self): return self._primary_field @property def partition_key_field(self): return self._partition_key_field @property def fields(self): """ Returns the fields about the CollectionSchema. :return list: List of FieldSchema, return when operation is successful. :example: >>> from pymilvus import FieldSchema, CollectionSchema, DataType >>> field = FieldSchema("int64", DataType.INT64, description="int64", is_primary=True) >>> schema = CollectionSchema(fields=[field]) >>> schema.fields [<pymilvus.schema.FieldSchema object at 0x7fd3716ffc50>] """ return self._fields @property def struct_fields(self): return self._struct_fields @property def functions(self): """ Returns the functions of the CollectionSchema. :return list: List of Function, return when operation is successful. """ return self._functions @property def description(self): """ Returns a text description of the CollectionSchema. :return str: CollectionSchema description text, return when operation is successful. :example: >>> from pymilvus import FieldSchema, CollectionSchema, DataType >>> field = FieldSchema("int64", DataType.INT64, description="int64", is_primary=True) >>> schema = CollectionSchema(fields=[field], description="test get description") >>> schema.description 'test get description' """ return self._description @property def auto_id(self): """ Whether the primary keys are automatically generated. :return bool: * True: If the primary keys are automatically generated, * False: Otherwise. :example: >>> from pymilvus import FieldSchema, CollectionSchema, DataType >>> field = FieldSchema("int64", DataType.INT64, description="int64", is_primary=True) >>> schema = CollectionSchema(fields=[field]) >>> schema.auto_id False """ if self.primary_field: return self.primary_field.auto_id return self._kwargs.get("auto_id", False) @auto_id.setter def auto_id(self, value: bool): if self.primary_field: self.primary_field.auto_id = bool(value) @property def enable_dynamic_field(self): return bool(self._enable_dynamic_field) @enable_dynamic_field.setter def enable_dynamic_field(self, value: bool): self._enable_dynamic_field = bool(value) def to_dict(self): res = { "auto_id": self.auto_id, "description": self._description, "fields": [s.to_dict() for s in self._fields], "enable_dynamic_field": self.enable_dynamic_field, } if self._functions is not None and len(self._functions) > 0: res["functions"] = [s.to_dict() for s in self._functions] if self._struct_fields is not None and len(self._struct_fields) > 0: res["struct_fields"] = [s.to_dict() for s in self._struct_fields] return res def verify(self): # final check, detect obvious problems self._check() def add_field(self, field_name: str, datatype: DataType, **kwargs): if ( datatype == DataType.ARRAY and "element_type" in kwargs and kwargs["element_type"] == DataType.STRUCT ): if "struct_schema" not in kwargs: raise ParamError(message="Param struct_schema is required when datatype is STRUCT") struct_schema = copy.deepcopy(kwargs.pop("struct_schema")) struct_schema.name = field_name if "max_capacity" not in kwargs: raise ParamError(message="Param max_capacity is required when datatype is STRUCT") struct_schema.max_capacity = kwargs["max_capacity"] if "mmap_enabled" in kwargs: struct_schema._type_params["mmap_enabled"] = kwargs["mmap_enabled"] self._struct_fields.append(struct_schema) return self field = FieldSchema(field_name, datatype, **kwargs) self._fields.append(field) self._mark_output_fields() return self def add_struct_field(self, struct_field_schema: "StructFieldSchema"): self._struct_fields.append(struct_field_schema) return self def add_function(self, function: "Function"): if not isinstance(function, Function): raise ParamError(message=ExceptionsMessage.FunctionIncorrectType) self._functions.append(function) self._mark_output_fields() return self
CollectionSchema
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/rich/progress.py
{ "start": 5561, "end": 8272 }
class ____(RawIOBase, BinaryIO): """A reader that tracks progress while it's being read from.""" def __init__( self, handle: BinaryIO, progress: "Progress", task: TaskID, close_handle: bool = True, ) -> None: self.handle = handle self.progress = progress self.task = task self.close_handle = close_handle self._closed = False def __enter__(self) -> "_Reader": self.handle.__enter__() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.close() def __iter__(self) -> BinaryIO: return self def __next__(self) -> bytes: line = next(self.handle) self.progress.advance(self.task, advance=len(line)) return line @property def closed(self) -> bool: return self._closed def fileno(self) -> int: return self.handle.fileno() def isatty(self) -> bool: return self.handle.isatty() @property def mode(self) -> str: return self.handle.mode @property def name(self) -> str: return self.handle.name def readable(self) -> bool: return self.handle.readable() def seekable(self) -> bool: return self.handle.seekable() def writable(self) -> bool: return False def read(self, size: int = -1) -> bytes: block = self.handle.read(size) self.progress.advance(self.task, advance=len(block)) return block def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override] n = self.handle.readinto(b) # type: ignore[attr-defined] self.progress.advance(self.task, advance=n) return n def readline(self, size: int = -1) -> bytes: # type: ignore[override] line = self.handle.readline(size) self.progress.advance(self.task, advance=len(line)) return line def readlines(self, hint: int = -1) -> List[bytes]: lines = self.handle.readlines(hint) self.progress.advance(self.task, advance=sum(map(len, lines))) return lines def close(self) -> None: if self.close_handle: self.handle.close() self._closed = True def seek(self, offset: int, whence: int = 0) -> int: pos = self.handle.seek(offset, whence) self.progress.update(self.task, completed=pos) return pos def tell(self) -> int: return self.handle.tell() def write(self, s: Any) -> int: raise UnsupportedOperation("write")
_Reader
python
readthedocs__readthedocs.org
readthedocs/integrations/migrations/0001_add_http_exchange.py
{ "start": 219, "end": 1940 }
class ____(migrations.Migration): safe = Safe.after_deploy() initial = True dependencies = [ ("contenttypes", "0002_remove_content_type_name"), ] operations = [ migrations.CreateModel( name="HttpExchange", fields=[ ( "id", models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True, serialize=False, ), ), ("object_id", models.PositiveIntegerField()), ("date", models.DateTimeField(auto_now_add=True, verbose_name="Date")), ( "request_headers", jsonfield.fields.JSONField(verbose_name="Request headers"), ), ("request_body", models.TextField(verbose_name="Request body")), ( "response_headers", jsonfield.fields.JSONField(verbose_name="Request headers"), ), ("response_body", models.TextField(verbose_name="Response body")), ( "status_code", models.IntegerField(default=200, verbose_name="Status code"), ), ( "content_type", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="contenttypes.ContentType", ), ), ], options={ "ordering": ["-date"], }, ), ]
Migration
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 10522, "end": 10724 }
class ____(_Constraint): """Constraint representing the None singleton.""" def is_satisfied_by(self, val): return val is None def __str__(self): return "None"
_NoneConstraint
python
django__django
tests/gis_tests/test_geoforms.py
{ "start": 8632, "end": 16720 }
class ____(SimpleTestCase): def setUp(self): self.geometries = { "point": GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), "multipoint": GEOSGeometry( "SRID=4326;MULTIPOINT(" "(13.18634033203125 14.504356384277344)," "(13.207969665527 14.490966796875)," "(13.177070617675 14.454917907714))" ), "linestring": GEOSGeometry( "SRID=4326;LINESTRING(" "-8.26171875 -0.52734375," "-7.734375 4.21875," "6.85546875 3.779296875," "5.44921875 -3.515625)" ), "multilinestring": GEOSGeometry( "SRID=4326;MULTILINESTRING(" "(-16.435546875 -2.98828125," "-17.2265625 2.98828125," "-0.703125 3.515625," "-1.494140625 -3.33984375)," "(-8.0859375 -5.9765625," "8.525390625 -8.7890625," "12.392578125 -0.87890625," "10.01953125 7.646484375))" ), "polygon": GEOSGeometry( "SRID=4326;POLYGON(" "(-1.669921875 6.240234375," "-3.8671875 -0.615234375," "5.9765625 -3.955078125," "18.193359375 3.955078125," "9.84375 9.4921875," "-1.669921875 6.240234375))" ), "multipolygon": GEOSGeometry( "SRID=4326;MULTIPOLYGON(" "((-17.578125 13.095703125," "-17.2265625 10.8984375," "-13.974609375 10.1953125," "-13.359375 12.744140625," "-15.732421875 13.7109375," "-17.578125 13.095703125))," "((-8.525390625 5.537109375," "-8.876953125 2.548828125," "-5.888671875 1.93359375," "-5.09765625 4.21875," "-6.064453125 6.240234375," "-8.525390625 5.537109375)))" ), "geometrycollection": GEOSGeometry( "SRID=4326;GEOMETRYCOLLECTION(" "POINT(5.625 -0.263671875)," "POINT(6.767578125 -3.603515625)," "POINT(8.525390625 0.087890625)," "POINT(8.0859375 -2.13134765625)," "LINESTRING(" "6.273193359375 -1.175537109375," "5.77880859375 -1.812744140625," "7.27294921875 -2.230224609375," "7.657470703125 -1.25244140625))" ), } def assertMapWidget(self, form_instance, geom_name): """ Make sure the MapWidget js is passed in the form media and a MapWidget is actually created """ self.assertTrue(form_instance.is_valid()) rendered = form_instance.as_p() map_fields = [ f for f in form_instance if isinstance(f.field, forms.GeometryField) ] for map_field in map_fields: attrs = { "base_layer": "nasaWorldview", "geom_type": map_field.field.geom_type, "map_srid": 3857, "display_raw": False, "required": True, "id": map_field.id_for_label, "geom_name": geom_name, } expected = json_script(attrs, f"{map_field.id_for_label}_mapwidget_options") self.assertInHTML(expected, rendered) self.assertIn("gis/js/OLMapWidget.js", str(form_instance.media)) def assertTextarea(self, geom, rendered): """Makes sure the wkt and a textarea are in the content""" self.assertIn("<textarea ", rendered) self.assertIn("required", rendered) ogr = geom.ogr ogr.transform(3857) self.assertIn(escape(ogr.json), rendered) # map_srid in openlayers.html template must not be localized. @override_settings(USE_THOUSAND_SEPARATOR=True) def test_pointfield(self): class PointForm(forms.Form): p = forms.PointField() geom = self.geometries["point"] form = PointForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "Point") self.assertFalse(PointForm().is_valid()) invalid = PointForm(data={"p": "some invalid geom"}) self.assertFalse(invalid.is_valid()) self.assertIn("Invalid geometry value", str(invalid.errors)) for invalid in [geo for key, geo in self.geometries.items() if key != "point"]: self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid()) def test_multipointfield(self): class PointForm(forms.Form): p = forms.MultiPointField() geom = self.geometries["multipoint"] form = PointForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiPoint") self.assertFalse(PointForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multipoint" ]: self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid()) def test_linestringfield(self): class LineStringForm(forms.Form): f = forms.LineStringField() geom = self.geometries["linestring"] form = LineStringForm(data={"f": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "LineString") self.assertFalse(LineStringForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "linestring" ]: self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid()) def test_multilinestringfield(self): class LineStringForm(forms.Form): f = forms.MultiLineStringField() geom = self.geometries["multilinestring"] form = LineStringForm(data={"f": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiLineString") self.assertFalse(LineStringForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multilinestring" ]: self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid()) def test_polygonfield(self): class PolygonForm(forms.Form): p = forms.PolygonField() geom = self.geometries["polygon"] form = PolygonForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "Polygon") self.assertFalse(PolygonForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "polygon" ]: self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid()) def test_multipolygonfield(self): class PolygonForm(forms.Form): p = forms.MultiPolygonField() geom = self.geometries["multipolygon"] form = PolygonForm(data={"p": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "MultiPolygon") self.assertFalse(PolygonForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "multipolygon" ]: self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid()) def test_geometrycollectionfield(self): class GeometryForm(forms.Form): g = forms.GeometryCollectionField() geom = self.geometries["geometrycollection"] form = GeometryForm(data={"g": geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form, "GeometryCollection") self.assertFalse(GeometryForm().is_valid()) for invalid in [ geo for key, geo in self.geometries.items() if key != "geometrycollection" ]: self.assertFalse(GeometryForm(data={"g": invalid.wkt}).is_valid())
SpecializedFieldTest
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
{ "start": 8814, "end": 22038 }
class ____(TestDagEndpoint): """Unit tests for Get DAGs.""" @pytest.mark.parametrize( ("query_params", "expected_total_entries", "expected_ids"), [ # Filters ({}, 2, [DAG1_ID, DAG2_ID]), ({"limit": 1}, 2, [DAG1_ID]), ({"offset": 1}, 2, [DAG2_ID]), ({"tags": ["example"]}, 1, [DAG1_ID]), ( {"exclude_stale": False}, 3, [DAG1_ID, DAG2_ID, DAG3_ID], ), ({"paused": True, "exclude_stale": False}, 1, [DAG3_ID]), ( {"paused": False}, 2, [DAG1_ID, DAG2_ID], ), ( {"owners": ["airflow"]}, 2, [DAG1_ID, DAG2_ID], ), ({"owners": ["test_owner"], "exclude_stale": False}, 1, [DAG3_ID]), ({"last_dag_run_state": "success", "exclude_stale": False}, 1, [DAG3_ID]), ({"last_dag_run_state": "failed", "exclude_stale": False}, 1, [DAG1_ID]), ({"dag_run_state": "failed"}, 1, [DAG1_ID]), ({"dag_run_state": "failed", "exclude_stale": False}, 1, [DAG1_ID]), ( {"dag_run_start_date_gte": DAG3_START_DATE_2.isoformat(), "exclude_stale": False}, 1, [DAG3_ID], ), ( {"dag_run_start_date_gt": DAG3_START_DATE_1.isoformat(), "exclude_stale": False}, 2, [DAG1_ID, DAG3_ID], ), ( { "dag_run_start_date_gte": DAG1_START_DATE.isoformat(), "dag_run_start_date_lte": DAG2_START_DATE.isoformat(), }, 1, [DAG1_ID], ), ( { "dag_run_start_date_gt": DAG1_START_DATE.isoformat(), "dag_run_start_date_lt": DAG2_START_DATE.isoformat(), }, 0, [], ), ( { "dag_run_start_date_gte": (DAG1_START_DATE - timedelta(days=1)).isoformat(), "dag_run_start_date_gt": (DAG1_START_DATE - timedelta(days=1)).isoformat(), }, 1, [DAG1_ID], ), ( { "dag_run_start_date_gt": DAG1_START_DATE.isoformat(), "dag_run_start_date_lte": DAG2_START_DATE.isoformat(), }, 0, [], ), ( { "dag_run_start_date_lt": DAG2_START_DATE.isoformat(), }, 1, [DAG1_ID], ), ( { "dag_run_start_date_lt": DAG2_START_DATE.isoformat(), "dag_run_start_date_lte": DAG3_START_DATE_2.isoformat(), }, 1, [DAG1_ID], ), ( { "dag_run_end_date_lte": (datetime.now(tz=timezone.utc) + timedelta(days=1)).isoformat(), "exclude_stale": False, }, 2, [DAG1_ID, DAG3_ID], ), ( { "dag_run_end_date_gte": DAG3_START_DATE_2.isoformat(), "dag_run_end_date_lte": (datetime.now(tz=timezone.utc) + timedelta(days=1)).isoformat(), "exclude_stale": False, "last_dag_run_state": "success", }, 1, [DAG3_ID], ), ( { "dag_run_start_date_gte": DAG2_START_DATE.isoformat(), "dag_run_end_date_lte": (datetime.now(tz=timezone.utc) + timedelta(days=1)).isoformat(), }, 0, [], ), ( { "dag_run_start_date_gte": (DAG3_START_DATE_1 - timedelta(days=1)).isoformat(), "dag_run_start_date_lte": (DAG3_START_DATE_1 + timedelta(days=1)).isoformat(), "last_dag_run_state": "success", "dag_run_state": "failed", "exclude_stale": False, }, 0, [], ), # Sort ( {"order_by": "-dag_id"}, 2, [DAG2_ID, DAG1_ID], ), ( {"order_by": "-dag_display_name"}, 2, [DAG2_ID, DAG1_ID], ), ( {"order_by": "dag_display_name"}, 2, [DAG1_ID, DAG2_ID], ), ( {"order_by": "next_dagrun", "exclude_stale": False}, 3, [DAG3_ID, DAG1_ID, DAG2_ID], ), ( {"order_by": "last_run_state", "exclude_stale": False}, 3, [DAG1_ID, DAG3_ID, DAG2_ID], ), ( {"order_by": "-last_run_state", "exclude_stale": False}, 3, [DAG3_ID, DAG1_ID, DAG2_ID], ), ( {"order_by": "last_run_start_date", "exclude_stale": False}, 3, [DAG1_ID, DAG3_ID, DAG2_ID], ), ( {"order_by": "-last_run_start_date", "exclude_stale": False}, 3, [DAG3_ID, DAG1_ID, DAG2_ID], ), ( {"order_by": ["next_dagrun", "-dag_display_name"], "exclude_stale": False}, 3, [DAG3_ID, DAG2_ID, DAG1_ID], ), # Search ({"dag_id_pattern": "1"}, 1, [DAG1_ID]), ({"dag_display_name_pattern": "test_dag2"}, 1, [DAG2_ID]), # Bundle filters ( {"bundle_name": "dag_maker"}, 2, [DAG1_ID, DAG2_ID], ), ({"bundle_name": "wrong_bundle"}, 0, []), ({"bundle_version": "1.0.0"}, 0, []), # Asset filters ({"has_asset_schedule": True}, 3, [ASSET_DEP_DAG_ID, ASSET_DEP_DAG2_ID, ASSET_SCHEDULED_DAG_ID]), ({"has_asset_schedule": False}, 2, [DAG1_ID, DAG2_ID]), ({"asset_dependency": "test_asset"}, 1, [ASSET_DEP_DAG_ID]), ({"asset_dependency": "dataset"}, 1, [ASSET_DEP_DAG2_ID]), ({"asset_dependency": "bucket"}, 1, [ASSET_DEP_DAG2_ID]), ({"asset_dependency": "s3://"}, 1, [ASSET_DEP_DAG2_ID]), ({"asset_dependency": "nonexistent"}, 0, []), ({"has_asset_schedule": True, "asset_dependency": "test_asset"}, 1, [ASSET_DEP_DAG_ID]), ({"has_asset_schedule": False, "asset_dependency": "test_asset"}, 0, []), ], ) def test_get_dags(self, test_client, query_params, expected_total_entries, expected_ids, session): # Only create asset test data for asset-related tests to avoid affecting other tests if any(param in query_params for param in ["has_asset_schedule", "asset_dependency"]): self._create_asset_test_data(session) with assert_queries_count(4): response = test_client.get("/dags", params=query_params) assert response.status_code == 200 body = response.json() assert body["total_entries"] == expected_total_entries actual_ids = [dag["dag_id"] for dag in body["dags"]] assert actual_ids == expected_ids @mock.patch("airflow.api_fastapi.auth.managers.base_auth_manager.BaseAuthManager.get_authorized_dag_ids") def test_get_dags_should_call_get_authorized_dag_ids(self, mock_get_authorized_dag_ids, test_client): mock_get_authorized_dag_ids.return_value = {DAG1_ID, DAG2_ID} response = test_client.get("/dags") mock_get_authorized_dag_ids.assert_called_once_with(user=mock.ANY, method="GET") assert response.status_code == 200 body = response.json() assert body["total_entries"] == 2 assert [dag["dag_id"] for dag in body["dags"]] == [DAG1_ID, DAG2_ID] @pytest.mark.parametrize( ("setup_favorites", "expected_total_entries", "expected_ids"), [ ([], 0, []), ([DAG1_ID], 1, [DAG1_ID]), ([DAG1_ID, DAG2_ID], 2, [DAG1_ID, DAG2_ID]), ], ) def test_get_dags_filter_favorites( self, session, test_client, setup_favorites, expected_total_entries, expected_ids ): """Test filtering DAGs by is_favorite=true.""" for dag_id in setup_favorites: session.add(DagFavorite(user_id="test", dag_id=dag_id)) session.commit() response = test_client.get("/dags", params={"is_favorite": True}) assert response.status_code == 200 body = response.json() assert body["total_entries"] == expected_total_entries assert sorted([dag["dag_id"] for dag in body["dags"]]) == sorted(expected_ids) def test_get_dags_filter_non_favorites(self, session, test_client): """Test filtering DAGs by is_favorite=false.""" # Mark DAG1 as favorite session.add(DagFavorite(user_id="test", dag_id=DAG1_ID)) session.commit() response = test_client.get("/dags", params={"is_favorite": False}) assert response.status_code == 200 body = response.json() # Should return only non-favorite DAGs (DAG2) assert body["total_entries"] == 1 assert [dag["dag_id"] for dag in body["dags"]] == [DAG2_ID] def test_get_dags_should_response_401(self, unauthenticated_test_client): response = unauthenticated_test_client.get("/dags") assert response.status_code == 401 def test_get_dags_should_response_403(self, unauthorized_test_client): response = unauthorized_test_client.get("/dags") assert response.status_code == 403 @pytest.mark.parametrize( ("filter_value", "expected_ids"), [ (True, [DAG1_ID]), (False, [DAG2_ID]), ], ) def test_get_dags_filter_has_import_errors(self, session, test_client, filter_value, expected_ids): dag = session.get(DagModel, DAG1_ID) dag.has_import_errors = True session.commit() response = test_client.get("/dags", params={"has_import_errors": filter_value}) assert response.status_code == 200 body = response.json() assert body["total_entries"] == 1 assert [dag["dag_id"] for dag in body["dags"]] == expected_ids def test_get_dags_no_n_plus_one_queries(self, session, test_client): """Test that fetching DAGs with tags doesn't trigger n+1 queries.""" num_dags = 5 for i in range(num_dags): dag_id = f"test_dag_queries_{i}" dag_model = DagModel( dag_id=dag_id, bundle_name="dag_maker", fileloc=f"/tmp/{dag_id}.py", is_stale=False, ) session.add(dag_model) session.flush() for j in range(3): tag = DagTag(name=f"tag_{i}_{j}", dag_id=dag_id) session.add(tag) session.commit() session.expire_all() with count_queries() as result: response = test_client.get("/dags", params={"limit": 10}) assert response.status_code == 200 body = response.json() dags_with_our_prefix = [d for d in body["dags"] if d["dag_id"].startswith("test_dag_queries_")] assert len(dags_with_our_prefix) == num_dags for dag in dags_with_our_prefix: assert len(dag["tags"]) == 3 first_query_count = sum(result.values()) # Add more DAGs and verify query count doesn't scale linearly for i in range(num_dags, num_dags + 3): dag_id = f"test_dag_queries_{i}" dag_model = DagModel( dag_id=dag_id, bundle_name="dag_maker", fileloc=f"/tmp/{dag_id}.py", is_stale=False, ) session.add(dag_model) session.flush() for j in range(3): tag = DagTag(name=f"tag_{i}_{j}", dag_id=dag_id) session.add(tag) session.commit() session.expire_all() with count_queries() as result2: response = test_client.get("/dags", params={"limit": 15}) assert response.status_code == 200 second_query_count = sum(result2.values()) # With n+1, adding 3 DAGs would add ~3 tag queries # Without n+1, query count should remain nearly identical assert second_query_count - first_query_count < 3, ( f"Added 3 DAGs but query count increased by {second_query_count - first_query_count} " f"({first_query_count} → {second_query_count}), suggesting n+1 queries for tags" )
TestGetDags
python
openai__openai-python
src/openai/resources/embeddings.py
{ "start": 6141, "end": 11416 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncEmbeddingsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncEmbeddingsWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncEmbeddingsWithStreamingResponse(self) async def create( self, *, input: Union[str, SequenceNotStr[str], Iterable[int], Iterable[Iterable[int]]], model: Union[str, EmbeddingModel], dimensions: int | Omit = omit, encoding_format: Literal["float", "base64"] | Omit = omit, user: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> CreateEmbeddingResponse: """ Creates an embedding vector representing the input text. Args: input: Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request. model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them. dimensions: The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. encoding_format: The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ params = { "input": input, "model": model, "user": user, "dimensions": dimensions, "encoding_format": encoding_format, } if not is_given(encoding_format): params["encoding_format"] = "base64" def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: if is_given(encoding_format): # don't modify the response object if a user explicitly asked for a format return obj if not obj.data: raise ValueError("No embedding data received") for embedding in obj.data: data = cast(object, embedding.embedding) if not isinstance(data, str): continue if not has_numpy(): # use array for base64 optimisation embedding.embedding = array.array("f", base64.b64decode(data)).tolist() else: embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] base64.b64decode(data), dtype="float32" ).tolist() return obj return await self._post( "/embeddings", body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, post_parser=parser, ), cast_to=CreateEmbeddingResponse, )
AsyncEmbeddings
python
pydantic__pydantic
pydantic/functional_validators.py
{ "start": 20313, "end": 20774 }
class ____(Protocol): """A `@model_validator` decorated function signature. This is used when `mode='before'` and the function does not have info argument. """ def __call__( # noqa: D102 self, # this can be a dict, a model instance # or anything else that gets passed to validate_python # thus validators _must_ handle all cases value: Any, /, ) -> Any: ...
FreeModelBeforeValidatorWithoutInfo
python
getsentry__sentry-python
tests/integrations/mcp/test_mcp.py
{ "start": 3135, "end": 32220 }
class ____: """Mock GetPromptResult object""" def __init__(self, messages): self.messages = messages def test_integration_patches_server(sentry_init): """Test that MCPIntegration patches the Server class""" # Get original methods before integration original_call_tool = Server.call_tool original_get_prompt = Server.get_prompt original_read_resource = Server.read_resource sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) # After initialization, the methods should be patched assert Server.call_tool is not original_call_tool assert Server.get_prompt is not original_get_prompt assert Server.read_resource is not original_read_resource @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (True, False), (False, True), (False, False)], ) def test_tool_handler_sync( sentry_init, capture_events, send_default_pii, include_prompts ): """Test that synchronous tool handlers create proper spans""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-123", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool(tool_name, arguments): return {"result": "success", "value": 42} with start_transaction(name="mcp tx"): # Call the tool handler result = test_tool("calculate", {"x": 10, "y": 5}) assert result == {"result": "success", "value": 42} (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "tools/call calculate" assert span["origin"] == "auto.ai.mcp" # Check span data assert span["data"][SPANDATA.MCP_TOOL_NAME] == "calculate" assert span["data"][SPANDATA.MCP_METHOD_NAME] == "tools/call" assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio" assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-123" assert span["data"]["mcp.request.argument.x"] == "10" assert span["data"]["mcp.request.argument.y"] == "5" # Check PII-sensitive data is only present when both flags are True if send_default_pii and include_prompts: assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps( { "result": "success", "value": 42, } ) assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT] == 2 else: assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"] assert SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT not in span["data"] @pytest.mark.asyncio @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (True, False), (False, True), (False, False)], ) async def test_tool_handler_async( sentry_init, capture_events, send_default_pii, include_prompts ): """Test that async tool handlers create proper spans""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext( request_id="req-456", session_id="session-789", transport="http" ) request_ctx.set(mock_ctx) @server.call_tool() async def test_tool_async(tool_name, arguments): return {"status": "completed"} with start_transaction(name="mcp tx"): result = await test_tool_async("process", {"data": "test"}) assert result == {"status": "completed"} (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "tools/call process" assert span["origin"] == "auto.ai.mcp" # Check span data assert span["data"][SPANDATA.MCP_TOOL_NAME] == "process" assert span["data"][SPANDATA.MCP_METHOD_NAME] == "tools/call" assert span["data"][SPANDATA.MCP_TRANSPORT] == "http" assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-456" assert span["data"][SPANDATA.MCP_SESSION_ID] == "session-789" assert span["data"]["mcp.request.argument.data"] == '"test"' # Check PII-sensitive data if send_default_pii and include_prompts: assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps( {"status": "completed"} ) else: assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"] def test_tool_handler_with_error(sentry_init, capture_events): """Test that tool handler errors are captured properly""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-error", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def failing_tool(tool_name, arguments): raise ValueError("Tool execution failed") with start_transaction(name="mcp tx"): with pytest.raises(ValueError): failing_tool("bad_tool", {}) # Should have error event and transaction assert len(events) == 2 error_event, tx = events # Check error event assert error_event["level"] == "error" assert error_event["exception"]["values"][0]["type"] == "ValueError" assert error_event["exception"]["values"][0]["value"] == "Tool execution failed" # Check transaction and span assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] # Error flag should be set for tools assert span["data"][SPANDATA.MCP_TOOL_RESULT_IS_ERROR] is True assert span["status"] == "internal_error" assert span["tags"]["status"] == "internal_error" @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (True, False), (False, True), (False, False)], ) def test_prompt_handler_sync( sentry_init, capture_events, send_default_pii, include_prompts ): """Test that synchronous prompt handlers create proper spans""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-prompt", transport="stdio") request_ctx.set(mock_ctx) @server.get_prompt() def test_prompt(name, arguments): return MockGetPromptResult([MockPromptMessage("user", "Tell me about Python")]) with start_transaction(name="mcp tx"): result = test_prompt("code_help", {"language": "python"}) assert result.messages[0].role == "user" assert result.messages[0].content.text == "Tell me about Python" (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "prompts/get code_help" assert span["origin"] == "auto.ai.mcp" # Check span data assert span["data"][SPANDATA.MCP_PROMPT_NAME] == "code_help" assert span["data"][SPANDATA.MCP_METHOD_NAME] == "prompts/get" assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio" assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-prompt" assert span["data"]["mcp.request.argument.name"] == '"code_help"' assert span["data"]["mcp.request.argument.language"] == '"python"' # Message count is always captured assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_COUNT] == 1 # For single message prompts, role and content should be captured only with PII if send_default_pii and include_prompts: assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE] == "user" assert ( span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT] == "Tell me about Python" ) else: assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE not in span["data"] assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT not in span["data"] @pytest.mark.asyncio @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (True, False), (False, True), (False, False)], ) async def test_prompt_handler_async( sentry_init, capture_events, send_default_pii, include_prompts ): """Test that async prompt handlers create proper spans""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext( request_id="req-async-prompt", session_id="session-abc", transport="http" ) request_ctx.set(mock_ctx) @server.get_prompt() async def test_prompt_async(name, arguments): return MockGetPromptResult( [ MockPromptMessage("system", "You are a helpful assistant"), MockPromptMessage("user", "What is MCP?"), ] ) with start_transaction(name="mcp tx"): result = await test_prompt_async("mcp_info", {}) assert len(result.messages) == 2 (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "prompts/get mcp_info" # For multi-message prompts, count is always captured assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_COUNT] == 2 # Role/content are never captured for multi-message prompts (even with PII) assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE not in span["data"] assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT not in span["data"] def test_prompt_handler_with_error(sentry_init, capture_events): """Test that prompt handler errors are captured""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-error-prompt", transport="stdio") request_ctx.set(mock_ctx) @server.get_prompt() def failing_prompt(name, arguments): raise RuntimeError("Prompt not found") with start_transaction(name="mcp tx"): with pytest.raises(RuntimeError): failing_prompt("missing_prompt", {}) # Should have error event and transaction assert len(events) == 2 error_event, tx = events assert error_event["level"] == "error" assert error_event["exception"]["values"][0]["type"] == "RuntimeError" def test_resource_handler_sync(sentry_init, capture_events): """Test that synchronous resource handlers create proper spans""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-resource", transport="stdio") request_ctx.set(mock_ctx) @server.read_resource() def test_resource(uri): return {"content": "file contents", "mime_type": "text/plain"} with start_transaction(name="mcp tx"): uri = MockURI("file:///path/to/file.txt") result = test_resource(uri) assert result["content"] == "file contents" (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "resources/read file:///path/to/file.txt" assert span["origin"] == "auto.ai.mcp" # Check span data assert span["data"][SPANDATA.MCP_RESOURCE_URI] == "file:///path/to/file.txt" assert span["data"][SPANDATA.MCP_METHOD_NAME] == "resources/read" assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio" assert span["data"][SPANDATA.MCP_REQUEST_ID] == "req-resource" assert span["data"][SPANDATA.MCP_RESOURCE_PROTOCOL] == "file" # Resources don't capture result content assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"] @pytest.mark.asyncio async def test_resource_handler_async(sentry_init, capture_events): """Test that async resource handlers create proper spans""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext( request_id="req-async-resource", session_id="session-res", transport="http" ) request_ctx.set(mock_ctx) @server.read_resource() async def test_resource_async(uri): return {"data": "resource data"} with start_transaction(name="mcp tx"): uri = MockURI("https://example.com/resource") result = await test_resource_async(uri) assert result["data"] == "resource data" (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 1 span = tx["spans"][0] assert span["op"] == OP.MCP_SERVER assert span["description"] == "resources/read https://example.com/resource" assert span["data"][SPANDATA.MCP_RESOURCE_URI] == "https://example.com/resource" assert span["data"][SPANDATA.MCP_RESOURCE_PROTOCOL] == "https" assert span["data"][SPANDATA.MCP_SESSION_ID] == "session-res" def test_resource_handler_with_error(sentry_init, capture_events): """Test that resource handler errors are captured""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-error-resource", transport="stdio") request_ctx.set(mock_ctx) @server.read_resource() def failing_resource(uri): raise FileNotFoundError("Resource not found") with start_transaction(name="mcp tx"): with pytest.raises(FileNotFoundError): uri = MockURI("file:///missing.txt") failing_resource(uri) # Should have error event and transaction assert len(events) == 2 error_event, tx = events assert error_event["level"] == "error" assert error_event["exception"]["values"][0]["type"] == "FileNotFoundError" @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (False, False)], ) def test_tool_result_extraction_tuple( sentry_init, capture_events, send_default_pii, include_prompts ): """Test extraction of tool results from tuple format (UnstructuredContent, StructuredContent)""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-tuple", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool_tuple(tool_name, arguments): # Return CombinationContent: (UnstructuredContent, StructuredContent) unstructured = [MockTextContent("Result text")] structured = {"key": "value", "count": 5} return (unstructured, structured) with start_transaction(name="mcp tx"): test_tool_tuple("combo_tool", {}) (tx,) = events span = tx["spans"][0] # Should extract the structured content (second element of tuple) only with PII if send_default_pii and include_prompts: assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps( { "key": "value", "count": 5, } ) assert span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT] == 2 else: assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"] assert SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT not in span["data"] @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (False, False)], ) def test_tool_result_extraction_unstructured( sentry_init, capture_events, send_default_pii, include_prompts ): """Test extraction of tool results from UnstructuredContent (list of content blocks)""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-unstructured", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool_unstructured(tool_name, arguments): # Return UnstructuredContent as list of content blocks return [ MockTextContent("First part"), MockTextContent("Second part"), ] with start_transaction(name="mcp tx"): test_tool_unstructured("text_tool", {}) (tx,) = events span = tx["spans"][0] # Should extract and join text from content blocks only with PII if send_default_pii and include_prompts: assert ( span["data"][SPANDATA.MCP_TOOL_RESULT_CONTENT] == '"First part Second part"' ) else: assert SPANDATA.MCP_TOOL_RESULT_CONTENT not in span["data"] def test_request_context_no_context(sentry_init, capture_events): """Test handling when no request context is available""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Clear request context (simulating no context available) # This will cause a LookupError when trying to get context request_ctx.set(None) @server.call_tool() def test_tool_no_ctx(tool_name, arguments): return {"result": "ok"} with start_transaction(name="mcp tx"): # This should work even without request context try: test_tool_no_ctx("tool", {}) except LookupError: # If it raises LookupError, that's expected when context is truly missing pass # Should still create span even if context is missing (tx,) = events span = tx["spans"][0] # Transport defaults to "pipe" when no context assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio" # Request ID and Session ID should not be present assert SPANDATA.MCP_REQUEST_ID not in span["data"] assert SPANDATA.MCP_SESSION_ID not in span["data"] def test_span_origin(sentry_init, capture_events): """Test that span origin is set correctly""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-origin", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool(tool_name, arguments): return {"result": "test"} with start_transaction(name="mcp tx"): test_tool("origin_test", {}) (tx,) = events assert tx["contexts"]["trace"]["origin"] == "manual" assert tx["spans"][0]["origin"] == "auto.ai.mcp" def test_multiple_handlers(sentry_init, capture_events): """Test that multiple handler calls create multiple spans""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-multi", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def tool1(tool_name, arguments): return {"result": "tool1"} @server.call_tool() def tool2(tool_name, arguments): return {"result": "tool2"} @server.get_prompt() def prompt1(name, arguments): return MockGetPromptResult([MockPromptMessage("user", "Test prompt")]) with start_transaction(name="mcp tx"): tool1("tool_a", {}) tool2("tool_b", {}) prompt1("prompt_a", {}) (tx,) = events assert tx["type"] == "transaction" assert len(tx["spans"]) == 3 # Check that we have different span types span_ops = [span["op"] for span in tx["spans"]] assert all(op == OP.MCP_SERVER for op in span_ops) span_descriptions = [span["description"] for span in tx["spans"]] assert "tools/call tool_a" in span_descriptions assert "tools/call tool_b" in span_descriptions assert "prompts/get prompt_a" in span_descriptions @pytest.mark.parametrize( "send_default_pii, include_prompts", [(True, True), (False, False)], ) def test_prompt_with_dict_result( sentry_init, capture_events, send_default_pii, include_prompts ): """Test prompt handler with dict result instead of GetPromptResult object""" sentry_init( integrations=[MCPIntegration(include_prompts=include_prompts)], traces_sample_rate=1.0, send_default_pii=send_default_pii, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-dict-prompt", transport="stdio") request_ctx.set(mock_ctx) @server.get_prompt() def test_prompt_dict(name, arguments): # Return dict format instead of GetPromptResult object return { "messages": [ {"role": "user", "content": {"text": "Hello from dict"}}, ] } with start_transaction(name="mcp tx"): test_prompt_dict("dict_prompt", {}) (tx,) = events span = tx["spans"][0] # Message count is always captured assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_COUNT] == 1 # Role and content only captured with PII if send_default_pii and include_prompts: assert span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE] == "user" assert ( span["data"][SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT] == "Hello from dict" ) else: assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_ROLE not in span["data"] assert SPANDATA.MCP_PROMPT_RESULT_MESSAGE_CONTENT not in span["data"] def test_resource_without_protocol(sentry_init, capture_events): """Test resource handler with URI without protocol scheme""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-no-proto", transport="stdio") request_ctx.set(mock_ctx) @server.read_resource() def test_resource(uri): return {"data": "test"} with start_transaction(name="mcp tx"): # URI without protocol test_resource("simple-path") (tx,) = events span = tx["spans"][0] assert span["data"][SPANDATA.MCP_RESOURCE_URI] == "simple-path" # No protocol should be set assert SPANDATA.MCP_RESOURCE_PROTOCOL not in span["data"] def test_tool_with_complex_arguments(sentry_init, capture_events): """Test tool handler with complex nested arguments""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-complex", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool_complex(tool_name, arguments): return {"processed": True} with start_transaction(name="mcp tx"): complex_args = { "nested": {"key": "value", "list": [1, 2, 3]}, "string": "test", "number": 42, } test_tool_complex("complex_tool", complex_args) (tx,) = events span = tx["spans"][0] # Complex arguments should be serialized assert span["data"]["mcp.request.argument.nested"] == json.dumps( {"key": "value", "list": [1, 2, 3]} ) assert span["data"]["mcp.request.argument.string"] == '"test"' assert span["data"]["mcp.request.argument.number"] == "42" @pytest.mark.asyncio async def test_async_handlers_mixed(sentry_init, capture_events): """Test mixing sync and async handlers in the same transaction""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context mock_ctx = MockRequestContext(request_id="req-mixed", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def sync_tool(tool_name, arguments): return {"type": "sync"} @server.call_tool() async def async_tool(tool_name, arguments): return {"type": "async"} with start_transaction(name="mcp tx"): sync_result = sync_tool("sync", {}) async_result = await async_tool("async", {}) assert sync_result["type"] == "sync" assert async_result["type"] == "async" (tx,) = events assert len(tx["spans"]) == 2 # Both should be instrumented correctly assert all(span["op"] == OP.MCP_SERVER for span in tx["spans"]) def test_sse_transport_detection(sentry_init, capture_events): """Test that SSE transport is correctly detected via query parameter""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context with SSE transport mock_ctx = MockRequestContext( request_id="req-sse", session_id="session-sse-123", transport="sse" ) request_ctx.set(mock_ctx) @server.call_tool() def test_tool(tool_name, arguments): return {"result": "success"} with start_transaction(name="mcp tx"): result = test_tool("sse_tool", {}) assert result == {"result": "success"} (tx,) = events span = tx["spans"][0] # Check that SSE transport is detected assert span["data"][SPANDATA.MCP_TRANSPORT] == "sse" assert span["data"][SPANDATA.NETWORK_TRANSPORT] == "tcp" assert span["data"][SPANDATA.MCP_SESSION_ID] == "session-sse-123" def test_streamable_http_transport_detection(sentry_init, capture_events): """Test that StreamableHTTP transport is correctly detected via header""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context with StreamableHTTP transport mock_ctx = MockRequestContext( request_id="req-http", session_id="session-http-456", transport="http" ) request_ctx.set(mock_ctx) @server.call_tool() def test_tool(tool_name, arguments): return {"result": "success"} with start_transaction(name="mcp tx"): result = test_tool("http_tool", {}) assert result == {"result": "success"} (tx,) = events span = tx["spans"][0] # Check that HTTP transport is detected assert span["data"][SPANDATA.MCP_TRANSPORT] == "http" assert span["data"][SPANDATA.NETWORK_TRANSPORT] == "tcp" assert span["data"][SPANDATA.MCP_SESSION_ID] == "session-http-456" def test_stdio_transport_detection(sentry_init, capture_events): """Test that stdio transport is correctly detected when no HTTP request""" sentry_init( integrations=[MCPIntegration()], traces_sample_rate=1.0, ) events = capture_events() server = Server("test-server") # Set up mock request context with stdio transport (no HTTP request) mock_ctx = MockRequestContext(request_id="req-stdio", transport="stdio") request_ctx.set(mock_ctx) @server.call_tool() def test_tool(tool_name, arguments): return {"result": "success"} with start_transaction(name="mcp tx"): result = test_tool("stdio_tool", {}) assert result == {"result": "success"} (tx,) = events span = tx["spans"][0] # Check that stdio transport is detected assert span["data"][SPANDATA.MCP_TRANSPORT] == "stdio" assert span["data"][SPANDATA.NETWORK_TRANSPORT] == "pipe" # No session ID for stdio transport assert SPANDATA.MCP_SESSION_ID not in span["data"]
MockGetPromptResult
python
PyCQA__pylint
tests/functional/i/invalid/invalid_hash_returned.py
{ "start": 298, "end": 404 }
class ____: """__hash__ returns <type 'int'>""" def __hash__(self): return 0
SecondGoodHash
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 18665, "end": 18796 }
class ____(_TestIDSTBase): def setup_method(self): self.rdt = int self.dec = 6 self.type = 4
TestIDSTIVnt
python
ApeWorX__ape
src/ape/pytest/coverage.py
{ "start": 5037, "end": 13335 }
class ____(ManagerAccessMixin): def __init__( self, config_wrapper: "ConfigWrapper", project: Optional["ProjectManager"] = None, output_path: Optional[Path] = None, ): self.config_wrapper = config_wrapper self._project = project or self.local_project if output_path: self._output_path = output_path elif hasattr(self._project, "manifest_path"): # Local project. self._output_path = self._project.manifest_path.parent else: self._output_path = Path.cwd() # Data gets initialized lazily (if coverage is needed). self._data: Optional[CoverageData] = None @property def data(self) -> Optional[CoverageData]: if not self.enabled: return None elif self._data is None: # First time being initialized. self._data = CoverageData(self._project, lambda: self._project._contract_sources) return self._data return self._data @property def enabled(self) -> bool: return self.config_wrapper.track_coverage @property def exclusions(self) -> list["ContractFunctionPath"]: return self.config_wrapper.coverage_exclusions def reset(self): if self.data: self.data.reset() def cover( self, traceback: "SourceTraceback", contract: Optional[str] = None, function: Optional[str] = None, ): """ Track the coverage from the given source traceback. Args: traceback (:class:`~ape.types.trace.SourceTraceback`): The class instance containing all the information regarding sources covered for a particular transaction. contract (Optional[str]): Optionally provide the contract's name. This is needed when incrementing function hits that don't have any statements, such as auto-getters. function (Optional[str]): Optionally include function's full name to ensure its hit count is bumped, even when there are not statements found. This is the only way to bump hit counts for auto-getters. """ if not self.data: return last_path: Optional[Path] = None last_pcs: set[int] = set() last_call: Optional[str] = None main_fn = None if (contract and not function) or (function and not contract): raise ValueError("Must provide both function and contract if supplying one of them.") elif contract and function: # Make sure it is the actual source. source_path = traceback[0].source_path if len(traceback) > 0 else None for project in self.data.report.projects: for src in project.sources: # NOTE: We will allow this check to skip if there is no source is the # traceback. This helps increment methods that are missing from the source map. path = self._project.path / src.source_id if source_path is not None and path != source_path: continue # Source containing the auto-getter found. for con in src.contracts: if con.name != contract: continue # Contract containing the auto-getter found. for fn in con.functions: if fn.full_name != function: continue # Auto-getter found. main_fn = fn count_at_start = main_fn.hit_count if main_fn else None for control_flow in traceback: if not control_flow.source_path or not control_flow.pcs: continue new_pcs, new_funcs = self._cover( control_flow, last_path=last_path, last_pcs=last_pcs, last_call=last_call ) if new_pcs: last_path = control_flow.source_path last_pcs = new_pcs if new_funcs: last_call = new_funcs[-1] if count_at_start is not None and main_fn and main_fn.hit_count == count_at_start: # If we get here, the control flow had no statements in it but yet # we were given contract and function information. This happens # for auto-getters where there are no source-map entries but the function # is still called. Thus, we need to bump the hit count for the auto-getter. main_fn.hit_count += 1 def _cover( self, control_flow: "ControlFlow", last_path: Optional[Path] = None, last_pcs: Optional[set[int]] = None, last_call: Optional[str] = None, ) -> tuple[set[int], list[str]]: if not self.data or control_flow.source_path is None: return set(), [] last_pcs = last_pcs or set() pcs = control_flow.pcs if last_path is not None and control_flow.source_path == last_path: # Remove possibly duplicate PCs. This shouldn't happen, # but just in case the compiler made a mistake, we will # still get accurate coverage. new_pcs = pcs - last_pcs else: new_pcs = pcs inc_fn = last_call is None or last_call != control_flow.closure.full_name return self.data.cover(control_flow.source_path, new_pcs, inc_fn_hits=inc_fn) def hit_function(self, contract_source: "ContractSource", method: "MethodABI"): """ Another way to increment a function's hit count. Providers may not offer a way to trace calls but this method is available to still increment function hit counts. Args: contract_source (``ContractSource``): A contract with a known source file. method (``MethodABI``): The method called. """ if not self.data: return for project in self.data.report.projects: for src in project.sources: if src.source_id != contract_source.source_id: continue for contract in src.contracts: if contract.name != contract_source.contract_type.name: continue for function in contract.functions: if function.full_name != method.selector: continue function.hit_count += 1 return def show_session_coverage(self) -> bool: if not self.data or not self.data.report or not self.data.report.sources: return False # Reports are set in ape-config.yaml. reports = self.config_wrapper.ape_test_config.coverage.reports if reports.terminal: verbose = ( reports.terminal.get("verbose", False) if isinstance(reports.terminal, dict) else False ) if isinstance(verbose, str): verbose = verbose.lower() if verbose in ("true", "1", "t"): verbose = True elif verbose in ("false", "0", "f"): verbose = False else: raise ValueError(f"Invalid value for `verbose` config '{verbose}'.") elif isinstance(verbose, int): verbose = bool(verbose) tables = parse_coverage_tables( self.data.report, verbose=verbose, statement=self.provider.supports_tracing ) for idx, table in enumerate(tables): self.chain_manager._reports.echo(table) if idx < len(tables) - 1: click.echo() if self.config_wrapper.xml_coverage: self.data.report.write_xml(self._output_path) if value := self.config_wrapper.html_coverage: verbose = value.get("verbose", False) if isinstance(value, dict) else False self.data.report.write_html(self._output_path, verbose=verbose) return True
CoverageTracker
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/queries/guestbook.py
{ "start": 704, "end": 1012 }
class ____(ndb.Model): """Models an individual Guestbook entry with content and date.""" content = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) @classmethod def query_book(cls, ancestor_key): return cls.query(ancestor=ancestor_key).order(-cls.date)
Greeting
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 60027, "end": 60462 }
class ____(torch.nn.Module): def __init__(self, qengine="fbgemm"): super().__init__() self.qconfig = torch.ao.quantization.get_default_qconfig(qengine) self.fc1 = QuantWrapper(torch.nn.Linear(5, 5).to(dtype=torch.float)) def forward(self, x): x = self.fc1(x) return x def get_example_inputs(self) -> tuple[Any, ...]: return (torch.rand(1, 5),)
AnnotatedSingleLayerLinearModel
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/widgets/control.py
{ "start": 639, "end": 3881 }
class ____(TracebackLinksMixin, GetHelpMixin, QTextEdit, BaseEditMixin): """ Subclass of QTextEdit with features from Spyder's mixins to use as the control widget for IPython widgets """ QT_CLASS = QTextEdit sig_visibility_changed = Signal(bool) sig_go_to_error_requested = Signal(str) sig_focus_changed = Signal() sig_help_requested = Signal(dict) """ This signal is emitted to request help on a given object's `name`. help_data: dict Example `{'name': str, 'ignore_unknown': bool}`. """ def __init__(self, parent=None): QTextEdit.__init__(self, parent) BaseEditMixin.__init__(self) TracebackLinksMixin.__init__(self) GetHelpMixin.__init__(self) self.calltip_widget = CallTipWidget(self, hide_timer_on=False) self.found_results = [] # To not use Spyder calltips obtained through the monitor self.calltips = False # ---- Public methods # ------------------------------------------------------------------------- def insert_horizontal_ruler(self): """ Insert a horizontal ruler with the appropriate color according to our theme in the current cursor position. We have to do this because html hr elements can't be stylized in QTextEdit. Taken from https://stackoverflow.com/a/50016969/438386 """ ruler = QTextFrameFormat() ruler.setHeight(1) ruler.setWidth(10000) ruler.setBackground(QColor(SpyderPalette.COLOR_TEXT_1)) cursor = self.textCursor() cursor.movePosition(QTextCursor.MoveOperation.End) cursor.insertFrame(ruler) # ---- Private methods # ------------------------------------------------------------------------- def _key_paren_left(self, text): """ Action for '(' """ self.current_prompt_pos = self.parentWidget()._prompt_pos if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text) # ---- Qt methods # ------------------------------------------------------------------------- def showEvent(self, event): """Reimplement Qt Method""" self.sig_visibility_changed.emit(True) def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if (key == Qt.Key_ParenLeft and not self.has_selected_text() and self.help_enabled and not self.parent()._reading): self._key_paren_left(text) else: # Let the parent widget handle the key press event QTextEdit.keyPressEvent(self, event) def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.sig_focus_changed.emit() return super().focusInEvent(event) def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.sig_focus_changed.emit() return super().focusOutEvent(event)
ControlWidget
python
huggingface__transformers
src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
{ "start": 41097, "end": 44800 }
class ____(Wav2Vec2ConformerForXVector): def __init__(self, config): super().__init__(config) def freeze_feature_encoder(self): raise AttributeError("Not needed for Wav2Vec2Bert") def forward( self, input_features: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[torch.Tensor] = None, ) -> Union[tuple, XVectorOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states outputs = self.wav2vec2_bert( input_features, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if self.config.use_weighted_layer_sum: hidden_states = outputs[_HIDDEN_STATES_START_POSITION] hidden_states = torch.stack(hidden_states, dim=1) norm_weights = nn.functional.softmax(self.layer_weights, dim=-1) hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1) else: hidden_states = outputs[0] hidden_states = self.projector(hidden_states) for tdnn_layer in self.tdnn: hidden_states = tdnn_layer(hidden_states) # Statistic Pooling if attention_mask is None: mean_features = hidden_states.mean(dim=1) std_features = hidden_states.std(dim=1) else: feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1)) tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths) mean_features = [] std_features = [] for i, length in enumerate(tdnn_output_lengths): mean_features.append(hidden_states[i, :length].mean(dim=0)) std_features.append(hidden_states[i, :length].std(dim=0)) mean_features = torch.stack(mean_features) std_features = torch.stack(std_features) statistic_pooling = torch.cat([mean_features, std_features], dim=-1) output_embeddings = self.feature_extractor(statistic_pooling) logits = self.classifier(output_embeddings) loss = None if labels is not None: loss = self.objective(logits, labels) if not return_dict: output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:] return ((loss,) + output) if loss is not None else output return XVectorOutput( loss=loss, logits=logits, embeddings=output_embeddings, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "Wav2Vec2BertForAudioFrameClassification", "Wav2Vec2BertForCTC", "Wav2Vec2BertForSequenceClassification", "Wav2Vec2BertForXVector", "Wav2Vec2BertModel", "Wav2Vec2BertPreTrainedModel", ]
Wav2Vec2BertForXVector
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 10343, "end": 10551 }
class ____(PolymorphicModel): date = models.DateTimeField() # Define abstract and swappable (being swapped for SwappedModel) models # To test manager validation (should be skipped for such models)
DateModel
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 81995, "end": 82111 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_KEYPOINT_MATCHING_MAPPING
AutoModelForKeypointMatching
python
ray-project__ray
python/ray/tests/test_runtime_env_conda_and_pip.py
{ "start": 2808, "end": 12335 }
class ____: @pytest.mark.skipif( os.environ.get("CI") and sys.platform != "linux", reason="Needs PR wheels built in CI, so only run on linux CI machines.", ) @pytest.mark.parametrize("field", ["conda", "pip"]) @pytest.mark.parametrize("spec_format", ["python_object"]) def test_job_level_gc( self, runtime_env_disable_URI_cache, start_cluster, field, spec_format, tmp_path ): """Tests that job-level conda env is GC'd when the job exits.""" # We must use a single-node cluster. If we simulate a multi-node # cluster then the conda installs will proceed simultaneously, one on # each node, but since they're actually running on the same machine we # get errors. cluster, address = start_cluster ray.init( address, runtime_env=generate_runtime_env_dict(field, spec_format, tmp_path) ) @ray.remote def f(): import pip_install_test # noqa: F401 return True # Ensure that the runtime env has been installed. assert ray.get(f.remote()) # Check that after the task is finished, the runtime_env is not GC'd # because the job is still alive. wait_for_condition(lambda: list_tasks()[0].state == "FINISHED") for _ in range(5): assert not check_local_files_gced(cluster) ray.shutdown() wait_for_condition(lambda: check_local_files_gced(cluster), timeout=30) # Check that we can reconnect with the same env. (In other words, ensure # the conda env was fully deleted and not left in some kind of corrupted # state that prevents reinstalling the same conda env.) ray.init( address, runtime_env=generate_runtime_env_dict(field, spec_format, tmp_path) ) assert ray.get(f.remote()) @pytest.mark.skipif( os.environ.get("CI") and sys.platform != "linux", reason="Requires PR wheels built in CI, so only run on linux CI machines.", ) @pytest.mark.parametrize("field", ["conda", "pip"]) @pytest.mark.parametrize("spec_format", ["python_object"]) def test_detached_actor_gc( self, runtime_env_disable_URI_cache, start_cluster, field, spec_format, tmp_path ): """Tests that detached actor's conda env is GC'd only when it exits.""" cluster, address = start_cluster ray.init( address, namespace="test", runtime_env=generate_runtime_env_dict(field, spec_format, tmp_path), ) @ray.remote class A: def test_import(self): import pip_install_test # noqa: F401 return True a = A.options(name="test", lifetime="detached").remote() ray.get(a.test_import.remote()) assert not check_local_files_gced(cluster) ray.shutdown() ray.init(address, namespace="test") assert not check_local_files_gced(cluster) a = ray.get_actor("test") assert ray.get(a.test_import.remote()) ray.kill(a) wait_for_condition(lambda: check_local_files_gced(cluster), timeout=30) def test_import_in_subprocess(shutdown_only): @ray.remote(runtime_env={"pip": ["pip-install-test==0.5"]}) def f(): return subprocess.run(["python", "-c", "import pip_install_test"]).returncode assert ray.get(f.remote()) == 0 def test_runtime_env_conda_not_exists_not_hang(shutdown_only): """Verify when the conda env doesn't exist, it doesn't hang Ray.""" ray.init(runtime_env={"conda": "env_which_does_not_exist"}) @ray.remote def f(): return 1 refs = [f.remote() for _ in range(5)] for ref in refs: with pytest.raises(ray.exceptions.RuntimeEnvSetupError) as exc_info: ray.get(ref) assert "doesn't exist from the output of `conda info --json`" in str( exc_info.value ) # noqa def test_get_requirements_file(): """Unit test for dependency_utils.get_requirements_file.""" with tempfile.TemporaryDirectory() as tmpdir: # If pip_list is None, we should return the internal pip filename. assert dependency_utils.get_requirements_file( tmpdir, pip_list=None ) == os.path.join(tmpdir, INTERNAL_PIP_FILENAME) # If the internal pip filename is not in pip_list, we should return the internal # pip filename. assert dependency_utils.get_requirements_file( tmpdir, pip_list=["foo", "bar"] ) == os.path.join(tmpdir, INTERNAL_PIP_FILENAME) # If the internal pip filename is in pip_list, we should append numbers to the # end of the filename until we find one that doesn't conflict. assert dependency_utils.get_requirements_file( tmpdir, pip_list=["foo", "bar", f"-r {INTERNAL_PIP_FILENAME}"] ) == os.path.join(tmpdir, f"{INTERNAL_PIP_FILENAME}.1") assert dependency_utils.get_requirements_file( tmpdir, pip_list=[ "foo", "bar", f"{INTERNAL_PIP_FILENAME}.1", f"{INTERNAL_PIP_FILENAME}.2", ], ) == os.path.join(tmpdir, f"{INTERNAL_PIP_FILENAME}.3") # If we can't find a valid filename, we should raise an error. with pytest.raises(RuntimeError) as excinfo: dependency_utils.get_requirements_file( tmpdir, pip_list=[ "foo", "bar", *[ f"{INTERNAL_PIP_FILENAME}.{i}" for i in range(MAX_INTERNAL_PIP_FILENAME_TRIES) ], ], ) assert "Could not find a valid filename for the internal " in str(excinfo.value) def test_working_dir_applies_for_pip_creation(start_cluster, tmp_working_dir): cluster, address = start_cluster with open(Path(tmp_working_dir) / "requirements.txt", "w") as f: f.write("-r more_requirements.txt") with open(Path(tmp_working_dir) / "more_requirements.txt", "w") as f: f.write("pip-install-test==0.5") ray.init( address, runtime_env={ "working_dir": tmp_working_dir, "pip": ["-r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/requirements.txt"], }, ) @ray.remote def test_import(): import pip_install_test return pip_install_test.__name__ assert ray.get(test_import.remote()) == "pip_install_test" def test_working_dir_applies_for_pip_creation_files(start_cluster, tmp_working_dir): """ Different from test_working_dir_applies_for_pip_creation, this test uses a file in `pip`. This file is read by the driver and hence has no relative path to the more_requirements.txt file, so you need to add a ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR} in the referenced path. """ cluster, address = start_cluster with open(Path(tmp_working_dir) / "requirements.txt", "w") as f: f.write("-r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/more_requirements.txt") with open(Path(tmp_working_dir) / "more_requirements.txt", "w") as f: f.write("pip-install-test==0.5") ray.init( address, runtime_env={ "working_dir": tmp_working_dir, "pip": str(Path(tmp_working_dir) / "requirements.txt"), }, ) @ray.remote def test_import(): import pip_install_test return pip_install_test.__name__ assert ray.get(test_import.remote()) == "pip_install_test" @pytest.mark.skipif( os.environ.get("CI") and sys.platform != "linux", reason="Requires PR wheels built in CI, so only run on linux CI machines.", ) def test_working_dir_applies_for_conda_creation(start_cluster, tmp_working_dir): cluster, address = start_cluster with open(Path(tmp_working_dir) / "requirements.txt", "w") as f: f.write("-r more_requirements.txt") with open(Path(tmp_working_dir) / "more_requirements.txt", "w") as f: f.write("pip-install-test==0.5") # Note: if you want to refernce some file in the working dir, you need to use # the ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR} variable. with open(Path(tmp_working_dir) / "environment.yml", "w") as f: f.write("dependencies:\n") f.write(" - pip\n") f.write(" - pip:\n") f.write(" - -r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/more_requirements.txt\n") ray.init( address, runtime_env={ "working_dir": tmp_working_dir, "conda": str(Path(tmp_working_dir) / "environment.yml"), }, ) @ray.remote def test_import(): import pip_install_test return pip_install_test.__name__ assert ray.get(test_import.remote()) == "pip_install_test" def test_pip_install_options(shutdown_only): # Test that this successfully builds a ray runtime environment using pip_install_options @ray.remote( runtime_env={ "pip": { "packages": ["pip-install-test==0.5"], "pip_install_options": [ "--no-cache-dir", "--no-build-isolation", "--disable-pip-version-check", ], } } ) def f(): return True assert ray.get(f.remote()) if __name__ == "__main__": sys.exit(pytest.main(["-sv", __file__]))
TestGC
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-astra/integration_tests/integration_test.py
{ "start": 468, "end": 1874 }
class ____(BaseIntegrationTest): def test_check_valid_config(self): outcome = DestinationAstra().check(logging.getLogger("airbyte"), self.config) assert outcome.status == Status.SUCCEEDED def test_check_invalid_config(self): invalid_config = self.config invalid_config["embedding"]["openai_key"] = 123 outcome = DestinationAstra().check(logging.getLogger("airbyte"), invalid_config) assert outcome.status == Status.FAILED def test_write(self): db_config = ConfigModel.parse_obj(self.config) embedder = create_from_config(db_config.embedding, db_config.processing) db_creds = db_config.indexing astra_client = AstraClient( db_creds.astra_db_endpoint, db_creds.astra_db_app_token, db_creds.astra_db_keyspace, embedder.embedding_dimensions, "cosine" ) astra_client.delete_documents(collection_name=db_creds.collection, filter={}) assert astra_client.count_documents(db_creds.collection) == 0 catalog = self._get_configured_catalog(DestinationSyncMode.overwrite) message1 = self._record("mystream", "text data 1", 1) message2 = self._record("mystream", "text data 2", 2) outcome = list(DestinationAstra().write(self.config, catalog, [message1, message2])) assert astra_client.count_documents(db_creds.collection) == 2
AstraIntegrationTest
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 6376, "end": 7080 }
class ____(TestCase): """Tests for ``nyclces()``""" def test_happy_path(self): """cycle a sequence three times""" r = ["a", "b", "c"] n = mi.ncycles(r, 3) self.assertEqual( ["a", "b", "c", "a", "b", "c", "a", "b", "c"], list(n) ) def test_null_case(self): """asking for 0 cycles should return an empty iterator""" n = mi.ncycles(range(100), 0) self.assertRaises(StopIteration, lambda: next(n)) def test_pathological_case(self): """asking for negative cycles should return an empty iterator""" n = mi.ncycles(range(100), -10) self.assertRaises(StopIteration, lambda: next(n))
NcyclesTests
python
encode__starlette
starlette/formparsers.py
{ "start": 1595, "end": 4157 }
class ____: def __init__(self, headers: Headers, stream: AsyncGenerator[bytes, None]) -> None: assert multipart is not None, "The `python-multipart` library must be installed to use form parsing." self.headers = headers self.stream = stream self.messages: list[tuple[FormMessage, bytes]] = [] def on_field_start(self) -> None: message = (FormMessage.FIELD_START, b"") self.messages.append(message) def on_field_name(self, data: bytes, start: int, end: int) -> None: message = (FormMessage.FIELD_NAME, data[start:end]) self.messages.append(message) def on_field_data(self, data: bytes, start: int, end: int) -> None: message = (FormMessage.FIELD_DATA, data[start:end]) self.messages.append(message) def on_field_end(self) -> None: message = (FormMessage.FIELD_END, b"") self.messages.append(message) def on_end(self) -> None: message = (FormMessage.END, b"") self.messages.append(message) async def parse(self) -> FormData: # Callbacks dictionary. callbacks: QuerystringCallbacks = { "on_field_start": self.on_field_start, "on_field_name": self.on_field_name, "on_field_data": self.on_field_data, "on_field_end": self.on_field_end, "on_end": self.on_end, } # Create the parser. parser = multipart.QuerystringParser(callbacks) field_name = b"" field_value = b"" items: list[tuple[str, str | UploadFile]] = [] # Feed the parser with data from the request. async for chunk in self.stream: if chunk: parser.write(chunk) else: parser.finalize() messages = list(self.messages) self.messages.clear() for message_type, message_bytes in messages: if message_type == FormMessage.FIELD_START: field_name = b"" field_value = b"" elif message_type == FormMessage.FIELD_NAME: field_name += message_bytes elif message_type == FormMessage.FIELD_DATA: field_value += message_bytes elif message_type == FormMessage.FIELD_END: name = unquote_plus(field_name.decode("latin-1")) value = unquote_plus(field_value.decode("latin-1")) items.append((name, value)) return FormData(items)
FormParser
python
pyca__cryptography
tests/x509/test_x509.py
{ "start": 75332, "end": 97450 }
class ____: @pytest.mark.parametrize( ("path", "loader_func"), [ [ os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ], [ os.path.join("x509", "requests", "rsa_sha1.der"), x509.load_der_x509_csr, ], ], ) def test_load_rsa_certificate_request(self, path, loader_func, backend): request = _load_cert(path, loader_func) assert isinstance(request.signature_hash_algorithm, hashes.SHA1) assert ( request.signature_algorithm_oid == SignatureAlgorithmOID.RSA_WITH_SHA1 ) public_key = request.public_key() assert isinstance(public_key, rsa.RSAPublicKey) assert ( request.public_key_algorithm_oid == PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5 ) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute(NameOID.COMMON_NAME, "cryptography.io"), ] extensions = request.extensions assert isinstance(extensions, x509.Extensions) assert list(extensions) == [] def test_load_legacy_pem_header(self, backend): cert = _load_cert( os.path.join("x509", "requests", "ec_sha256_old_header.pem"), x509.load_pem_x509_csr, ) assert isinstance(cert, x509.CertificateSigningRequest) def test_invalid_pem(self, backend): with pytest.raises(ValueError, match="Unable to load"): x509.load_pem_x509_csr(b"notacsr") crl = load_vectors_from_file( filename=os.path.join("x509", "custom", "crl_empty.pem"), loader=lambda pemfile: pemfile.read(), mode="rb", ) with pytest.raises(ValueError, match="Valid PEM but no"): x509.load_pem_x509_csr(crl) @pytest.mark.parametrize( "loader_func", [x509.load_pem_x509_csr, x509.load_der_x509_csr] ) def test_invalid_certificate_request(self, loader_func, backend): with pytest.raises(ValueError): loader_func(b"notacsr") def test_unsupported_signature_hash_algorithm_request(self, backend): request = _load_cert( os.path.join("x509", "requests", "rsa_md4.pem"), x509.load_pem_x509_csr, ) with raises_unsupported_algorithm(None): request.signature_hash_algorithm def test_invalid_version(self, backend): with pytest.raises(x509.InvalidVersion): _load_cert( os.path.join("x509", "requests", "bad-version.pem"), x509.load_pem_x509_csr, ) def test_duplicate_extension(self, backend): request = _load_cert( os.path.join("x509", "requests", "two_basic_constraints.pem"), x509.load_pem_x509_csr, ) with pytest.raises(x509.DuplicateExtension) as exc: request.extensions assert exc.value.oid == ExtensionOID.BASIC_CONSTRAINTS def test_unsupported_critical_extension(self, backend): request = _load_cert( os.path.join( "x509", "requests", "unsupported_extension_critical.pem" ), x509.load_pem_x509_csr, ) ext = request.extensions.get_extension_for_oid( x509.ObjectIdentifier("1.2.3.4") ) assert isinstance(ext.value, x509.UnrecognizedExtension) assert ext.value.value == b"value" def test_unsupported_extension(self, backend): request = _load_cert( os.path.join("x509", "requests", "unsupported_extension.pem"), x509.load_pem_x509_csr, ) extensions = request.extensions assert len(extensions) == 1 assert extensions[0].oid == x509.ObjectIdentifier("1.2.3.4") assert extensions[0].value == x509.UnrecognizedExtension( x509.ObjectIdentifier("1.2.3.4"), b"value" ) def test_no_extension_with_other_attributes(self, backend): request = _load_cert( os.path.join("x509", "requests", "challenge-unstructured.pem"), x509.load_pem_x509_csr, ) assert len(request.extensions) == 0 def test_request_basic_constraints(self, backend): request = _load_cert( os.path.join("x509", "requests", "basic_constraints.pem"), x509.load_pem_x509_csr, ) extensions = request.extensions assert isinstance(extensions, x509.Extensions) assert list(extensions) == [ x509.Extension( ExtensionOID.BASIC_CONSTRAINTS, True, x509.BasicConstraints(ca=True, path_length=1), ), ] def test_subject_alt_name(self, backend): request = _load_cert( os.path.join("x509", "requests", "san_rsa_sha1.pem"), x509.load_pem_x509_csr, ) ext = request.extensions.get_extension_for_class( x509.SubjectAlternativeName ) assert list(ext.value) == [ x509.DNSName("cryptography.io"), x509.DNSName("sub.cryptography.io"), ] def test_freeipa_bad_critical(self, backend): csr = _load_cert( os.path.join("x509", "requests", "freeipa-bad-critical.pem"), x509.load_pem_x509_csr, ) with pytest.raises(ValueError): csr.extensions def test_public_bytes_pem(self, backend): # Load an existing CSR. request = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) # Encode it to PEM and load it back. request = x509.load_pem_x509_csr( request.public_bytes( encoding=serialization.Encoding.PEM, ), ) # We should recover what we had to start with. assert isinstance(request.signature_hash_algorithm, hashes.SHA1) public_key = request.public_key() assert isinstance(public_key, rsa.RSAPublicKey) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute(NameOID.COMMON_NAME, "cryptography.io"), ] def test_public_bytes_der(self, backend): # Load an existing CSR. request = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) # Encode it to DER and load it back. request = x509.load_der_x509_csr( request.public_bytes( encoding=serialization.Encoding.DER, ), ) # We should recover what we had to start with. assert isinstance(request.signature_hash_algorithm, hashes.SHA1) public_key = request.public_key() assert isinstance(public_key, rsa.RSAPublicKey) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Texas"), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute(NameOID.COMMON_NAME, "cryptography.io"), ] def test_signature(self, backend): request = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) assert request.signature == binascii.unhexlify( b"8364c86ffbbfe0bfc9a21f831256658ca8989741b80576d36f08a934603a43b1" b"837246d00167a518abb1de7b51a1e5b7ebea14944800818b1a923c804f120a0d" b"624f6310ef79e8612755c2b01dcc7f59dfdbce0db3f2630f185f504b8c17af80" b"cbd364fa5fda68337153930948226cd4638287a0aed6524d3006885c19028a1e" b"e2f5a91d6e77dbaa0b49996ee0a0c60b55b61bd080a08bb34aa7f3e07e91f37f" b"6a11645be2d8654c1570dcda145ed7cc92017f7d53225d7f283f3459ec5bda41" b"cf6dd75d43676c543483385226b7e4fa29c8739f1b0eaf199613593991979862" b"e36181e8c4c270c354b7f52c128db1b70639823324c7ea24791b7bc3d7005f3b" ) @pytest.mark.supported( only_if=lambda backend: backend.signature_hash_supported( hashes.SHA1() ), skip_message="Does not support SHA-1 signature.", ) def test_tbs_certrequest_bytes(self, backend): request = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) assert request.tbs_certrequest_bytes == binascii.unhexlify( b"308201840201003057310b3009060355040613025553310e300c060355040813" b"055465786173310f300d0603550407130641757374696e310d300b060355040a" b"130450794341311830160603550403130f63727970746f6772617068792e696f" b"30820122300d06092a864886f70d01010105000382010f003082010a02820101" b"00a840a78460cb861066dfa3045a94ba6cf1b7ab9d24c761cffddcc2cb5e3f1d" b"c3e4be253e7039ef14fe9d6d2304f50d9f2e1584c51530ab75086f357138bff7" b"b854d067d1d5f384f1f2f2c39cc3b15415e2638554ef8402648ae3ef08336f22" b"b7ecc6d4331c2b21c3091a7f7a9518180754a646640b60419e4cc6f5c798110a" b"7f030a639fe87e33b4776dfcd993940ec776ab57a181ad8598857976dc303f9a" b"573ca619ab3fe596328e92806b828683edc17cc256b41948a2bfa8d047d2158d" b"3d8e069aa05fa85b3272abb1c4b4422b6366f3b70e642377b145cd6259e5d3e7" b"db048d51921e50766a37b1b130ee6b11f507d20a834001e8de16a92c14f2e964" b"a30203010001a000" ) assert request.signature_hash_algorithm is not None public_key = request.public_key() assert isinstance(public_key, rsa.RSAPublicKey) public_key.verify( request.signature, request.tbs_certrequest_bytes, padding.PKCS1v15(), request.signature_hash_algorithm, ) def test_public_bytes_invalid_encoding(self, backend): request = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) with pytest.raises(TypeError): request.public_bytes("NotAnEncoding") # type: ignore[arg-type] def test_signature_invalid(self, backend): request = _load_cert( os.path.join("x509", "requests", "invalid_signature.pem"), x509.load_pem_x509_csr, ) assert not request.is_signature_valid def test_signature_valid(self, backend): request = _load_cert( os.path.join("x509", "requests", "rsa_sha256.pem"), x509.load_pem_x509_csr, ) assert request.is_signature_valid @pytest.mark.parametrize( ("request_path", "loader_func", "encoding"), [ ( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, serialization.Encoding.PEM, ), ( os.path.join("x509", "requests", "rsa_sha1.der"), x509.load_der_x509_csr, serialization.Encoding.DER, ), ], ) def test_public_bytes_match( self, request_path, loader_func, encoding, backend ): request_bytes = load_vectors_from_file( request_path, lambda pemfile: pemfile.read(), mode="rb" ) request = loader_func(request_bytes) serialized = request.public_bytes(encoding) assert serialized == request_bytes def test_eq(self, backend): request1 = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) request2 = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) assert request1 == request2 def test_ne(self, backend): request1 = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) request2 = _load_cert( os.path.join("x509", "requests", "san_rsa_sha1.pem"), x509.load_pem_x509_csr, ) assert request1 != request2 assert request1 != object() def test_ordering_unsupported(self, backend): csr = _load_cert( os.path.join("x509", "requests", "rsa_sha256.pem"), x509.load_pem_x509_csr, ) csr2 = _load_cert( os.path.join("x509", "requests", "rsa_sha256.pem"), x509.load_pem_x509_csr, ) with pytest.raises(TypeError, match="'>' not supported"): csr > csr2 # type: ignore[operator] def test_hash(self, backend): request1 = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) request2 = _load_cert( os.path.join("x509", "requests", "rsa_sha1.pem"), x509.load_pem_x509_csr, ) request3 = _load_cert( os.path.join("x509", "requests", "san_rsa_sha1.pem"), x509.load_pem_x509_csr, ) assert hash(request1) == hash(request2) assert hash(request1) != hash(request3) @pytest.mark.parametrize( ("hashalg", "hashalg_oid"), [ (hashes.SHA224, x509.SignatureAlgorithmOID.RSA_WITH_SHA224), (hashes.SHA256, x509.SignatureAlgorithmOID.RSA_WITH_SHA256), (hashes.SHA384, x509.SignatureAlgorithmOID.RSA_WITH_SHA384), (hashes.SHA512, x509.SignatureAlgorithmOID.RSA_WITH_SHA512), (hashes.SHA3_224, x509.SignatureAlgorithmOID.RSA_WITH_SHA3_224), (hashes.SHA3_256, x509.SignatureAlgorithmOID.RSA_WITH_SHA3_256), (hashes.SHA3_384, x509.SignatureAlgorithmOID.RSA_WITH_SHA3_384), (hashes.SHA3_512, x509.SignatureAlgorithmOID.RSA_WITH_SHA3_512), ], ) def test_build_cert( self, rsa_key_2048: rsa.RSAPrivateKey, hashalg, hashalg_oid, backend ): if not backend.signature_hash_supported(hashalg()): pytest.skip(f"{hashalg} signature not supported") issuer_private_key = rsa_key_2048 subject_private_key = rsa_key_2048 not_valid_before = datetime.datetime(2002, 1, 1, 12, 1) not_valid_after = datetime.datetime(2030, 12, 31, 8, 30) builder = ( x509.CertificateBuilder() .serial_number(777) .issuer_name( x509.Name( [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io" ), ] ) ) .subject_name( x509.Name( [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA"), x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io" ), ] ) ) .public_key(subject_private_key.public_key()) .add_extension( x509.BasicConstraints(ca=False, path_length=None), True, ) .add_extension( x509.SubjectAlternativeName([x509.DNSName("cryptography.io")]), critical=False, ) .not_valid_before(not_valid_before) .not_valid_after(not_valid_after) ) cert = builder.sign(issuer_private_key, hashalg(), backend) assert cert.version is x509.Version.v3 public_key = cert.public_key() assert isinstance(public_key, rsa.RSAPublicKey) assert ( cert.public_key_algorithm_oid == PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5 ) assert cert.signature_algorithm_oid == hashalg_oid assert type(cert.signature_hash_algorithm) is hashalg _check_cert_times( cert, not_valid_before=not_valid_before, not_valid_after=not_valid_after, ) basic_constraints = cert.extensions.get_extension_for_oid( ExtensionOID.BASIC_CONSTRAINTS ) assert isinstance(basic_constraints.value, x509.BasicConstraints) assert basic_constraints.value.ca is False assert basic_constraints.value.path_length is None subject_alternative_name = cert.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME ) assert isinstance( subject_alternative_name.value, x509.SubjectAlternativeName ) assert list(subject_alternative_name.value) == [ x509.DNSName("cryptography.io"), ] def test_build_cert_private_type_encoding( self, rsa_key_2048: rsa.RSAPrivateKey, backend ): issuer_private_key = rsa_key_2048 subject_private_key = rsa_key_2048 not_valid_before = datetime.datetime(2002, 1, 1, 12, 1) not_valid_after = datetime.datetime(2030, 12, 31, 8, 30) name = x509.Name( [ x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas", _ASN1Type.PrintableString, ), x509.NameAttribute(NameOID.LOCALITY_NAME, "Austin"), x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io", _ASN1Type.IA5String, ), ] ) builder = ( x509.CertificateBuilder() .serial_number(777) .issuer_name(name) .subject_name(name) .public_key(subject_private_key.public_key()) .not_valid_before(not_valid_before) .not_valid_after(not_valid_after) ) cert = builder.sign(issuer_private_key, hashes.SHA256(), backend) for dn in (cert.subject, cert.issuer): assert ( dn.get_attributes_for_oid(NameOID.STATE_OR_PROVINCE_NAME)[ 0 ]._type == _ASN1Type.PrintableString ) assert ( dn.get_attributes_for_oid(NameOID.STATE_OR_PROVINCE_NAME)[ 0 ]._type == _ASN1Type.PrintableString ) assert ( dn.get_attributes_for_oid(NameOID.LOCALITY_NAME)[0]._type == _ASN1Type.UTF8String ) def test_build_cert_printable_string_country_name( self, rsa_key_2048: rsa.RSAPrivateKey, backend ): issuer_private_key = rsa_key_2048 subject_private_key = rsa_key_2048 not_valid_before = datetime.datetime(2002, 1, 1, 12, 1) not_valid_after = datetime.datetime(2030, 12, 31, 8, 30) builder = ( x509.CertificateBuilder() .serial_number(777) .issuer_name( x509.Name( [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute( NameOID.JURISDICTION_COUNTRY_NAME, "US" ), x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), ] ) ) .subject_name( x509.Name( [ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute( NameOID.JURISDICTION_COUNTRY_NAME, "US" ), x509.NameAttribute( NameOID.STATE_OR_PROVINCE_NAME, "Texas" ), ] ) ) .public_key(subject_private_key.public_key()) .not_valid_before(not_valid_before) .not_valid_after(not_valid_after) ) cert = builder.sign(issuer_private_key, hashes.SHA256(), backend) parsed = test_support.test_parse_certificate( cert.public_bytes(serialization.Encoding.DER) ) # Check that each value was encoded as an ASN.1 PRINTABLESTRING. assert parsed.issuer_value_tags[0] == 0x13 assert parsed.subject_value_tags[0] == 0x13 assert parsed.issuer_value_tags[1] == 0x13 assert parsed.subject_value_tags[1] == 0x13
TestRSACertificateRequest
python
ethereum__web3.py
web3/_utils/filters.py
{ "start": 5307, "end": 5995 }
class ____(BaseFilter): def __init__(self, filter_id: HexStr, eth_module: "AsyncEth") -> None: self.eth_module = eth_module super().__init__(filter_id) async def get_new_entries(self) -> list[LogReceipt]: filter_changes = await self.eth_module.get_filter_changes(self.filter_id) log_entries = self._filter_valid_entries(filter_changes) return self._format_log_entries(log_entries) async def get_all_entries(self) -> list[LogReceipt]: filter_logs = await self.eth_module.get_filter_logs(self.filter_id) log_entries = self._filter_valid_entries(filter_logs) return self._format_log_entries(log_entries)
AsyncFilter
python
redis__redis-py
redis/auth/token_manager.py
{ "start": 1113, "end": 1613 }
class ____: def __init__(self, max_attempts: int, delay_in_ms: float): self.max_attempts = max_attempts self.delay_in_ms = delay_in_ms def get_max_attempts(self) -> int: """ Retry attempts before exception will be thrown. :return: int """ return self.max_attempts def get_delay_in_ms(self) -> float: """ Delay between retries in seconds. :return: int """ return self.delay_in_ms
RetryPolicy
python
django__django
tests/forms_tests/widget_tests/test_hiddeninput.py
{ "start": 86, "end": 1023 }
class ____(WidgetTest): widget = HiddenInput() def test_render(self): self.check_html( self.widget, "email", "", html='<input type="hidden" name="email">' ) def test_use_required_attribute(self): # Always False to avoid browser validation on inputs hidden from the # user. self.assertIs(self.widget.use_required_attribute(None), False) self.assertIs(self.widget.use_required_attribute(""), False) self.assertIs(self.widget.use_required_attribute("foo"), False) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = CharField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, False) self.assertHTMLEqual( '<input type="hidden" name="field" id="id_field">', form.render(), )
HiddenInputTest
python
wandb__wandb
wandb/vendor/pygments/lexers/asm.py
{ "start": 6626, "end": 12787 }
class ____(RegexLexer): """ For HSAIL assembly code. .. versionadded:: 2.2 """ name = 'HSAIL' aliases = ['hsail', 'hsa'] filenames = ['*.hsail'] mimetypes = ['text/x-hsail'] string = r'"[^"]*?"' identifier = r'[a-zA-Z_][\w.]*' # Registers register_number = r'[0-9]+' register = r'(\$(c|s|d|q)' + register_number + ')' # Qualifiers alignQual = r'(align\(\d+\))' widthQual = r'(width\((\d+|all)\))' allocQual = r'(alloc\(agent\))' # Instruction Modifiers roundingMod = (r'((_ftz)?(_up|_down|_zero|_near))') datatypeMod = (r'_(' # packedTypes r'u8x4|s8x4|u16x2|s16x2|u8x8|s8x8|u16x4|s16x4|u32x2|s32x2|' r'u8x16|s8x16|u16x8|s16x8|u32x4|s32x4|u64x2|s64x2|' r'f16x2|f16x4|f16x8|f32x2|f32x4|f64x2|' # baseTypes r'u8|s8|u16|s16|u32|s32|u64|s64|' r'b128|b8|b16|b32|b64|b1|' r'f16|f32|f64|' # opaqueType r'roimg|woimg|rwimg|samp|sig32|sig64)') # Numeric Constant float = r'((\d+\.)|(\d*\.\d+))[eE][+-]?\d+' hexfloat = r'0[xX](([0-9a-fA-F]+\.[0-9a-fA-F]*)|([0-9a-fA-F]*\.[0-9a-fA-F]+))[pP][+-]?\d+' ieeefloat = r'0((h|H)[0-9a-fA-F]{4}|(f|F)[0-9a-fA-F]{8}|(d|D)[0-9a-fA-F]{16})' tokens = { 'root': [ include('whitespace'), include('comments'), (string, String), (r'@' + identifier + ':?', Name.Label), (register, Name.Variable.Anonymous), include('keyword'), (r'&' + identifier, Name.Variable.Global), (r'%' + identifier, Name.Variable), (hexfloat, Number.Hex), (r'0[xX][a-fA-F0-9]+', Number.Hex), (ieeefloat, Number.Float), (float, Number.Float), ('\d+', Number.Integer), (r'[=<>{}\[\]()*.,:;!]|x\b', Punctuation) ], 'whitespace': [ (r'(\n|\s)+', Text), ], 'comments': [ (r'/\*.*?\*/', Comment.Multiline), (r'//.*?\n', Comment.Singleline), ], 'keyword': [ # Types (r'kernarg' + datatypeMod, Keyword.Type), # Regular keywords (r'\$(full|base|small|large|default|zero|near)', Keyword), (words(( 'module', 'extension', 'pragma', 'prog', 'indirect', 'signature', 'decl', 'kernel', 'function', 'enablebreakexceptions', 'enabledetectexceptions', 'maxdynamicgroupsize', 'maxflatgridsize', 'maxflatworkgroupsize', 'requireddim', 'requiredgridsize', 'requiredworkgroupsize', 'requirenopartialworkgroups'), suffix=r'\b'), Keyword), # instructions (roundingMod, Keyword), (datatypeMod, Keyword), (r'_(' + alignQual + '|' + widthQual + ')', Keyword), (r'_kernarg', Keyword), (r'(nop|imagefence)\b', Keyword), (words(( 'cleardetectexcept', 'clock', 'cuid', 'debugtrap', 'dim', 'getdetectexcept', 'groupbaseptr', 'kernargbaseptr', 'laneid', 'maxcuid', 'maxwaveid', 'packetid', 'setdetectexcept', 'waveid', 'workitemflatabsid', 'workitemflatid', 'nullptr', 'abs', 'bitrev', 'currentworkgroupsize', 'currentworkitemflatid', 'fract', 'ncos', 'neg', 'nexp2', 'nlog2', 'nrcp', 'nrsqrt', 'nsin', 'nsqrt', 'gridgroups', 'gridsize', 'not', 'sqrt', 'workgroupid', 'workgroupsize', 'workitemabsid', 'workitemid', 'ceil', 'floor', 'rint', 'trunc', 'add', 'bitmask', 'borrow', 'carry', 'copysign', 'div', 'rem', 'sub', 'shl', 'shr', 'and', 'or', 'xor', 'unpackhi', 'unpacklo', 'max', 'min', 'fma', 'mad', 'bitextract', 'bitselect', 'shuffle', 'cmov', 'bitalign', 'bytealign', 'lerp', 'nfma', 'mul', 'mulhi', 'mul24hi', 'mul24', 'mad24', 'mad24hi', 'bitinsert', 'combine', 'expand', 'lda', 'mov', 'pack', 'unpack', 'packcvt', 'unpackcvt', 'sad', 'sementp', 'ftos', 'stof', 'cmp', 'ld', 'st', '_eq', '_ne', '_lt', '_le', '_gt', '_ge', '_equ', '_neu', '_ltu', '_leu', '_gtu', '_geu', '_num', '_nan', '_seq', '_sne', '_slt', '_sle', '_sgt', '_sge', '_snum', '_snan', '_sequ', '_sneu', '_sltu', '_sleu', '_sgtu', '_sgeu', 'atomic', '_ld', '_st', '_cas', '_add', '_and', '_exch', '_max', '_min', '_or', '_sub', '_wrapdec', '_wrapinc', '_xor', 'ret', 'cvt', '_readonly', '_kernarg', '_global', 'br', 'cbr', 'sbr', '_scacq', '_screl', '_scar', '_rlx', '_wave', '_wg', '_agent', '_system', 'ldimage', 'stimage', '_v2', '_v3', '_v4', '_1d', '_2d', '_3d', '_1da', '_2da', '_1db', '_2ddepth', '_2dadepth', '_width', '_height', '_depth', '_array', '_channelorder', '_channeltype', 'querysampler', '_coord', '_filter', '_addressing', 'barrier', 'wavebarrier', 'initfbar', 'joinfbar', 'waitfbar', 'arrivefbar', 'leavefbar', 'releasefbar', 'ldf', 'activelaneid', 'activelanecount', 'activelanemask', 'activelanepermute', 'call', 'scall', 'icall', 'alloca', 'packetcompletionsig', 'addqueuewriteindex', 'casqueuewriteindex', 'ldqueuereadindex', 'stqueuereadindex', 'readonly', 'global', 'private', 'group', 'spill', 'arg', '_upi', '_downi', '_zeroi', '_neari', '_upi_sat', '_downi_sat', '_zeroi_sat', '_neari_sat', '_supi', '_sdowni', '_szeroi', '_sneari', '_supi_sat', '_sdowni_sat', '_szeroi_sat', '_sneari_sat', '_pp', '_ps', '_sp', '_ss', '_s', '_p', '_pp_sat', '_ps_sat', '_sp_sat', '_ss_sat', '_s_sat', '_p_sat')), Keyword), # Integer types (r'i[1-9]\d*', Keyword) ] }
HsailLexer
python
pytorch__pytorch
test/onnx/model_defs/lstm_flattening_result.py
{ "start": 896, "end": 1503 }
class ____(nn.Module): def __init__(self, input_size, hidden_size, layers, bidirect, dropout, batch_first): super().__init__() self.batch_first = batch_first self.inner_model = nn.LSTM( input_size=input_size, hidden_size=hidden_size, num_layers=layers, bidirectional=bidirect, dropout=dropout, batch_first=batch_first, ) def forward(self, input, hx=None): output, (hidden, cell) = self.inner_model.forward(input, hx) return output, hidden, cell
LstmFlatteningResultWithoutSeqLength
python
huggingface__transformers
tests/models/llama4/test_image_processing_llama4.py
{ "start": 3011, "end": 4841 }
class ____(ImageProcessingTestMixin, unittest.TestCase): test_slow_image_processor = False fast_image_processing_class = Llama4ImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = Llama4ImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processor, "do_resize")) self.assertTrue(hasattr(image_processor, "size")) self.assertTrue(hasattr(image_processor, "do_normalize")) self.assertTrue(hasattr(image_processor, "image_mean")) self.assertTrue(hasattr(image_processor, "image_std")) self.assertTrue(hasattr(image_processor, "do_convert_rgb")) def test_split_tiles(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) image = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)[0] processed_images = image_processor( image, max_patches=16, ) self.assertEqual(len(processed_images.pixel_values), 1) self.assertEqual(processed_images.pixel_values[0].shape[0], 17) self.assertEqual(processed_images.pixel_values[0].shape[-2:], (20, 20)) @unittest.skip("Broken on main right now. Should be fixable!") def test_image_processor_save_load_with_autoimageprocessor(self): pass
Llama4ImageProcessingTest
python
catalyst-team__catalyst
catalyst/contrib/layers/arcmargin.py
{ "start": 69, "end": 1937 }
class ____(nn.Module): """Implementation of Arc Margin Product. Args: in_features: size of each input sample. out_features: size of each output sample. Shape: - Input: :math:`(batch, H_{in})` where :math:`H_{in} = in\_features`. - Output: :math:`(batch, H_{out})` where :math:`H_{out} = out\_features`. Example: >>> layer = ArcMarginProduct(5, 10) >>> loss_fn = nn.CrosEntropyLoss() >>> embedding = torch.randn(3, 5, requires_grad=True) >>> target = torch.empty(3, dtype=torch.long).random_(10) >>> output = layer(embedding) >>> loss = loss_fn(output, target) >>> self.engine.backward(loss) """ def __init__(self, in_features: int, out_features: int): # noqa: D107 super(ArcMarginProduct, self).__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.Tensor(out_features, in_features)) nn.init.xavier_uniform_(self.weight) def __repr__(self) -> str: """Object representation.""" rep = ( "ArcMarginProduct(" f"in_features={self.in_features}," f"out_features={self.out_features}" ")" ) return rep def forward(self, input: torch.Tensor) -> torch.Tensor: """ Args: input: input features, expected shapes ``BxF`` where ``B`` is batch dimension and ``F`` is an input feature dimension. Returns: tensor (logits) with shapes ``BxC`` where ``C`` is a number of classes (out_features). """ cosine = F.linear(F.normalize(input), F.normalize(self.weight)) return cosine __all__ = ["ArcMarginProduct"]
ArcMarginProduct
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_variables.py
{ "start": 8333, "end": 9448 }
class ____: @pytest.mark.parametrize( ("keys_to_create", "key_to_delete"), [ (["key1", "key2"], "key1"), (["key3/with_slash", "key4"], "key3/with_slash"), ], ) def test_should_delete_variable(self, client, session, keys_to_create, key_to_delete): for i, key in enumerate(keys_to_create, 1): Variable.set(key=key, value=str(i)) vars = session.query(Variable).all() assert len(vars) == len(keys_to_create) response = client.delete(f"/execution/variables/{key_to_delete}") assert response.status_code == 204 vars = session.query(Variable).all() assert len(vars) == len(keys_to_create) - 1 def test_should_not_delete_variable(self, client, session): Variable.set(key="key", value="value") vars = session.query(Variable).all() assert len(vars) == 1 response = client.delete("/execution/variables/non_existent_key") assert response.status_code == 204 vars = session.query(Variable).all() assert len(vars) == 1
TestDeleteVariable
python
keon__algorithms
tests/test_map.py
{ "start": 5709, "end": 5938 }
class ____(unittest.TestCase): def test_is_anagram(self): self.assertTrue(is_anagram("anagram", "nagaram")) self.assertFalse(is_anagram("rat", "car")) if __name__ == "__main__": unittest.main()
TestIsAnagram
python
mlflow__mlflow
mlflow/server/auth/db/models.py
{ "start": 1948, "end": 2514 }
class ____(Base): __tablename__ = "registered_model_permissions" id = Column(Integer(), primary_key=True) name = Column(String(255), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False) permission = Column(String(255)) __table_args__ = (UniqueConstraint("name", "user_id", name="unique_name_user"),) def to_mlflow_entity(self): return RegisteredModelPermission( name=self.name, user_id=self.user_id, permission=self.permission, )
SqlRegisteredModelPermission
python
getsentry__sentry
tests/sentry/auth/providers/test_oauth2.py
{ "start": 423, "end": 938 }
class ____(OAuth2Provider): name = "dummy" key = "oauth2_dummy" def get_client_id(self) -> str: raise NotImplementedError def get_client_secret(self) -> str: raise NotImplementedError def get_refresh_token_url(self) -> str: raise NotImplementedError def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]: raise NotImplementedError def build_config(self, state): raise NotImplementedError @control_silo_test
DummyOAuth2Provider
python
kamyu104__LeetCode-Solutions
Python/find-the-derangement-of-an-array.py
{ "start": 29, "end": 365 }
class ____(object): def findDerangement(self, n): """ :type n: int :rtype: int """ M = 1000000007 mul, total = 1, 0 for i in reversed(xrange(n+1)): total = (total + M + (1 if i % 2 == 0 else -1) * mul) % M mul = (mul * i) % M return total
Solution
python
getsentry__sentry
tests/sentry/workflow_engine/test_base.py
{ "start": 5396, "end": 13221 }
class ____(TestCase, OccurrenceTestMixin): def create_snuba_query(self, **kwargs): return SnubaQuery.objects.create( type=SnubaQuery.Type.ERROR.value, dataset="events", aggregate="count()", time_window=60, resolution=60, **kwargs, ) def create_snuba_query_subscription( self, project_id: int | None = None, snuba_query_id: int | None = None, **kwargs ): if snuba_query_id is None: snuba_query_id = self.create_snuba_query().id if project_id is None: project_id = self.project.id return QuerySubscription.objects.create( project_id=project_id, snuba_query_id=snuba_query_id, **kwargs, ) def create_event( self, project_id: int, timestamp: datetime, fingerprint: str, environment=None, level="error", tags: list[list[str]] | None = None, ) -> Event: data = { "timestamp": timestamp.isoformat(), "environment": environment, "fingerprint": [fingerprint], "level": level, "user": {"id": uuid4().hex}, "exception": { "values": [ { "type": "IntegrationError", "value": "Identity not found.", } ] }, } if tags: data["tags"] = tags return self.store_event( data=data, project_id=project_id, assert_no_errors=False, default_event_type=EventType.ERROR, ) def create_detector_and_workflow( self, name_prefix: str = "test", workflow_triggers: DataConditionGroup | None = None, detector_type: str = MetricIssue.slug, project: Project | None = None, **kwargs, ) -> tuple[Workflow, Detector, DetectorWorkflow, DataConditionGroup]: """ Create a Workflow, Detector, DetectorWorkflow, and DataConditionGroup for testing. These models are configured to work together to test the workflow engine. """ workflow_triggers = workflow_triggers or self.create_data_condition_group() if not workflow_triggers.conditions.exists(): # create a trigger condition for a new event self.create_data_condition( condition_group=workflow_triggers, type=Condition.EVENT_SEEN_COUNT, comparison=1, condition_result=True, ) workflow = self.create_workflow( name=f"{name_prefix}_workflow", when_condition_group=workflow_triggers, **kwargs, ) detector = self.create_detector( name=f"{name_prefix}_detector", type=detector_type, project=project if project else self.project, ) detector_workflow = self.create_detector_workflow( detector=detector, workflow=workflow, ) return workflow, detector, detector_workflow, workflow_triggers def create_test_query_data_source( self, detector: Detector ) -> tuple[SnubaQuery, QuerySubscription, DataSource, DataPacket]: """ Create a DataSource and DataPacket for testing; this will create a QuerySubscriptionUpdate and link it to a data_source. A detector is required to create this test data, so we can ensure that the detector has a condition to evaluate for the data_packet that evalutes to true. """ with self.tasks(): snuba_query = create_snuba_query( query_type=SnubaQuery.Type.ERROR, dataset=Dataset.Events, query="hello", aggregate="count()", time_window=timedelta(minutes=1), resolution=timedelta(minutes=1), environment=self.environment, event_types=[SnubaQueryEventType.EventType.ERROR], ) query_subscription = create_snuba_subscription( project=detector.project, subscription_type=INCIDENTS_SNUBA_SUBSCRIPTION_TYPE, snuba_query=snuba_query, ) subscription_update = ProcessedSubscriptionUpdate( subscription_id=str(query_subscription.id), values={"value": 1}, timestamp=datetime.now(UTC), entity="test-entity", ) data_source = self.create_data_source( source_id=str(subscription_update.subscription_id), organization=self.organization, ) data_source.detectors.add(detector) if detector.workflow_condition_group is None: detector.workflow_condition_group = self.create_data_condition_group(logic_type="any") detector.save() self.create_data_condition( condition_group=detector.workflow_condition_group, type=Condition.EQUAL, condition_result=DetectorPriorityLevel.HIGH, comparison=1, ) # Create a data_packet from the update for testing data_packet = DataPacket[ProcessedSubscriptionUpdate]( source_id=str(subscription_update.subscription_id), packet=subscription_update, ) return snuba_query, query_subscription, data_source, data_packet def create_workflow_action( self, workflow: Workflow, action: Action | None = None, **kwargs, ) -> tuple[DataConditionGroup, Action]: action_group = self.create_data_condition_group(logic_type="any-short") action = action or self.create_action(integration_id=self.integration.id) self.create_data_condition_group_action( condition_group=action_group, action=action, ) # Add the action group to the workflow self.create_workflow_data_condition_group(workflow, action_group) return action_group, action def create_group_event( self, project: Project | None = None, event: Event | None = None, occurrence: IssueOccurrence | None = None, environment: str | None = None, fingerprint="test_fingerprint", group_type_id: int | None = None, ) -> tuple[Group, Event, GroupEvent]: project = project or self.project event = event or self.create_event( project.id, datetime.now(), fingerprint, environment, ) if group_type_id: group = self.create_group(project=project, type=group_type_id) else: group = self.create_group(project=project) event.for_group(group) group_event = GroupEvent( self.project.id, event.event_id, group, event.data, event._snuba_data, occurrence, ) return group, event, group_event def create_sentry_app_with_schema(self) -> tuple[SentryApp, SentryAppInstallation]: sentry_app_settings_schema = self.create_alert_rule_action_schema() sentry_app = self.create_sentry_app( name="Moo Deng's Fire Sentry App", organization=self.organization, schema={ "elements": [ sentry_app_settings_schema, ] }, is_alertable=True, ) installation = self.create_sentry_app_installation( slug=sentry_app.slug, organization=self.organization ) return sentry_app, installation
BaseWorkflowTest
python
ansible__ansible
lib/ansible/plugins/cache/jsonfile.py
{ "start": 1340, "end": 1659 }
class ____(BaseFileCacheModule): """A caching module backed by json files.""" def _load(self, filepath: str) -> object: return json.loads(pathlib.Path(filepath).read_text()) def _dump(self, value: object, filepath: str) -> None: pathlib.Path(filepath).write_text(json.dumps(value))
CacheModule
python
xlwings__xlwings
xlwings/utils.py
{ "start": 8084, "end": 27849 }
class ____: def __init__(self, s): self.value = tuple(map(try_parse_int, s.split("."))) @property def major(self): return self.value[0] @property def minor(self): return self.value[1] if len(self.value) > 1 else None def __str__(self): return ".".join(map(str, self.value)) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(str(self))) def __eq__(self, other): if isinstance(other, VersionNumber): return self.value == other.value elif isinstance(other, str): return self.value == VersionNumber(other).value elif isinstance(other, tuple): return self.value[: len(other)] == other elif isinstance(other, int): return self.major == other else: return False def __lt__(self, other): if isinstance(other, VersionNumber): return self.value < other.value elif isinstance(other, str): return self.value < VersionNumber(other).value elif isinstance(other, tuple): return self.value[: len(other)] < other elif isinstance(other, int): return self.major < other else: raise TypeError("Cannot compare other object with version number") def process_image(image, format, export_options): """Returns filename and is_temp_file""" image = fspath(image) if isinstance(image, str): return image, False elif mpl and isinstance(image, mpl.figure.Figure): image_type = "mpl" elif plotly_go and isinstance(image, plotly_go.Figure): image_type = "plotly" else: raise TypeError("Don't know what to do with that image object") if export_options is None: export_options = {"bbox_inches": "tight", "dpi": 200} if format == "vector": if sys.platform.startswith("darwin"): format = "pdf" else: format = "svg" temp_dir = os.path.realpath(tempfile.gettempdir()) filename = os.path.join(temp_dir, str(uuid.uuid4()) + "." + format) if image_type == "mpl": canvas = mpl.backends.backend_agg.FigureCanvas(image) canvas.draw() image.savefig(filename, **export_options) plt.close(image) elif image_type == "plotly": image.write_image(filename) return filename, True def fspath(path): """Convert path-like object to string. On python <= 3.5 the input argument is always returned unchanged (no support for path-like objects available). TODO: can be removed as 3.5 no longer supported. """ if hasattr(os, "PathLike") and isinstance(path, os.PathLike): return os.fspath(path) else: return path def read_config_sheet(book): try: return book.sheets["xlwings.conf"]["A1:B1"].options(dict, expand="down").value except: # noqa: E722 # A missing sheet currently produces different errors on mac and win return {} def read_user_config(): """Returns keys in lowercase of xlwings.conf in the user's home directory""" config = {} if Path(xlwings.USER_CONFIG_FILE).is_file(): with open(xlwings.USER_CONFIG_FILE, "r") as f: for line in f: values = re.findall(r'"[^"]*"', line) if values: config[values[0].strip('"').lower()] = os.path.expandvars( values[1].strip('"') ) return config @lru_cache(None) def get_cached_user_config(key): return read_user_config().get(key.lower()) def exception(logger, msg, *args): if logger.hasHandlers(): logger.exception(msg, *args) else: print(msg % args) traceback.print_exc() def chunk(sequence, chunksize): for i in range(0, len(sequence), chunksize): yield sequence[i : i + chunksize] def query_yes_no(question, default="yes"): """Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". Licensed under the MIT License Copyright by Trent Mick https://code.activestate.com/recipes/577058/ """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == "": return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def prepare_sys_path(args_string): """Called from Excel to prepend the default paths and those from the PYTHONPATH setting to sys.path. While RunPython could use Book.caller(), the UDF server can't, as this runs before VBA can push the ActiveWorkbook over. UDFs also can't interact with the book object in general as Excel is busy during the function call and so won't allow you to read out the config sheet, for example. Before 0.24.9, these manipulations were handled in VBA, but couldn't handle SharePoint. """ args = os.path.normcase(os.path.expandvars(args_string)).split(";") paths = [] if args[0].lower() == "true": # Add dir of Excel file to PYTHONPATH # Not sure if we really need normcase, # but on Windows it replaces "/" with "\", so let's revert that active_fullname = args[1].replace("\\", "/") this_fullname = args[2].replace("\\", "/") for fullname in [active_fullname, this_fullname]: if not fullname: continue elif "://" in fullname: fullname = Path( fullname_url_to_local_path( url=fullname, sheet_onedrive_consumer_config=args[3], sheet_onedrive_commercial_config=args[4], sheet_sharepoint_config=args[5], ) ) else: fullname = Path(fullname) paths += [str(fullname.parent), str(fullname.with_suffix(".zip"))] if args[6:]: paths += args[6:] if paths: sys.path[0:0] = list(set(paths)) @lru_cache(None) def fullname_url_to_local_path( url, sheet_onedrive_consumer_config=None, sheet_onedrive_commercial_config=None, sheet_sharepoint_config=None, ): """ When AutoSave is enabled in Excel with either OneDrive or SharePoint, VBA/COM's Workbook.FullName turns into a URL without any possibilities to get the local file path. While OneDrive and OneDrive for Business make it easy enough to derive the local path from the URL, SharePoint allows to define the "Site name" and "Site address" independently from each other with the former ending up in the local folder path and the latter in the FullName URL. Adding to the complexity: (1) When the site name contains spaces, they will be stripped out from the URL and (2) you can sync a subfolder directly (this, at least, works when you have a single folder at the SharePoint's Document root), which results in skipping a folder level locally when compared to the online/URL version. And (3) the OneDriveCommercial env var sometimes seems to actually point to the local SharePoint folder. Parameters ---------- url : str URL as returned by VBA's FullName sheet_onedrive_consumer_config : str Optional Path to the local OneDrive (Personal) as defined in the Workbook's config sheet sheet_onedrive_commercial_config : str Optional Path to the local OneDrive for Business as defined in the Workbook's config sheet sheet_sharepoint_config : str Optional Path to the local SharePoint drive as defined in the Workbook's config sheet """ # Directory config files can't be used # since the whole purpose of this exercise is to find out about a book's dir onedrive_consumer_config_name = ( "ONEDRIVE_CONSUMER_WIN" if sys.platform.startswith("win") else "ONEDRIVE_CONSUMER_MAC" ) onedrive_commercial_config_name = ( "ONEDRIVE_COMMERCIAL_WIN" if sys.platform.startswith("win") else "ONEDRIVE_COMMERCIAL_MAC" ) sharepoint_config_name = ( "SHAREPOINT_WIN" if sys.platform.startswith("win") else "SHAREPOINT_MAC" ) if sheet_onedrive_consumer_config is not None: sheet_onedrive_consumer_config = os.path.expandvars( sheet_onedrive_consumer_config ) if sheet_onedrive_commercial_config is not None: sheet_onedrive_commercial_config = os.path.expandvars( sheet_onedrive_commercial_config ) if sheet_sharepoint_config is not None: sheet_sharepoint_config = os.path.expandvars(sheet_sharepoint_config) onedrive_consumer_config = sheet_onedrive_consumer_config or read_user_config().get( onedrive_consumer_config_name.lower() ) onedrive_commercial_config = ( sheet_onedrive_commercial_config or read_user_config().get(onedrive_commercial_config_name.lower()) ) sharepoint_config = sheet_sharepoint_config or read_user_config().get( sharepoint_config_name.lower() ) # OneDrive pattern = re.compile(r"https://d.docs.live.net/[^/]*/(.*)") match = pattern.match(url) if match: if sys.platform.startswith("darwin"): default_dir = Path.home() / "Library" / "CloudStorage" / "OneDrive-Personal" else: default_dir = Path.home() / "OneDrive" legacy_default_dir = Path.home() / "OneDrive" root = ( onedrive_consumer_config or os.getenv("OneDriveConsumer") or os.getenv("OneDrive") or (str(default_dir) if default_dir.is_dir() else None) or (str(legacy_default_dir) if legacy_default_dir else None) ) if not root: raise xlwings.XlwingsError( f"Couldn't find the local OneDrive folder. Please configure the " f"{onedrive_consumer_config_name} setting, see: xlwings.org/error." ) local_path = Path(root) / match.group(1) if local_path.is_file(): return str(local_path) else: raise xlwings.XlwingsError( "Couldn't find your local OneDrive file, see: xlwings.org/error" ) # OneDrive for Business pattern = re.compile(r"https://[^-]*-my.sharepoint.[^/]*/[^/]*/[^/]*/[^/]*/(.*)") match = pattern.match(url) if match: root = ( onedrive_commercial_config or os.getenv("OneDriveCommercial") or os.getenv("OneDrive") ) if not root: raise xlwings.XlwingsError( f"Couldn't find the local OneDrive for Business folder. " f"Please configure the {onedrive_commercial_config_name} setting, " f"see: xlwings.org/error." ) local_path = Path(root) / match.group(1) if local_path.is_file(): return str(local_path) else: raise xlwings.XlwingsError( "Couldn't find your local OneDrive for Business file, " "see: xlwings.org/error" ) # SharePoint Online & On-Premises pattern = re.compile(r"https?://[^/]*/sites/([^/]*)/([^/]*)/(.*)") match = pattern.match(url) if match: # xlwings config if sharepoint_config: root = sharepoint_config local_path = Path(root) / f"{match.group(1)} - Documents" / match.group(3) if local_path.is_file(): return str(local_path) # Env var if os.getenv("OneDriveCommercial"): # Default top level mapping root = os.getenv("OneDriveCommercial").replace("OneDrive - ", "") local_path = Path(root) / f"{match.group(1)} - Documents" / match.group(3) if local_path.is_file(): return str(local_path) # Windows registry url_to_mount = get_url_to_mount() mount_point = None for url_namespace, mount_point in url_to_mount.items(): if url.startswith(url_namespace): local_path = Path(mount_point) / url[len(url_namespace) :] if local_path.is_file(): return str(local_path) # Horrible fallback return search_local_sharepoint_path( url, root if not mount_point else mount_point, sharepoint_config, sharepoint_config_name, ) raise xlwings.XlwingsError( f"URL {url} not recognized as valid OneDrive/SharePoint link." ) def to_pdf( obj, path=None, include=None, exclude=None, layout=None, exclude_start_string=None, show=None, quality=None, ): report_path = fspath(path) layout_path = fspath(layout) if isinstance(obj, (xlwings.Book, xlwings.Sheet)): if report_path is None: filename, extension = os.path.splitext(obj.fullname) directory, _ = os.path.split(obj.fullname) if directory: report_path = os.path.join(directory, filename + ".pdf") else: report_path = filename + ".pdf" if (include is not None) and (exclude is not None): raise ValueError("You can only use either 'include' or 'exclude'") # Hide sheets to exclude them from printing if isinstance(include, (str, int)): include = [include] if isinstance(exclude, (str, int)): exclude = [exclude] exclude_by_name = [ sheet.index for sheet in obj.sheets if sheet.name.startswith(exclude_start_string) ] visibility = {} if include or exclude or exclude_by_name: for sheet in obj.sheets: visibility[sheet] = sheet.visible try: if include: for sheet in obj.sheets: if (sheet.name in include) or (sheet.index in include): sheet.visible = True else: sheet.visible = False if exclude or exclude_by_name: exclude = [] if exclude is None else exclude for sheet in obj.sheets: if ( (sheet.name in exclude) or (sheet.index in exclude) or (sheet.index in exclude_by_name) ): sheet.visible = False obj.impl.to_pdf(os.path.realpath(report_path), quality=quality) except Exception: raise finally: # Reset visibility if include or exclude or exclude_by_name: for sheet, tf in visibility.items(): sheet.visible = tf else: if report_path is None: if isinstance(obj, xlwings.Chart): directory, _ = os.path.split(obj.parent.book.fullname) filename = obj.name elif isinstance(obj, xlwings.Range): directory, _ = os.path.split(obj.sheet.book.fullname) filename = ( str(obj) .replace("<", "") .replace(">", "") .replace(":", "_") .replace(" ", "") ) else: raise ValueError(f"Object of type {type(obj)} are not supported.") if directory: report_path = os.path.join(directory, filename + ".pdf") else: report_path = filename + ".pdf" obj.impl.to_pdf(os.path.realpath(report_path), quality=quality) if layout: from .pro.reports.pdf import print_on_layout print_on_layout(report_path=report_path, layout_path=layout_path) if show: if sys.platform.startswith("win"): os.startfile(report_path) else: subprocess.run(["open", report_path]) return report_path def get_url_to_mount(): """Windows stores the sharepoint mount points in the registry. This helps but still isn't foolproof. """ if sys.platform.startswith("win"): import winreg from winreg import HKEY_CURRENT_USER, KEY_READ root = r"SOFTWARE\SyncEngines\Providers\OneDrive" url_to_mount = {} try: with winreg.OpenKey(HKEY_CURRENT_USER, root, 0, KEY_READ) as root_key: for i in range(0, winreg.QueryInfoKey(root_key)[0]): subfolder = winreg.EnumKey(root_key, i) with winreg.OpenKey( HKEY_CURRENT_USER, f"{root}\\{subfolder}", 0, KEY_READ ) as key: try: mount_point, _ = winreg.QueryValueEx(key, "MountPoint") url_namespace, _ = winreg.QueryValueEx(key, "URLNamespace") url_to_mount[url_namespace] = mount_point except FileNotFoundError: pass except FileNotFoundError: pass return url_to_mount else: return {} def search_local_sharepoint_path(url, root, sharepoint_config, sharepoint_config_name): book_name = url.split("/")[-1] local_book_paths = [] for path in Path(root).rglob("[!~$]*.xls*"): if path.name.lower() == book_name.lower(): local_book_paths.append(path) if len(local_book_paths) == 1: return str(local_book_paths[0]) elif len(local_book_paths) == 0: raise xlwings.XlwingsError( "Couldn't find your SharePoint file locally, see: xlwings.org/error" ) else: raise xlwings.XlwingsError( f"Your SharePoint configuration either requires your workbook name to be " f"unique across all synced SharePoint folders or you need to " f"{'edit' if sharepoint_config else 'add'} the {sharepoint_config_name} " f"setting including one or more folder levels, see: xlwings.org/error." ) def excel_update_picture(picture_impl, filename): name = picture_impl.name left, top = picture_impl.left, picture_impl.top width, height = picture_impl.width, picture_impl.height picture_impl.delete() picture_impl = picture_impl.parent.pictures.add( filename, link_to_file=False, save_with_document=True, left=left, top=top, width=width, height=height, anchor=None, ) picture_impl.name = name return picture_impl def determine_columns_or_rows(address): """ If the address is a row '1:3' or a column 'A:C', it returns "rows" or "columns", respectively. """ start, end = address.replace("$", "").split(":") if start.isdigit() and end.isdigit(): return "rows" elif start.isalpha() and end.isalpha(): return "columns"
VersionNumber
python
scipy__scipy
benchmarks/benchmarks/interpolate.py
{ "start": 6784, "end": 7905 }
class ____(Benchmark): """ Author: josef-pktd and scipy mailinglist example 'http://scipy-user.10969.n7.nabble.com/BivariateSpline-examples\ -and-my-crashing-python-td14801.html' """ param_names = ['n_samples'] params = [ [10, 20, 30] ] def setup(self, n_samples): x = np.arange(0, n_samples, 0.5) y = np.arange(0, n_samples, 0.5) x, y = np.meshgrid(x, y) x = x.ravel() y = y.ravel() xmin = x.min()-1 xmax = x.max()+1 ymin = y.min()-1 ymax = y.max()+1 s = 1.1 self.yknots = np.linspace(ymin+s, ymax-s, 10) self.xknots = np.linspace(xmin+s, xmax-s, 10) self.z = np.sin(x) + 0.1*np.random.normal(size=x.shape) self.x = x self.y = y def time_smooth_bivariate_spline(self, n_samples): interpolate.SmoothBivariateSpline(self.x, self.y, self.z) def time_lsq_bivariate_spline(self, n_samples): interpolate.LSQBivariateSpline(self.x, self.y, self.z, self.xknots.flat, self.yknots.flat)
BivariateSpline
python
numpy__numpy
tools/swig/test/testMatrix.py
{ "start": 11250, "end": 11513 }
class ____(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" ######################################################################
uintTestCase
python
fluentpython__example-code
17-futures/countries/flags2_asyncio.py
{ "start": 737, "end": 3460 }
class ____(Exception): # <1> def __init__(self, country_code): self.country_code = country_code @asyncio.coroutine def get_flag(base_url, cc): # <2> url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower()) resp = yield from aiohttp.request('GET', url) with contextlib.closing(resp): if resp.status == 200: image = yield from resp.read() return image elif resp.status == 404: raise web.HTTPNotFound() else: raise aiohttp.HttpProcessingError( code=resp.status, message=resp.reason, headers=resp.headers) @asyncio.coroutine def download_one(cc, base_url, semaphore, verbose): # <3> try: with (yield from semaphore): # <4> image = yield from get_flag(base_url, cc) # <5> except web.HTTPNotFound: # <6> status = HTTPStatus.not_found msg = 'not found' except Exception as exc: raise FetchError(cc) from exc # <7> else: save_flag(image, cc.lower() + '.gif') # <8> status = HTTPStatus.ok msg = 'OK' if verbose and msg: print(cc, msg) return Result(status, cc) # END FLAGS2_ASYNCIO_TOP # BEGIN FLAGS2_ASYNCIO_DOWNLOAD_MANY @asyncio.coroutine def downloader_coro(cc_list, base_url, verbose, concur_req): # <1> counter = collections.Counter() semaphore = asyncio.Semaphore(concur_req) # <2> to_do = [download_one(cc, base_url, semaphore, verbose) for cc in sorted(cc_list)] # <3> to_do_iter = asyncio.as_completed(to_do) # <4> if not verbose: to_do_iter = tqdm.tqdm(to_do_iter, total=len(cc_list)) # <5> for future in to_do_iter: # <6> try: res = yield from future # <7> except FetchError as exc: # <8> country_code = exc.country_code # <9> try: error_msg = exc.__cause__.args[0] # <10> except IndexError: error_msg = exc.__cause__.__class__.__name__ # <11> if verbose and error_msg: msg = '*** Error for {}: {}' print(msg.format(country_code, error_msg)) status = HTTPStatus.error else: status = res.status counter[status] += 1 # <12> return counter # <13> def download_many(cc_list, base_url, verbose, concur_req): loop = asyncio.get_event_loop() coro = downloader_coro(cc_list, base_url, verbose, concur_req) counts = loop.run_until_complete(coro) # <14> loop.close() # <15> return counts if __name__ == '__main__': main(download_many, DEFAULT_CONCUR_REQ, MAX_CONCUR_REQ) # END FLAGS2_ASYNCIO_DOWNLOAD_MANY
FetchError
python
django__django
django/db/models/aggregates.py
{ "start": 8543, "end": 9699 }
class ____(Aggregate): function = "COUNT" name = "Count" output_field = IntegerField() allow_distinct = True empty_result_set_value = 0 arity = 1 allows_composite_expressions = True def __init__(self, expression, filter=None, **extra): if expression == "*": expression = Star() if isinstance(expression, Star) and filter is not None: raise ValueError("Star cannot be used with filter. Please specify a field.") super().__init__(expression, filter=filter, **extra) def resolve_expression(self, *args, **kwargs): result = super().resolve_expression(*args, **kwargs) source_expressions = result.get_source_expressions() # In case of composite primary keys, count the first column. if isinstance(expr := source_expressions[0], ColPairs): if self.distinct: raise ValueError( "COUNT(DISTINCT) doesn't support composite primary keys" ) source_expressions[0] = expr.get_cols()[0] result.set_source_expressions(source_expressions) return result
Count
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 293303, "end": 294440 }
class ____: def setup_method(self): self.rng = np.random.default_rng(2792245532) def test_erlang_runtimewarning(self): # erlang should generate a RuntimeWarning if a non-integer # shape parameter is used. with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) # The non-integer shape parameter 1.3 should trigger a # RuntimeWarning assert_raises(RuntimeWarning, stats.erlang.rvs, 1.3, loc=0, scale=1, size=4, random_state=self.rng) # Calling the fit method with `f0` set to an integer should # *not* trigger a RuntimeWarning. It should return the same # values as gamma.fit(...). data = [0.5, 1.0, 2.0, 4.0] result_erlang = stats.erlang.fit(data, f0=1) result_gamma = stats.gamma.fit(data, f0=1) assert_allclose(result_erlang, result_gamma, rtol=1e-3) def test_gh_pr_10949_argcheck(self): assert_equal(stats.erlang.pdf(0.5, a=[1, -1]), stats.gamma.pdf(0.5, a=[1, -1]))
TestErlang
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py
{ "start": 880, "end": 1777 }
class ____: ... T3 = TypeVar("T3", A, B, Union[C, D]) def do_something(value: T3) -> T3: ... def func10(value: Union[C, D]): value1 = do_something(value) def func11(value: D): value1 = do_something(value) def func12(value: Union[A, B]): # This should generate an error because A and B # map to different constraints. value1 = do_something(value) def func13(value: Union[A, D]): # This should generate an error because A and D # map to different constraints. value1 = do_something(value) T4 = TypeVar("T4", A, B, Union[C, D]) def func14(cls: Type[T4]) -> T4: instance1 = cls() reveal_type(instance1, expected_text="T4@func14") # Unknown return instance1 def func15(cls: Union[Type[Union[A, B]], Type[Union[C, D]]]) -> Union[A, B, C, D]: instance2 = cls() reveal_type(instance2, expected_text="A | B | C | D") return instance2
D
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 30905, "end": 31518 }
class ____(VOTableSpecWarning): """ An XML namespace was specified on the ``VOTABLE`` element, but the namespace does not match what is expected for a ``VOTABLE`` file. The ``VOTABLE`` namespace is:: http://www.ivoa.net/xml/VOTable/vX.X where "X.X" is the version number. Some files in the wild set the namespace to the location of the VOTable schema, which is not correct and will not pass some validating parsers. """ message_template = ( "An XML namespace is specified, but is incorrect. Expected '{}', got '{}'" ) default_args = ("x", "y")
W41
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 3927, "end": 4486 }
class ____(Event): name: str = "create_run" @classmethod def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None: # Capture the set of currently imported packages at run creation time to # understand how MLflow is used together with other libraries. Collecting # this data at run creation ensures accuracy and completeness. return { "imports": [pkg for pkg in MODULES_TO_CHECK_IMPORT if pkg in sys.modules], "experiment_id": arguments.get("experiment_id"), }
CreateRunEvent
python
viewflow__viewflow
tests/workflow/test_managers_perms.py
{ "start": 452, "end": 1024 }
class ____(flow.Flow): """ Flow available for staff users only.""" start = flow.StartHandle(this.start_flow).Next(this.task) task = ( flow.View(this.task_view) .Assign(this.get_task_user) .Next(this.end) ) end = flow.End() def start_flow(self, activation, user=None): activation.process.data = {'user_pk': user.pk} def get_task_user(self, activation): User.object.get(pk=activation.process.data['user_pk']) def has_view_permission(self, user, obj=None): return user.is_staff
StaffOnlyFlow
python
ray-project__ray
rllib/algorithms/algorithm.py
{ "start": 205969, "end": 211499 }
class ____: def __init__(self, algo: Algorithm): self.algo = algo self.time_start = None self.time_stop = None def __enter__(self): # Before first call to `step()`, `results` is expected to be None -> # Start with self.failures=-1 -> set to 0 before the very first call # to `self.step()`. self.failures = -1 self.time_start = time.time() self.sampled = 0 self.trained = 0 if self.algo.config.enable_env_runner_and_connector_v2: self.init_env_steps_sampled = self.algo.metrics.peek( (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 ) self.init_env_steps_trained = self.algo.metrics.peek( (LEARNER_RESULTS, ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), default=0, ) self.init_agent_steps_sampled = sum( self.algo.metrics.peek( (ENV_RUNNER_RESULTS, NUM_AGENT_STEPS_SAMPLED_LIFETIME), default={} ).values() ) self.init_agent_steps_trained = sum( self.algo.metrics.peek( (LEARNER_RESULTS, NUM_AGENT_STEPS_TRAINED_LIFETIME), default={} ).values() ) else: self.init_env_steps_sampled = self.algo._counters[NUM_ENV_STEPS_SAMPLED] self.init_env_steps_trained = self.algo._counters[NUM_ENV_STEPS_TRAINED] self.init_agent_steps_sampled = self.algo._counters[NUM_AGENT_STEPS_SAMPLED] self.init_agent_steps_trained = self.algo._counters[NUM_AGENT_STEPS_TRAINED] self.failure_tolerance = ( self.algo.config.num_consecutive_env_runner_failures_tolerance ) return self def __exit__(self, *args): self.time_stop = time.time() def get_time_taken_sec(self) -> float: """Returns the time we spent in the context in seconds.""" return self.time_stop - self.time_start def should_stop(self, results): # Before first call to `step()`. if results in [None, False]: # Fail after n retries. self.failures += 1 if self.failures > self.failure_tolerance: raise RuntimeError( "More than `num_consecutive_env_runner_failures_tolerance=" f"{self.failure_tolerance}` consecutive worker failures! " "Exiting." ) # Continue to very first `step()` call or retry `step()` after # a (tolerable) failure. return False # Stopping criteria. if self.algo.config.enable_env_runner_and_connector_v2: if self.algo.config.count_steps_by == "agent_steps": self.sampled = ( sum( self.algo.metrics.peek( (ENV_RUNNER_RESULTS, NUM_AGENT_STEPS_SAMPLED_LIFETIME), default={}, ).values() ) - self.init_agent_steps_sampled ) self.trained = ( sum( self.algo.metrics.peek( (LEARNER_RESULTS, NUM_AGENT_STEPS_TRAINED_LIFETIME), default={}, ).values() ) - self.init_agent_steps_trained ) else: self.sampled = ( self.algo.metrics.peek( (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 ) - self.init_env_steps_sampled ) self.trained = ( self.algo.metrics.peek( (LEARNER_RESULTS, ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), default=0, ) - self.init_env_steps_trained ) else: if self.algo.config.count_steps_by == "agent_steps": self.sampled = ( self.algo._counters[NUM_AGENT_STEPS_SAMPLED] - self.init_agent_steps_sampled ) self.trained = ( self.algo._counters[NUM_AGENT_STEPS_TRAINED] - self.init_agent_steps_trained ) else: self.sampled = ( self.algo._counters[NUM_ENV_STEPS_SAMPLED] - self.init_env_steps_sampled ) self.trained = ( self.algo._counters[NUM_ENV_STEPS_TRAINED] - self.init_env_steps_trained ) min_t = self.algo.config.min_time_s_per_iteration min_sample_ts = self.algo.config.min_sample_timesteps_per_iteration min_train_ts = self.algo.config.min_train_timesteps_per_iteration # Repeat if not enough time has passed or if not enough # env|train timesteps have been processed (or these min # values are not provided by the user). if ( (not min_t or time.time() - self.time_start >= min_t) and (not min_sample_ts or self.sampled >= min_sample_ts) and (not min_train_ts or self.trained >= min_train_ts) ): return True else: return False
TrainIterCtx
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 4339, "end": 4508 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneRunEvent) name = "AlertSuccessEvent"
GrapheneAlertSuccessEvent
python
walkccc__LeetCode
solutions/2107. Number of Unique Flavors After Sharing K Candies/2107.py
{ "start": 0, "end": 473 }
class ____: def shareCandies(self, candies: list[int], k: int) -> int: ans = 0 count = collections.Counter(candies) unique = len(count) for i, candy in enumerate(candies): count[candy] -= 1 if count[candy] == 0: del count[candy] unique -= 1 if i >= k: count[candies[i - k]] += 1 if count[candies[i - k]] == 1: unique += 1 if i >= k - 1: ans = max(ans, unique) return ans
Solution
python
conda__conda
conda/core/link.py
{ "start": 5928, "end": 7654 }
class ____: """A container for groups of actions carried out during an UnlinkLinkTransaction. :param remove_menu_action_groups: Actions which remove menu items :param unlink_action_groups: Actions which unlink files :param unregister_action_groups: Actions which unregister environment locations :param link_action_groups: Actions which link files :param register_action_groups: Actions which register environment locations :param compile_action_groups: Actions which compile pyc files :param make_menu_action_groups: Actions which create menu items :param entry_point_action_groups: Actions which create python entry points :param prefix_record_groups: Actions which create package json files in ``conda-meta/`` :param initial_action_groups: User-defined actions which run before all other actions :param final_action_groups: User-defined actions which run after all other actions """ remove_menu_action_groups: Iterable[ActionGroup] unlink_action_groups: Iterable[ActionGroup] unregister_action_groups: Iterable[ActionGroup] link_action_groups: Iterable[ActionGroup] register_action_groups: Iterable[ActionGroup] compile_action_groups: Iterable[ActionGroup] make_menu_action_groups: Iterable[ActionGroup] entry_point_action_groups: Iterable[ActionGroup] prefix_record_groups: Iterable[ActionGroup] initial_action_groups: Iterable[ActionGroup] = () final_action_groups: Iterable[ActionGroup] = () def __iter__(self) -> Generator[Iterable[ActionGroup], None, None]: for field in fields(self): yield getattr(self, field.name) @deprecated("25.9", "26.3", addendum="Use PrefixActions instead.")
PrefixActions
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_indexing.py
{ "start": 64924, "end": 67118 }
class ____: # This is adapted from pandas/tests/arrays/masked/test_indexing.py def _check_setitem_invalid(self, df, invalid, indexer): orig_df = df.copy() # iloc with pytest.raises(TypeError, match="Invalid value"): df.iloc[indexer, 0] = invalid df = orig_df.copy() # loc with pytest.raises(TypeError, match="Invalid value"): df.loc[indexer, "a"] = invalid df = orig_df.copy() def _check_setitem_valid(self, df, value, indexer): orig_df = df.copy() # iloc df.iloc[indexer, 0] = value df = orig_df.copy() # loc df.loc[indexer, "a"] = value df = orig_df.copy() _invalid_scalars = [ 1 + 2j, "True", "1", "1.0", pd.NaT, np.datetime64("NaT"), np.timedelta64("NaT"), ] _indexers = [0, [0], slice(0, 1), [True, False, False], slice(None, None, None)] @pytest.mark.parametrize( "invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)] ) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_bool(self, invalid, indexer): df = DataFrame({"a": [True, False, False]}, dtype="bool") self._check_setitem_invalid(df, invalid, indexer) @pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)]) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_int(self, invalid, any_int_numpy_dtype, indexer): df = DataFrame({"a": [1, 2, 3]}, dtype=any_int_numpy_dtype) if isna(invalid) and invalid is not pd.NaT and not np.isnat(invalid): self._check_setitem_valid(df, invalid, indexer) else: self._check_setitem_invalid(df, invalid, indexer) @pytest.mark.parametrize("invalid", _invalid_scalars + [True]) @pytest.mark.parametrize("indexer", _indexers) def test_setitem_validation_scalar_float(self, invalid, float_numpy_dtype, indexer): df = DataFrame({"a": [1, 2, None]}, dtype=float_numpy_dtype) self._check_setitem_invalid(df, invalid, indexer)
TestSetitemValidation
python
pytorch__pytorch
test/jit/_imported_class_test/foo.py
{ "start": 179, "end": 285 }
class ____: def __init__(self, x): self.x = x self.nested = bar.FooSameName(x)
FooSameName
python
Pylons__pyramid
tests/test_config/test_tweens.py
{ "start": 6474, "end": 16673 }
class ____(unittest.TestCase): def _makeOne(self): from pyramid.config.tweens import Tweens return Tweens() def test_add_explicit(self): tweens = self._makeOne() tweens.add_explicit('name', 'factory') self.assertEqual(tweens.explicit, [('name', 'factory')]) tweens.add_explicit('name2', 'factory2') self.assertEqual( tweens.explicit, [('name', 'factory'), ('name2', 'factory2')] ) def test_add_implicit(self): tweens = self._makeOne() tweens.add_implicit('name', 'factory') tweens.add_implicit('name2', 'factory2') self.assertEqual( tweens.sorter.sorted(), [('name2', 'factory2'), ('name', 'factory')], ) def test___call___explicit(self): tweens = self._makeOne() def factory1(handler, registry): return handler def factory2(handler, registry): return '123' tweens.explicit = [('name', factory1), ('name', factory2)] self.assertEqual(tweens(None, None), '123') def test___call___implicit(self): tweens = self._makeOne() def factory1(handler, registry): return handler def factory2(handler, registry): return '123' tweens.add_implicit('name2', factory2) tweens.add_implicit('name1', factory1) self.assertEqual(tweens(None, None), '123') def test_implicit_ordering_1(self): tweens = self._makeOne() tweens.add_implicit('name1', 'factory1') tweens.add_implicit('name2', 'factory2') self.assertEqual( tweens.implicit(), [('name2', 'factory2'), ('name1', 'factory1')] ) def test_implicit_ordering_2(self): from pyramid.tweens import MAIN tweens = self._makeOne() tweens.add_implicit('name1', 'factory1') tweens.add_implicit('name2', 'factory2', over=MAIN) self.assertEqual( tweens.implicit(), [('name1', 'factory1'), ('name2', 'factory2')] ) def test_implicit_ordering_3(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('auth', 'auth_factory', under='browserid') add('dbt', 'dbt_factory') add('retry', 'retry_factory', over='txnmgr', under='exceptionview') add('browserid', 'browserid_factory') add('txnmgr', 'txnmgr_factory', under='exceptionview') add('exceptionview', 'excview_factory', over=MAIN) self.assertEqual( tweens.implicit(), [ ('browserid', 'browserid_factory'), ('auth', 'auth_factory'), ('dbt', 'dbt_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ('txnmgr', 'txnmgr_factory'), ], ) def test_implicit_ordering_4(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('auth', 'auth_factory', under='browserid') add('retry', 'retry_factory', over='txnmgr', under='exceptionview') add('browserid', 'browserid_factory') add('txnmgr', 'txnmgr_factory', under='exceptionview') add('dbt', 'dbt_factory') self.assertEqual( tweens.implicit(), [ ('dbt', 'dbt_factory'), ('browserid', 'browserid_factory'), ('auth', 'auth_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ('txnmgr', 'txnmgr_factory'), ], ) def test_implicit_ordering_5(self): from pyramid.tweens import INGRESS, MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('auth', 'auth_factory', under=INGRESS) add('retry', 'retry_factory', over='txnmgr', under='exceptionview') add('browserid', 'browserid_factory', under=INGRESS) add('txnmgr', 'txnmgr_factory', under='exceptionview', over=MAIN) add('dbt', 'dbt_factory') self.assertEqual( tweens.implicit(), [ ('dbt', 'dbt_factory'), ('browserid', 'browserid_factory'), ('auth', 'auth_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ('txnmgr', 'txnmgr_factory'), ], ) def test_implicit_ordering_missing_over_partial(self): from pyramid.exceptions import ConfigurationError tweens = self._makeOne() add = tweens.add_implicit add('dbt', 'dbt_factory') add('auth', 'auth_factory', under='browserid') add('retry', 'retry_factory', over='txnmgr', under='exceptionview') add('browserid', 'browserid_factory') self.assertRaises(ConfigurationError, tweens.implicit) def test_implicit_ordering_missing_under_partial(self): from pyramid.exceptions import ConfigurationError tweens = self._makeOne() add = tweens.add_implicit add('dbt', 'dbt_factory') add('auth', 'auth_factory', under='txnmgr') add('retry', 'retry_factory', over='dbt', under='exceptionview') add('browserid', 'browserid_factory') self.assertRaises(ConfigurationError, tweens.implicit) def test_implicit_ordering_missing_over_and_under_partials(self): from pyramid.exceptions import ConfigurationError tweens = self._makeOne() add = tweens.add_implicit add('dbt', 'dbt_factory') add('auth', 'auth_factory', under='browserid') add('retry', 'retry_factory', over='foo', under='txnmgr') add('browserid', 'browserid_factory') self.assertRaises(ConfigurationError, tweens.implicit) def test_implicit_ordering_missing_over_partial_with_fallback(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('auth', 'auth_factory', under='browserid') add( 'retry', 'retry_factory', over=('txnmgr', MAIN), under='exceptionview', ) add('browserid', 'browserid_factory') add('dbt', 'dbt_factory') self.assertEqual( tweens.implicit(), [ ('dbt', 'dbt_factory'), ('browserid', 'browserid_factory'), ('auth', 'auth_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ], ) def test_implicit_ordering_missing_under_partial_with_fallback(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('auth', 'auth_factory', under=('txnmgr', 'browserid')) add('retry', 'retry_factory', under='exceptionview') add('browserid', 'browserid_factory') add('dbt', 'dbt_factory') self.assertEqual( tweens.implicit(), [ ('dbt', 'dbt_factory'), ('browserid', 'browserid_factory'), ('auth', 'auth_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ], ) def test_implicit_ordering_with_partial_fallbacks(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=('wontbethere', MAIN)) add('retry', 'retry_factory', under='exceptionview') add('browserid', 'browserid_factory', over=('wont2', 'exceptionview')) self.assertEqual( tweens.implicit(), [ ('browserid', 'browserid_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ], ) def test_implicit_ordering_with_multiple_matching_fallbacks(self): from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('retry', 'retry_factory', under='exceptionview') add('browserid', 'browserid_factory', over=('retry', 'exceptionview')) self.assertEqual( tweens.implicit(), [ ('browserid', 'browserid_factory'), ('exceptionview', 'excview_factory'), ('retry', 'retry_factory'), ], ) def test_implicit_ordering_with_missing_fallbacks(self): from pyramid.exceptions import ConfigurationError from pyramid.tweens import MAIN tweens = self._makeOne() add = tweens.add_implicit add('exceptionview', 'excview_factory', over=MAIN) add('retry', 'retry_factory', under='exceptionview') add('browserid', 'browserid_factory', over=('txnmgr', 'auth')) self.assertRaises(ConfigurationError, tweens.implicit) def test_implicit_ordering_conflict_direct(self): from pyramid.exceptions import CyclicDependencyError tweens = self._makeOne() add = tweens.add_implicit add('browserid', 'browserid_factory') add('auth', 'auth_factory', over='browserid', under='browserid') self.assertRaises(CyclicDependencyError, tweens.implicit) def test_implicit_ordering_conflict_indirect(self): from pyramid.exceptions import CyclicDependencyError tweens = self._makeOne() add = tweens.add_implicit add('browserid', 'browserid_factory') add('auth', 'auth_factory', over='browserid') add('dbt', 'dbt_factory', under='browserid', over='auth') self.assertRaises(CyclicDependencyError, tweens.implicit)
TestTweens
python
pytorch__pytorch
torch/optim/lr_scheduler.py
{ "start": 12163, "end": 12469 }
class ____: def __init__(self, o: LRScheduler) -> None: self.o = o def __enter__(self) -> Self: self.o._get_lr_called_within_step = True return self def __exit__(self, type, value, traceback) -> None: self.o._get_lr_called_within_step = False
_enable_get_lr_call
python
dagster-io__dagster
python_modules/libraries/dagster-tableau/dagster_tableau/resources.py
{ "start": 37485, "end": 38671 }
class ____(StateBackedDefinitionsLoader[TableauWorkspaceData]): workspace: BaseTableauWorkspace translator: DagsterTableauTranslator workbook_selector_fn: Optional[WorkbookSelectorFn] = None @property def defs_key(self) -> str: return f"{TABLEAU_RECONSTRUCTION_METADATA_KEY_PREFIX}/{self.workspace.site_name}" def fetch_state(self) -> TableauWorkspaceData: return self.workspace.fetch_tableau_workspace_data() def defs_from_state(self, state: TableauWorkspaceData) -> Definitions: selected_state = state.to_workspace_data_selection( workbook_selector_fn=self.workbook_selector_fn ) all_external_data = [ *selected_state.data_sources_by_id.values(), *selected_state.sheets_by_id.values(), *selected_state.dashboards_by_id.values(), ] all_external_asset_specs = [ self.translator.get_asset_spec( TableauTranslatorData(content_data=content, workspace_data=selected_state) ) for content in all_external_data ] return Definitions(assets=all_external_asset_specs)
TableauWorkspaceDefsLoader
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/hide_value.py
{ "start": 103, "end": 260 }
class ____: """docstring""" #: docstring #: #: :meta hide-value: SENTINEL1 = object() #: :meta hide-value: SENTINEL2 = object()
Foo
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_view_test.py
{ "start": 962, "end": 5805 }
class ____(test.TestCase): def test_children(self): root = autotrackable.AutoTrackable() root.leaf = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) current_name, node_id = next( iter( checkpoint_view.CheckpointView(root_save_path).children(0).items())) self.assertEqual("leaf", current_name) self.assertEqual(1, node_id) def test_all_nodes(self): root = autotrackable.AutoTrackable() root.leaf = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) all_nodes = checkpoint_view.CheckpointView(root_save_path).descendants() self.assertEqual(3, len(all_nodes)) self.assertEqual(0, all_nodes[0]) self.assertEqual(1, all_nodes[1]) def test_all_nodes_with_paths(self): root = autotrackable.AutoTrackable() leaf1 = root.leaf1 = autotrackable.AutoTrackable() leaf2 = root.leaf2 = autotrackable.AutoTrackable() leaf1.leaf3 = autotrackable.AutoTrackable() leaf1.leaf4 = autotrackable.AutoTrackable() leaf2.leaf5 = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) all_nodes_with_paths = checkpoint_view.CheckpointView( root_save_path)._descendants_with_paths() self.assertEqual( { "root", "root.leaf1", "root.leaf2", "root.save_counter", "root.leaf1.leaf3", "root.leaf1.leaf4", "root.leaf2.leaf5" }, set(all_nodes_with_paths.values())) def test_match(self): root1 = autotrackable.AutoTrackable() leaf1 = root1.leaf1 = autotrackable.AutoTrackable() leaf2 = root1.leaf2 = autotrackable.AutoTrackable() leaf1.leaf3 = autotrackable.AutoTrackable() leaf1.leaf4 = autotrackable.AutoTrackable() leaf2.leaf5 = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root1) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) root2 = autotrackable.AutoTrackable() leaf11 = root2.leaf1 = autotrackable.AutoTrackable() leaf12 = root2.leaf2 = autotrackable.AutoTrackable() leaf13 = leaf11.leaf3 = autotrackable.AutoTrackable() leaf15 = leaf12.leaf5 = autotrackable.AutoTrackable() matching_nodes = checkpoint_view.CheckpointView(root_save_path).match(root2) self.assertDictEqual(matching_nodes, { 0: root2, 1: leaf11, 2: leaf12, 4: leaf13, 6: leaf15 }) def test_match_overlapping_nodes(self): root1 = autotrackable.AutoTrackable() root1.a = root1.b = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root1) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) root2 = autotrackable.AutoTrackable() a1 = root2.a = autotrackable.AutoTrackable() root2.b = autotrackable.AutoTrackable() with self.assertLogs(level="WARNING") as logs: matching_nodes = checkpoint_view.CheckpointView(root_save_path).match( root2) self.assertDictEqual( matching_nodes, { 0: root2, 1: a1, # Only the first element at the same position will be matched. }) expected_message = ( "Inconsistent references when matching the checkpoint into this object" " graph.") self.assertIn(expected_message, logs.output[0]) def test_diff(self): root1 = autotrackable.AutoTrackable() leaf1 = root1.leaf1 = autotrackable.AutoTrackable() leaf2 = root1.leaf2 = autotrackable.AutoTrackable() leaf1.leaf3 = autotrackable.AutoTrackable() leaf1.leaf4 = autotrackable.AutoTrackable() leaf2.leaf5 = autotrackable.AutoTrackable() root_ckpt = trackable_utils.Checkpoint(root=root1) root_save_path = root_ckpt.save( os.path.join(self.get_temp_dir(), "root_ckpt")) root2 = autotrackable.AutoTrackable() leaf11 = root2.leaf1 = autotrackable.AutoTrackable() leaf12 = root2.leaf2 = autotrackable.AutoTrackable() leaf13 = leaf11.leaf3 = autotrackable.AutoTrackable() leaf15 = leaf12.leaf5 = autotrackable.AutoTrackable() leaf16 = leaf12.leaf6 = autotrackable.AutoTrackable() diff = checkpoint_view.CheckpointView(root_save_path).diff(root2) self.assertEqual(len(diff), 3) self.assertDictEqual(diff[0], { 0: root2, 1: leaf11, 2: leaf12, 4: leaf13, 6: leaf15 }) self.assertListEqual(diff[1], [3, 5]) self.assertListEqual(diff[2], [leaf16]) if __name__ == "__main__": test.main()
CheckpointViewTest