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
modin-project__modin
modin/tests/test_utils.py
{ "start": 1623, "end": 13416 }
class ____(BaseParent): """this is class docstring""" def method(self): """ordinary method (child)""" def own_method(self): """own method""" def no_overwrite(self): """another own method""" F = property(method) @pytest.fixture(scope="module") def wrapped_cls(): @modin.utils._inherit_docstrings(BaseChild) class Wrapped: def method(self): pass def base_method(self): pass def own_method(self): pass def no_overwrite(self): """not overwritten doc""" @property def prop(self): return None @staticmethod def static(): pass @classmethod def clsmtd(cls): pass F = property(method) return Wrapped def _check_doc(wrapped, orig): assert wrapped.__doc__ == orig.__doc__ if isinstance(wrapped, property): assert wrapped.fget.__doc_inherited__ else: assert wrapped.__doc_inherited__ def test_doc_inherit_clslevel(wrapped_cls): _check_doc(wrapped_cls, BaseChild) def test_doc_inherit_methods(wrapped_cls): _check_doc(wrapped_cls.method, BaseChild.method) _check_doc(wrapped_cls.base_method, BaseParent.base_method) _check_doc(wrapped_cls.own_method, BaseChild.own_method) assert wrapped_cls.no_overwrite.__doc__ != BaseChild.no_overwrite.__doc__ assert not getattr(wrapped_cls.no_overwrite, "__doc_inherited__", False) def test_doc_inherit_special(wrapped_cls): _check_doc(wrapped_cls.static, BaseChild.static) _check_doc(wrapped_cls.clsmtd, BaseChild.clsmtd) def test_doc_inherit_props(wrapped_cls): assert type(wrapped_cls.method) == type(BaseChild.method) # noqa: E721 _check_doc(wrapped_cls.prop, BaseChild.prop) _check_doc(wrapped_cls.F, BaseChild.F) def test_doc_inherit_prop_builder(): def builder(name): return property(lambda self: name) class Parent: prop = builder("Parent") @modin.utils._inherit_docstrings(Parent) class Child(Parent): prop = builder("Child") assert Parent().prop == "Parent" assert Child().prop == "Child" @pytest.mark.parametrize( "source_doc,to_append,expected", [ ( "One-line doc.", "One-line message.", "One-line doc.One-line message.", ), ( """ Regular doc-string With the setted indent style. """, """ Doc-string having different indents in comparison with the regular one. """, """ Regular doc-string With the setted indent style. Doc-string having different indents in comparison with the regular one. """, ), ], ) def test_append_to_docstring(source_doc, to_append, expected): def source_fn(): pass source_fn.__doc__ = source_doc result_fn = modin.utils.append_to_docstring(to_append)(source_fn) answer = dedent(result_fn.__doc__) expected = dedent(expected) assert answer == expected def test_align_indents(): source = """ Source string that sets the indent pattern.""" target = indent(source, " " * 5) result = modin.utils.align_indents(source, target) assert source == result def test_format_string(): template = """ Source template string that has some {inline_placeholder}s. Placeholder1: {new_line_placeholder1} Placeholder2: {new_line_placeholder2} Placeholder3: {new_line_placeholder3} Placeholder4: {new_line_placeholder4}Text text: Placeholder5: {new_line_placeholder5} """ singleline_value = "Single-line value" multiline_value = """ Some string Having different indentation From the source one.""" multiline_value_new_line_at_the_end = multiline_value + "\n" multiline_value_new_line_at_the_begin = "\n" + multiline_value expected = """ Source template string that has some Single-line values. Placeholder1: Some string Having different indentation From the source one. Placeholder2: Single-line value Placeholder3: Some string Having different indentation From the source one. Placeholder4: Some string Having different indentation From the source one. Text text: Placeholder5: Some string Having different indentation From the source one. """ # noqa: W293 answer = modin.utils.format_string( template, inline_placeholder=singleline_value, new_line_placeholder1=multiline_value, new_line_placeholder2=singleline_value, new_line_placeholder3=multiline_value_new_line_at_the_begin, new_line_placeholder4=multiline_value_new_line_at_the_end, new_line_placeholder5=multiline_value, ) assert answer == expected def warns_that_defaulting_to_pandas_if( condition: bool, prefix: Optional[str] = None, suffix: Optional[str] = None ): """ Get a context manager that checks for a default to pandas warning if `condition` is True. Parameters ---------- condition : bool Whether to check for the default to pandas warning. prefix : Optional[str] If specified, checks that the start of the warning message matches this argument before "[Dd]efaulting to pandas". suffix : Optional[str] If specified, checks that the end of the warning message matches this argument after "[Dd]efaulting to pandas". Returns ------- pytest.recwarn.WarningsChecker or contextlib.nullcontext If ``condition`` is True, ``WarningsChecker`` is returned, which will check for a ``UserWarning`` indicating that Modin is defaulting to Pandas. If it is False, a ``nullcontext`` is returned to avoid checking for the warning about defaulting to Pandas. """ assert isinstance(condition, bool) return ( warns_that_defaulting_to_pandas(prefix=prefix, suffix=suffix) if condition else contextlib.nullcontext() ) def warns_that_defaulting_to_pandas(prefix=None, suffix=None): """ Assert that code warns that it's defaulting to pandas. Parameters ---------- prefix : Optional[str] If specified, checks that the start of the warning message matches this argument before "[Dd]efaulting to pandas". suffix : Optional[str] If specified, checks that the end of the warning message matches this argument after "[Dd]efaulting to pandas". Returns ------- pytest.recwarn.WarningsChecker """ match = "[Dd]efaulting to pandas" if prefix: # Message may be separated by newlines match = match + "(.|\\n)+" if suffix: match += "(.|\\n)+" + suffix return pytest.warns(UserWarning, match=match) @pytest.mark.parametrize("as_json", [True, False]) def test_show_versions(as_json, capsys): modin.utils.show_versions(as_json=as_json) versions = capsys.readouterr().out assert modin.__version__ in versions if as_json: versions = json.loads(versions) assert versions["modin dependencies"]["modin"] == modin.__version__ def test_warns_that_defaulting_to_pandas(): with warns_that_defaulting_to_pandas(): ErrorMessage.default_to_pandas() with warns_that_defaulting_to_pandas(): ErrorMessage.default_to_pandas(message="Function name") def test_warns_that_defaulting_to_pandas_if_false(): with pytest.raises(UserWarning): with warns_that_defaulting_to_pandas_if(False): ErrorMessage.default_to_pandas() def test_warns_that_defaulting_to_pandas_if_true(): with warns_that_defaulting_to_pandas_if(True): ErrorMessage.default_to_pandas() def test_warns_that_defaulting_to_pandas_if_non_bool(): with pytest.raises(AssertionError): warns_that_defaulting_to_pandas_if(3) def test_assert_dtypes_equal(): """Verify that `assert_dtypes_equal` from test utils works correctly (raises an error when it has to).""" from modin.tests.pandas.utils import assert_dtypes_equal # Serieses with equal dtypes sr1, sr2 = pd.Series([1.0]), pandas.Series([1.0]) assert sr1.dtype == sr2.dtype == "float" assert_dtypes_equal(sr1, sr2) # shouldn't raise an error since dtypes are equal # Serieses with different dtypes belonging to the same class sr1 = sr1.astype("int") assert sr1.dtype != sr2.dtype and sr1.dtype == "int" assert_dtypes_equal(sr1, sr2) # shouldn't raise an error since both are numeric # Serieses with different dtypes not belonging to the same class sr2 = sr2.astype("str") assert sr1.dtype != sr2.dtype and sr2.dtype == "object" with pytest.raises(AssertionError): assert_dtypes_equal(sr1, sr2) # Dfs with equal dtypes df1, df2 = create_test_dfs({"a": [1], "b": [1.0]}) assert_dtypes_equal(df1, df2) # shouldn't raise an error since dtypes are equal # Dfs with different dtypes belonging to the same class df1 = df1.astype({"a": "float"}) assert df1.dtypes["a"] != df2.dtypes["a"] assert_dtypes_equal(df1, df2) # shouldn't raise an error since both are numeric # Dfs with different dtypes df2 = df2.astype("str") with pytest.raises(AssertionError): assert_dtypes_equal(sr1, sr2) # Dfs with categorical dtypes df1 = df1.astype("category") df2 = df2.astype("category") assert_dtypes_equal(df1, df2) # shouldn't raise an error since both are categorical # Dfs with different dtypes (categorical and str) df1 = df1.astype({"a": "str"}) with pytest.raises(AssertionError): assert_dtypes_equal(df1, df2) def test_execute(): data = np.random.rand(100, 64) modin_df, pandas_df = create_test_dfs(data) partitions = modin_df._query_compiler._modin_frame._partitions.flatten() mgr_cls = modin_df._query_compiler._modin_frame._partition_mgr_cls # check modin case with patch.object(mgr_cls, "wait_partitions", new=Mock()): modin.utils.execute(modin_df) mgr_cls.wait_partitions.assert_called_once() assert (mgr_cls.wait_partitions.call_args[0] == partitions).all() # check pandas case without error with patch.object(mgr_cls, "wait_partitions", new=Mock()): modin.utils.execute(pandas_df) mgr_cls.wait_partitions.assert_not_called() with patch.object(mgr_cls, "wait_partitions", new=Mock()): modin.utils.execute(modin_df) mgr_cls.wait_partitions.assert_called_once() # check several modin dataframes with patch.object(mgr_cls, "wait_partitions", new=Mock()): modin.utils.execute(modin_df, modin_df[modin_df.columns[:4]]) mgr_cls.wait_partitions.assert_called assert mgr_cls.wait_partitions.call_count == 2 def current_execution_is_native() -> bool: """Whether the current global execution mode is native.""" return StorageFormat.get() == "Native" and Engine.get() == "Native" def df_or_series_using_native_execution(df: Union[pd.DataFrame, pd.Series]) -> bool: """Whether this Modin DataFrame or Series is using native execution.""" return ( df._query_compiler.engine == "Native" and df._query_compiler.storage_format == "Native" )
BaseChild
python
tensorflow__tensorflow
tensorflow/python/eager/ops_test.py
{ "start": 1695, "end": 19023 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testExecuteBasic(self): three = constant_op.constant(3) five = constant_op.constant(5) product = three * five self.assertAllEqual(15, product) @test_util.run_gpu_only def testMatMulGPU(self): three = constant_op.constant([[3.]]).gpu() five = constant_op.constant([[5.]]).gpu() product = math_ops.matmul(three, five) self.assertEqual([[15.0]], product.numpy()) def testExecuteStringAttr(self): three = constant_op.constant(3.0) checked_three = array_ops.check_numerics(three, message='just checking') self.assertEqual([[3]], checked_three.numpy()) def testExecuteFloatAttr(self): three = constant_op.constant(3.0) almost_three = constant_op.constant(2.8) almost_equal = math_ops.approximate_equal( three, almost_three, tolerance=0.3) self.assertTrue(almost_equal) def testExecuteIntAttr(self): three = constant_op.constant(3) four = constant_op.constant(4) total = math_ops.add_n([three, four]) self.assertAllEqual(7, total) def testExecuteBoolAttr(self): three = constant_op.constant([[3]]) five = constant_op.constant([[5]]) product = math_ops.matmul(three, five, transpose_a=True) self.assertAllEqual([[15]], product) def testExecuteOneListOutput(self): split_dim = constant_op.constant(1) value = constant_op.constant([[0, 1, 2], [3, 4, 5]]) x1, x2, x3 = array_ops.split(value, 3, axis=split_dim) self.assertAllEqual([[0], [3]], x1) self.assertAllEqual([[1], [4]], x2) self.assertAllEqual([[2], [5]], x3) def testGraphMode(self): graph = ops.Graph() with graph.as_default(), context.graph_mode(): array_ops.placeholder(dtypes.int32) self.assertLen(graph.get_operations(), 1) # See comments on handling of int32 tensors on GPU in # EagerTensor.__init__. @test_util.run_gpu_only def testInt32CPUDefault(self): with context.device('/gpu:0'): r = constant_op.constant(1) + constant_op.constant(2) self.assertAllEqual(r, 3) def testExecuteListOutputLen1(self): split_dim = constant_op.constant(1) value = constant_op.constant([[0, 1, 2], [3, 4, 5]]) result = array_ops.split(value, 1, axis=split_dim) self.assertIsInstance(result, list) self.assertLen(result, 1) self.assertAllEqual([[0, 1, 2], [3, 4, 5]], result[0]) def testExecuteListOutputLen0(self): empty = constant_op.constant([], dtype=dtypes.int32) result = array_ops_stack.unstack(empty, 0) self.assertIsInstance(result, list) self.assertEmpty(result) def testExecuteMultipleNonListOutput(self): x = constant_op.constant([1, 2, 3, 4, 5, 6]) y = constant_op.constant([1, 3, 5]) result = array_ops.listdiff(x, y) out, idx = result self.assertIs(out, result.out) self.assertIs(idx, result.idx) self.assertAllEqual([2, 4, 6], out) self.assertAllEqual([1, 3, 5], idx) def testExecuteMultipleListOutput(self): split_dim = constant_op.constant(1, dtype=dtypes.int64) indices = constant_op.constant([[0, 2], [0, 4], [0, 5], [1, 0], [1, 1]], dtype=dtypes.int64) values = constant_op.constant([2, 3, 5, 7, 11]) shape = constant_op.constant([2, 7], dtype=dtypes.int64) result = sparse_ops.gen_sparse_ops.sparse_split( split_dim, indices, values, shape, num_split=2) output_indices, output_values, output_shape = result self.assertLen(output_indices, 2) self.assertLen(output_values, 2) self.assertLen(output_shape, 2) self.assertEqual(output_indices, result.output_indices) self.assertEqual(output_values, result.output_values) self.assertEqual(output_shape, result.output_shape) self.assertAllEqual([[0, 2], [1, 0], [1, 1]], output_indices[0]) self.assertAllEqual([[0, 0], [0, 1]], output_indices[1]) self.assertAllEqual([2, 7, 11], output_values[0]) self.assertAllEqual([3, 5], output_values[1]) self.assertAllEqual([2, 4], output_shape[0]) self.assertAllEqual([2, 3], output_shape[1]) # TODO(josh11b): Test an op that has multiple outputs, some but not # all of which are lists. Examples: barrier_take_many (currently # unsupported since it uses a type list) or sdca_optimizer (I don't # have an example of legal inputs & outputs). def testComposition(self): x = constant_op.constant(1, dtype=dtypes.int32) three_x = x + x + x self.assertEqual(dtypes.int32, three_x.dtype) self.assertAllEqual(3, three_x) def testOperatorOverrides(self): def ops_test(v1, v2): a = constant_op.constant(v1) b = constant_op.constant(v2) self.assertAllEqual((-a), np.negative(v1)) self.assertAllEqual(abs(b), np.absolute(v2)) self.assertAllEqual((a + b), np.add(v1, v2)) self.assertAllEqual((a - b), np.subtract(v1, v2)) self.assertAllEqual((a * b), np.multiply(v1, v2)) self.assertAllEqual((a * a), np.multiply(v1, v1)) if all(x >= 0 for x in v2): self.assertAllEqual((a**b), np.power(v1, v2)) self.assertAllEqual((a / b), np.true_divide(v1, v2)) self.assertAllEqual((a / a), np.true_divide(v1, v1)) self.assertAllEqual((a % b), np.mod(v1, v2)) self.assertAllEqual((a < b), np.less(v1, v2)) self.assertAllEqual((a <= b), np.less_equal(v1, v2)) self.assertAllEqual((a > b), np.greater(v1, v2)) self.assertAllEqual((a >= b), np.greater_equal(v1, v2)) # TODO(b/120678848): Remove the else branch once we enable # tensor.Tensor._USE_EQUALITY by default. if tensor.Tensor._USE_EQUALITY: self.assertAllEqual((a == b), np.equal(v1, v2)) self.assertAllEqual((a != b), np.not_equal(v1, v2)) else: self.assertAllEqual((a == b), np.equal(v1, v2)[0]) self.assertAllEqual((a != b), np.not_equal(v1, v2)[0]) self.assertAllEqual(v1[0], a[constant_op.constant(0)]) ops_test([1, 4, 8], [2, 3, 5]) ops_test([1, -4, -5], [-2, 3, -6]) def test_basic_slice(self): npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3) t = constant_op.constant(npt) self.assertAllEqual(npt[:, :, :], t[:, :, :]) self.assertAllEqual(npt[::, ::, ::], t[::, ::, ::]) self.assertAllEqual(npt[::1, ::1, ::1], t[::1, ::1, ::1]) self.assertAllEqual(npt[::1, ::5, ::2], t[::1, ::5, ::2]) self.assertAllEqual(npt[::-1, :, :], t[::-1, :, :]) self.assertAllEqual(npt[:, ::-1, :], t[:, ::-1, :]) self.assertAllEqual(npt[:, :, ::-1], t[:, :, ::-1]) self.assertAllEqual(npt[-2::-1, :, ::1], t[-2::-1, :, ::1]) self.assertAllEqual(npt[-2::-1, :, ::2], t[-2::-1, :, ::2]) def testDegenerateSlices(self): npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3) t = constant_op.constant(npt) # degenerate by offering a forward interval with a negative stride self.assertAllEqual(npt[0:-1:-1, :, :], t[0:-1:-1, :, :]) # degenerate with a reverse interval with a positive stride self.assertAllEqual(npt[-1:0, :, :], t[-1:0, :, :]) # empty interval in every dimension self.assertAllEqual(npt[-1:0, 2:2, 2:3:-1], t[-1:0, 2:2, 2:3:-1]) def testEllipsis(self): npt = np.array( [[[[[1, 2], [3, 4], [5, 6]]], [[[7, 8], [9, 10], [11, 12]]]]]) t = constant_op.constant(npt) self.assertAllEqual(npt[0:], t[0:]) # implicit ellipsis self.assertAllEqual(npt[0:, ...], t[0:, ...]) # ellipsis alone self.assertAllEqual(npt[...], t[...]) # ellipsis at end self.assertAllEqual(npt[0:1, ...], t[0:1, ...]) # ellipsis at begin self.assertAllEqual(npt[..., 0:1], t[..., 0:1]) # ellipsis at middle self.assertAllEqual(npt[0:1, ..., 0:1], t[0:1, ..., 0:1]) def testShrink(self): npt = np.array([[[[[1, 2, 4, 5], [5, 6, 7, 8], [9, 10, 11, 12]]], [[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]]]]) t = constant_op.constant(npt) self.assertAllEqual(npt[:, :, :, :, 3], t[:, :, :, :, 3]) self.assertAllEqual(npt[..., 3], t[..., 3]) self.assertAllEqual(npt[:, 0], t[:, 0]) self.assertAllEqual(npt[:, :, 0], t[:, :, 0]) @test_util.run_gpu_only def testOpWithInputsOnDifferentDevices(self): # The GPU kernel for the Reshape op requires that the # shape input be on CPU. value = constant_op.constant([1., 2.]).gpu() shape = constant_op.constant([2, 1]) reshaped = array_ops.reshape(value, shape) self.assertAllEqual([[1], [2]], reshaped.cpu()) def testInt64(self): # Fill requires the first input to be an int32 tensor. self.assertAllEqual( [1.0, 1.0], array_ops.fill(constant_op.constant([2], dtype=dtypes.int64), constant_op.constant(1))) @test_util.run_gpu_only def testOutputOnHostMemory(self): # The Shape op kernel on GPU places the output in host memory. value = constant_op.constant([1.]).gpu() shape = array_ops.shape(value) self.assertEqual([1], shape.numpy()) @test_util.run_gpu_only def testSilentCopy(self): # Temporarily replace the context # pylint: disable=protected-access old_context = context.context() context._set_context(context.Context()) try: config.set_device_policy('silent') cpu_tensor = constant_op.constant(1.0) gpu_tensor = cpu_tensor.gpu() self.assertAllEqual(cpu_tensor + gpu_tensor, 2.0) finally: context._set_context(old_context) # pylint: enable=protected-access @test_util.run_gpu_only def testSoftPlacement(self): # Temporarily replace the context # pylint: disable=protected-access old_context = context.context() context._set_context(context.Context()) try: config.set_device_policy('silent') config.set_soft_device_placement(True) cpu_tensor = constant_op.constant(1.0) result = cpu_tensor + cpu_tensor self.assertEqual(result.device, '/job:localhost/replica:0/task:0/device:GPU:0') finally: context._set_context(old_context) # pylint: enable=protected-access def testRandomUniform(self): scalar_shape = constant_op.constant([], dtype=dtypes.int32) x = random_ops.random_uniform(scalar_shape) self.assertEqual(0, x.shape.ndims) self.assertEqual(dtypes.float32, x.dtype) x = random_ops.random_uniform( scalar_shape, minval=constant_op.constant(5.), maxval=constant_op.constant(6.)) self.assertLess(x, 6) self.assertGreaterEqual(x, 5) def testArgsToMatchingEagerDefault(self): # Uses default ctx = context.context() allowed_dtypes = [dtypes.int32, dtypes.int64] # Follows standard int conversion rules t, r = execute.args_to_matching_eager([[3, 4]], ctx, allowed_dtypes, dtypes.int32) self.assertEqual(t, dtypes.int32) self.assertEqual(r[0].dtype, dtypes.int32) t, r = execute.args_to_matching_eager([[3, 4]], ctx, allowed_dtypes, dtypes.int64) self.assertEqual(t, dtypes.int32) self.assertEqual(r[0].dtype, dtypes.int32) # Use int64 since it is a better fit t, r = execute.args_to_matching_eager([[2**48]], ctx, allowed_dtypes, dtypes.int32) self.assertEqual(t, dtypes.int64) self.assertEqual(r[0].dtype, dtypes.int64) # When the regular tensor conversion fails, then use the default type as a # hint. allowed_dtypes = [dtypes.uint32, dtypes.uint32] t, r = execute.args_to_matching_eager([[3, 4]], ctx, allowed_dtypes, dtypes.uint32) self.assertEqual(t, dtypes.uint32) self.assertEqual(r[0].dtype, dtypes.uint32) t, r = execute.args_to_matching_eager([[3, 4]], ctx, allowed_dtypes, dtypes.uint64) self.assertEqual(t, dtypes.uint64) self.assertEqual(r[0].dtype, dtypes.uint64) t, r = execute.args_to_matching_eager([], ctx, allowed_dtypes, dtypes.int64) self.assertEqual(t, dtypes.int64) # Doesn't use default allowed_dtypes = [dtypes.int32, dtypes.string] t, r = execute.args_to_matching_eager([['string', 'arg']], ctx, allowed_dtypes, dtypes.int32) self.assertEqual(t, dtypes.string) self.assertEqual(r[0].dtype, dtypes.string) def testIdentity(self): self.assertAllEqual(2, array_ops.identity(2)) @test_util.run_gpu_only def testIdentityOnVariable(self): with context.device('/gpu:0'): v = resource_variable_ops.ResourceVariable(True) self.assertAllEqual(True, array_ops.identity(v)) def testIncompatibleSetShape(self): x = constant_op.constant(1) with self.assertRaises(ValueError): x.set_shape((1, 2)) def testCompatibleSetShape(self): x = constant_op.constant([[1, 2]]) x.set_shape(tensor_shape.TensorShape([None, 2])) self.assertEqual(x.get_shape(), (1, 2)) @parameterized.named_parameters( ('Tensor', lambda: constant_op.constant(1.3+1j)), ('Variable', lambda: resource_variable_ops.ResourceVariable(1.3+1j))) def testCastToPrimitiveTypesFrom(self, value_fn): x = value_fn() self.assertIsInstance(int(x), int) self.assertEqual(int(x), 1) self.assertIsInstance(float(x), float) self.assertAllClose(float(x), 1.3) self.assertIsInstance(complex(x), complex) self.assertAllClose(complex(x), 1.3+1j) def testCastNonScalarToPrimitiveTypesFails(self): x = constant_op.constant([1.3, 2]) with self.assertRaises(TypeError): int(x) with self.assertRaises(TypeError): float(x) def testRange(self): x = constant_op.constant(2) self.assertEqual([0, 1], list(range(x))) def testFormatString(self): x = constant_op.constant(3.1415) self.assertEqual('3.14', '{:.2f}'.format(x)) def testNoOpIsNone(self): self.assertIsNone(control_flow_ops.no_op()) def testEagerContextPreservedAcrossThreads(self): def init_fn(): self.assertTrue(context.executing_eagerly()) with ops.init_scope(): self.assertTrue(context.executing_eagerly()) context_switches = context.context().context_switches self.assertLen(context_switches.stack, 1) self.assertFalse(context_switches.stack[0].is_building_function) self.assertEqual(context_switches.stack[0].enter_context_fn, context.eager_mode) self.assertTrue(context.executing_eagerly()) t1 = threading.Thread(target=init_fn) t1.start() t1.join() def testWeakrefEagerTensor(self): x = constant_op.constant([[1.]]) x.at1 = constant_op.constant([[2.]]) x.at2 = 3. weak_x = weakref.ref(x) weak_xat1 = weakref.ref(x.at1) del x self.assertIs(weak_x(), None) self.assertIs(weak_xat1(), None) def testWeakKeyDictionaryTensor(self): weak_key_dict = weakref.WeakKeyDictionary() strong_x = constant_op.constant([[1.]]) strong_y = constant_op.constant([[2.]]) strong_x_ref = strong_x.ref() strong_y_ref = strong_y.ref() weak_key_dict[strong_x_ref] = constant_op.constant([[3.]]) weak_key_dict[strong_y_ref] = constant_op.constant([[4.]]) strong_y.a = constant_op.constant([[5.]]) weak_x_ref = weakref.ref(strong_x) del strong_x, strong_x_ref self.assertIs(weak_x_ref(), None) self.assertEqual([strong_y_ref], list(weak_key_dict)) self.assertLen(list(weak_key_dict), 1) self.assertLen(weak_key_dict, 1) del strong_y, strong_y_ref self.assertEqual([], list(weak_key_dict)) def testEagerTensorsCanBeGarbageCollected(self): x = constant_op.constant([[1.]]) y = constant_op.constant([[2.]]) x.y = y y.x = x weak_x = weakref.ref(x) weak_y = weakref.ref(y) del x del y # Run a gc a few times to ensure cycles are resolved. gc.collect() gc.collect() gc.collect() gc.collect() self.assertIs(weak_x(), None) self.assertIs(weak_y(), None) @test_util.disable_tfrt( 'b/153697193: tfrt cannot decode python stacktrace yet') # TODO(b/234153596): Disabled because it invalidates stack traces on other # tests (due to partial migration to absl::Status). def DISABLED_testAsyncExceptionStackTrace(self): config.set_synchronous_execution(False) def exception_originated_from_here(): # Invalid shapes for matmul. return math_ops.matmul([[1]], [[2], [3]]) # In sync mode, an exception would have been raised here but since this is # in async, the exception will be raised next. x = exception_originated_from_here() with self.assertRaisesRegex(errors_impl.InvalidArgumentError, 'in exception_originated_from_here'): x.numpy() context.async_clear_error() config.set_synchronous_execution(True) def testCrossContextTensorCache(self): old_context = context.context() old_x = constant_op.constant(9.5) context._set_context(context.Context()) try: new_x = constant_op.constant(9.5) self.assertEqual(new_x.numpy(), 9.5) finally: context._set_context(old_context) self.assertEqual(old_x.numpy(), 9.5) if __name__ == '__main__': test.main()
OpsTest
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_modelresource/test_data_import.py
{ "start": 307, "end": 5698 }
class ____(TestCase): def setUp(self): self.resource = BookResource() self.book = Book.objects.create(name="Some book") self.dataset = tablib.Dataset(headers=["id", "name", "author_email", "price"]) row = [self.book.pk, "Some book", "test@example.com", "10.25"] self.dataset.append(row) def test_get_diff(self): diff = Diff(self.resource, self.book, False) book2 = Book(name="Some other book") diff.compare_with(self.resource, book2) html = diff.as_html() headers = self.resource.get_export_headers() self.assertEqual( html[headers.index("name")], '<span>Some </span><ins style="background:#e6ffe6;">' "other </ins><span>book</span>", ) self.assertFalse(html[headers.index("author_email")]) def test_import_data_update(self): result = self.resource.import_data(self.dataset, raise_errors=True) self.assertFalse(result.has_errors()) self.assertEqual(len(result.rows), 1) self.assertTrue(result.rows[0].diff) self.assertEqual( result.rows[0].import_type, results.RowResult.IMPORT_TYPE_UPDATE ) self.assertEqual(result.rows[0].row_values.get("name"), None) self.assertEqual(result.rows[0].row_values.get("author_email"), None) self.assertIsNone(result.rows[0].instance) self.assertIsNotNone(result.rows[0].original) instance = Book.objects.get(pk=self.book.pk) self.assertEqual(instance.author_email, "test@example.com") self.assertEqual(instance.price, Decimal("10.25")) def test_import_data_new(self): Book.objects.all().delete() self.assertEqual(0, Book.objects.count()) result = self.resource.import_data(self.dataset, raise_errors=True) self.assertFalse(result.has_errors()) self.assertEqual(len(result.rows), 1) self.assertTrue(result.rows[0].diff) self.assertEqual(result.rows[0].import_type, results.RowResult.IMPORT_TYPE_NEW) self.assertEqual(result.rows[0].row_values.get("name"), None) self.assertEqual(result.rows[0].row_values.get("author_email"), None) self.assertIsNone(result.rows[0].instance) self.assertIsNone(result.rows[0].original) self.assertEqual(1, Book.objects.count()) instance = Book.objects.first() self.assertEqual(instance.author_email, "test@example.com") self.assertEqual(instance.price, Decimal("10.25")) def test_import_data_new_store_instance(self): self.resource = BookResourceWithStoreInstance() Book.objects.all().delete() self.assertEqual(0, Book.objects.count()) result = self.resource.import_data(self.dataset, raise_errors=True) self.assertEqual(result.rows[0].import_type, results.RowResult.IMPORT_TYPE_NEW) self.assertIsNotNone(result.rows[0].instance) self.assertIsNone(result.rows[0].original) self.assertEqual(1, Book.objects.count()) book = Book.objects.first() self.assertEqual(book.pk, result.rows[0].instance.pk) def test_import_data_update_store_instance(self): self.resource = BookResourceWithStoreInstance() result = self.resource.import_data(self.dataset, raise_errors=True) self.assertEqual( result.rows[0].import_type, results.RowResult.IMPORT_TYPE_UPDATE ) self.assertIsNotNone(result.rows[0].instance) self.assertIsNotNone(result.rows[0].original) self.assertEqual(1, Book.objects.count()) book = Book.objects.first() self.assertEqual(book.pk, result.rows[0].instance.pk) @skipUnlessDBFeature("supports_transactions") @mock.patch("import_export.resources.connections") def test_import_data_no_transaction(self, mock_db_connections): class Features: supports_transactions = False class DummyConnection: features = Features() dummy_connection = DummyConnection() mock_db_connections.__getitem__.return_value = dummy_connection result = self.resource.import_data( self.dataset, dry_run=True, use_transactions=False, raise_errors=True ) self.assertFalse(result.has_errors()) self.assertEqual(len(result.rows), 1) self.assertTrue(result.rows[0].diff) self.assertEqual( result.rows[0].import_type, results.RowResult.IMPORT_TYPE_UPDATE ) self.assertEqual(result.rows[0].row_values.get("name"), None) self.assertEqual(result.rows[0].row_values.get("author_email"), None) def test_import_data_new_override_do_instance_save(self): class CustomDoInstanceSave(BookResource): is_create = False def do_instance_save(self, instance, is_create): self.is_create = is_create super().do_instance_save(instance, is_create) Book.objects.all().delete() self.assertEqual(0, Book.objects.count()) self.resource = CustomDoInstanceSave() self.assertFalse(self.resource.is_create) result = self.resource.import_data(self.dataset, raise_errors=True) self.assertFalse(result.has_errors()) self.assertEqual(1, Book.objects.count()) self.assertTrue(self.resource.is_create)
DataImportTests
python
spyder-ide__spyder
spyder/plugins/outlineexplorer/api.py
{ "start": 3288, "end": 4768 }
class ____(QObject): """ Proxy class between editors and OutlineExplorerWidget. """ sig_cursor_position_changed = Signal(int, int) sig_outline_explorer_data_changed = Signal(list) sig_start_outline_spinner = Signal() def __init__(self): super().__init__() self.fname = None def is_python(self): """Return whether the editor is a python file or not.""" raise NotImplementedError def get_id(self): """Return an unique id, used for identify objects in a dict""" raise NotImplementedError def give_focus(self): """Give focus to the editor, called when toogling visibility of OutlineExplorerWidget.""" raise NotImplementedError def get_line_count(self): """Return the number of lines of the editor (int).""" raise NotImplementedError def parent(self): """This is used for diferenciate editors in multi-window mode.""" return None def get_cursor_line_number(self): """Return the cursor line number.""" raise NotImplementedError def outlineexplorer_data_list(self): """Returns a list of outline explorer data.""" raise NotImplementedError def request_symbols(self): """Request current editor symbols.""" raise NotImplementedError @property def is_cloned(self): """Check if the associated editor is cloned.""" return False
OutlineExplorerProxy
python
pytest-dev__pytest-asyncio
docs/reference/fixtures/event_loop_policy_parametrized_example.py
{ "start": 184, "end": 619 }
class ____(DefaultEventLoopPolicy): pass @pytest.fixture( params=( DefaultEventLoopPolicy(), CustomEventLoopPolicy(), ), ) def event_loop_policy(request): return request.param @pytest.mark.asyncio @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def test_uses_custom_event_loop_policy(): assert isinstance(asyncio.get_event_loop_policy(), DefaultEventLoopPolicy)
CustomEventLoopPolicy
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 193683, "end": 194541 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateRef""" __schema__ = github_schema __field_names__ = ("repository_id", "name", "oid", "client_mutation_id") repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId") """The Node ID of the Repository to create the Ref in.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The fully qualified name of the new Ref (ie: `refs/heads/my_new_branch`). """ oid = sgqlc.types.Field(sgqlc.types.non_null(GitObjectID), graphql_name="oid") """The GitObjectID that the new Ref shall target. Must point to a commit. """ client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateRefInput
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 25601, "end": 26085 }
class ____(PyperclipException): """ Exception raised when clipboard functionality is unsupported by Windows. Access to the clipboard handle would be denied due to some other window process is accessing it. """ def __init__(self, message: str) -> None: # attr only exists on Windows, so typing fails on other platforms message += f" ({ctypes.WinError()})" # type: ignore[attr-defined] super().__init__(message)
PyperclipWindowsException
python
conda__conda
conda/env/env.py
{ "start": 11672, "end": 14324 }
class ____: """A class representing an ``environment.yaml`` file""" def __init__( self, name=None, filename=None, channels=None, dependencies=None, prefix=None, variables=None, ): self.name = name self.filename = filename self.prefix = prefix self.dependencies = Dependencies(dependencies) self.variables = variables if channels is None: channels = [] self.channels = channels def add_channels(self, channels): """Add channels to the ``EnvironmentYaml``""" self.channels = list(unique(chain.from_iterable((channels, self.channels)))) def remove_channels(self): """Remove all channels from the ``EnvironmentYaml``""" self.channels = [] def to_dict(self, stream=None): """Convert information related to the ``EnvironmentYaml`` into a dictionary""" d = {"name": self.name} if self.channels: d["channels"] = self.channels if self.dependencies: d["dependencies"] = self.dependencies.raw if self.variables: d["variables"] = self.variables if self.prefix: d["prefix"] = self.prefix if stream is None: return d stream.write(json.dumps(d)) def to_yaml(self, stream=None): """Convert information related to the ``EnvironmentYaml`` into a ``yaml`` string""" d = self.to_dict() out = yaml_safe_dump(d, stream) if stream is None: return out def save(self): """Save the ``EnvironmentYaml`` data to a ``yaml`` file""" with open(self.filename, "wb") as fp: self.to_yaml(stream=fp) def to_environment_model(self) -> EnvironmentModel: """Convert the ``Environment`` into a ``model.Environment`` object""" config = EnvironmentConfig(channels=tuple(self.channels)) external_packages = {} if pip_dependencies := self.dependencies.get("pip"): external_packages["pip"] = pip_dependencies requested_packages = [ MatchSpec(spec) for spec in self.dependencies.get("conda", []) ] return EnvironmentModel( prefix=self.prefix or context.target_prefix, platform=context.subdir, name=self.name, config=config, variables=self.variables, external_packages=external_packages, requested_packages=requested_packages, ) @deprecated("26.3", "26.9", addendum="Use `conda.env.env.EnvironmentYaml` instead.")
EnvironmentYaml
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/assignment1.py
{ "start": 132, "end": 1153 }
class ____: def __init__(self): self.string_list: list[str] = [] def do_something(self, num: int) -> str: return "" a = ClassA() a.string_list = ["yep"] # This should generate an error because of a type mismatch. a.string_list = "bbb" # This should generate an error because of a type mismatch. a.string_list = {} # This should generate an error because of a type mismatch. a.string_list = [1] # This should generate an error because there is no member # called string_list2 defined. a.string_list2 = 4 def patch1(num: int) -> str: return "" def patch2(self, num: int) -> str: return "" a.do_something = lambda num: "hello" a.do_something = patch1 # This should generate an error because of a param count mismatch a.do_something = lambda: "hello" # This should generate an error because of a return type mismatch a.do_something = lambda x: 1 ClassA.do_something = patch2 # This should generate an error because of a param count mismatch ClassA.do_something = patch1
ClassA
python
mlflow__mlflow
mlflow/gateway/schemas/chat.py
{ "start": 1067, "end": 1139 }
class ____(RequestModel): name: str
UnityCatalogFunctionToolDefinition
python
pytorch__pytorch
test/torch_np/numpy_tests/fft/test_helper.py
{ "start": 526, "end": 5468 }
class ____(TestCase): def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] y = [-4, -3, -2, -1, 0, 1, 2, 3, 4] assert_array_almost_equal(fft.fftshift(x), y) assert_array_almost_equal(fft.ifftshift(y), x) x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1] y = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] assert_array_almost_equal(fft.fftshift(x), y) assert_array_almost_equal(fft.ifftshift(y), x) def test_inverse(self): for n in [1, 4, 9, 100, 211]: x = np.random.random((n,)) assert_array_almost_equal(fft.ifftshift(fft.fftshift(x)), x) def test_axes_keyword(self): freqs = [[0, 1, 2], [3, 4, -4], [-3, -2, -1]] shifted = [[-1, -3, -2], [2, 0, 1], [-4, 3, 4]] assert_array_almost_equal(fft.fftshift(freqs, axes=(0, 1)), shifted) assert_array_almost_equal( fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,)) ) assert_array_almost_equal(fft.ifftshift(shifted, axes=(0, 1)), freqs) assert_array_almost_equal( fft.ifftshift(shifted, axes=0), fft.ifftshift(shifted, axes=(0,)) ) assert_array_almost_equal(fft.fftshift(freqs), shifted) assert_array_almost_equal(fft.ifftshift(shifted), freqs) def test_uneven_dims(self): """Test 2D input, which has uneven dimension sizes""" freqs = [[0, 1], [2, 3], [4, 5]] # shift in dimension 0 shift_dim0 = [[4, 5], [0, 1], [2, 3]] assert_array_almost_equal(fft.fftshift(freqs, axes=0), shift_dim0) assert_array_almost_equal(fft.ifftshift(shift_dim0, axes=0), freqs) assert_array_almost_equal(fft.fftshift(freqs, axes=(0,)), shift_dim0) assert_array_almost_equal(fft.ifftshift(shift_dim0, axes=[0]), freqs) # shift in dimension 1 shift_dim1 = [[1, 0], [3, 2], [5, 4]] assert_array_almost_equal(fft.fftshift(freqs, axes=1), shift_dim1) assert_array_almost_equal(fft.ifftshift(shift_dim1, axes=1), freqs) # shift in both dimensions shift_dim_both = [[5, 4], [1, 0], [3, 2]] assert_array_almost_equal(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both) assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs) assert_array_almost_equal(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both) assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs) # axes=None (default) shift in all dimensions assert_array_almost_equal(fft.fftshift(freqs, axes=None), shift_dim_both) assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=None), freqs) assert_array_almost_equal(fft.fftshift(freqs), shift_dim_both) assert_array_almost_equal(fft.ifftshift(shift_dim_both), freqs) def test_equal_to_original(self): """Test that the new (>=v1.15) implementation (see #10073) is equal to the original (<=v1.14)""" if TEST_WITH_TORCHDYNAMO: from numpy import arange, asarray, concatenate, take else: from torch._numpy import arange, asarray, concatenate, take def original_fftshift(x, axes=None): """How fftshift was implemented in v1.14""" tmp = asarray(x) ndim = tmp.ndim if axes is None: axes = list(range(ndim)) elif isinstance(axes, int): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = (n + 1) // 2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y def original_ifftshift(x, axes=None): """How ifftshift was implemented in v1.14""" tmp = asarray(x) ndim = tmp.ndim if axes is None: axes = list(range(ndim)) elif isinstance(axes, int): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = n - (n + 1) // 2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y # create possible 2d array combinations and try all possible keywords # compare output to original functions for i in range(16): for j in range(16): for axes_keyword in [0, 1, None, (0,), (0, 1)]: inp = np.random.rand(i, j) assert_array_almost_equal( fft.fftshift(inp, axes_keyword), original_fftshift(inp, axes_keyword), ) assert_array_almost_equal( fft.ifftshift(inp, axes_keyword), original_ifftshift(inp, axes_keyword), )
TestFFTShift
python
uqfoundation__dill
dill/_dill.py
{ "start": 36237, "end": 36717 }
class ____(object): def __init__(self, attrs, index=None): self.attrs = attrs self.index = index def __getattribute__(self, attr): attrs = object.__getattribute__(self, "attrs") index = object.__getattribute__(self, "index") if index is None: index = len(attrs) attrs.append(attr) else: attrs[index] = ".".join([attrs[index], attr]) return type(self)(attrs, index)
_attrgetter_helper
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0035_backport_indexes.py
{ "start": 149, "end": 1310 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0034_remove_protected_privacy_level"), ] operations = [ migrations.AlterField( model_name="build", name="date", field=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Date"), ), migrations.AlterField( model_name="build", name="state", field=models.CharField( choices=[ ("triggered", "Triggered"), ("cloning", "Cloning"), ("installing", "Installing"), ("building", "Building"), ("uploading", "Uploading"), ("finished", "Finished"), ], db_index=True, default="finished", max_length=55, verbose_name="State", ), ), migrations.AddIndex( model_name="build", index=models.Index(fields=["project", "date"], name="builds_buil_project_fea68c_idx"), ), ]
Migration
python
hynek__structlog
src/structlog/dev.py
{ "start": 3930, "end": 5243 }
class ____: """ Column styles settings for console rendering. These are console ANSI codes that are printed before the respective fields. This allows for a certain amount of customization if you don't want to configure your columns. .. versionadded:: 25.5.0 It was handled by private structures before. """ reset: str bright: str level_critical: str level_exception: str level_error: str level_warn: str level_info: str level_debug: str level_notset: str timestamp: str logger_name: str kv_key: str kv_value: str _colorful_styles = ColumnStyles( reset=RESET_ALL, bright=BRIGHT, level_critical=RED, level_exception=RED, level_error=RED, level_warn=YELLOW, level_info=GREEN, level_debug=GREEN, level_notset=RED_BACK, timestamp=DIM, logger_name=BLUE, kv_key=CYAN, kv_value=MAGENTA, ) _plain_styles = ColumnStyles( reset="", bright="", level_critical="", level_exception="", level_error="", level_warn="", level_info="", level_debug="", level_notset="", timestamp="", logger_name="", kv_key="", kv_value="", ) # Backward compatibility aliases _ColorfulStyles = _colorful_styles _PlainStyles = _plain_styles
ColumnStyles
python
doocs__leetcode
solution/2100-2199/2162.Minimum Cost to Set Cooking Time/Solution.py
{ "start": 0, "end": 688 }
class ____: def minCostSetTime( self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int ) -> int: def f(m, s): if not 0 <= m < 100 or not 0 <= s < 100: return inf arr = [m // 10, m % 10, s // 10, s % 10] i = 0 while i < 4 and arr[i] == 0: i += 1 t = 0 prev = startAt for v in arr[i:]: if v != prev: t += moveCost t += pushCost prev = v return t m, s = divmod(targetSeconds, 60) ans = min(f(m, s), f(m - 1, s + 60)) return ans
Solution
python
mkdocs__mkdocs
mkdocs/structure/pages.py
{ "start": 12326, "end": 13003 }
class ____(markdown.treeprocessors.Treeprocessor): def __init__(self, file: File, files: Files, config: MkDocsConfig) -> None: self.present_anchor_ids: set[str] = set() def run(self, root: etree.Element) -> None: add = self.present_anchor_ids.add for element in root.iter(): if anchor := element.get('id'): add(anchor) if element.tag == 'a': if anchor := element.get('name'): add(anchor) def _register(self, md: markdown.Markdown) -> None: md.treeprocessors.register(self, "mkdocs_extract_anchors", priority=5) # Same as 'toc'.
_ExtractAnchorsTreeprocessor
python
great-expectations__great_expectations
great_expectations/data_context/store/datasource_store.py
{ "start": 1353, "end": 10237 }
class ____(Store): """ A DatasourceStore manages Datasources for the DataContext. """ _key_class = DataContextVariableKey def __init__( self, store_name: Optional[str] = None, store_backend: Optional[dict] = None, runtime_environment: Optional[dict] = None, ) -> None: super().__init__( store_backend=store_backend, runtime_environment=runtime_environment, store_name=store_name, # type: ignore[arg-type] # FIXME CoP ) # Gather the call arguments of the present function (include the "module_name" and add the "class_name"), filter # noqa: E501 # FIXME CoP # out the Falsy values, and set the instance "_config" variable equal to the resulting dictionary. # noqa: E501 # FIXME CoP self._config = { "store_backend": store_backend, "runtime_environment": runtime_environment, "store_name": store_name, "module_name": self.__class__.__module__, "class_name": self.__class__.__name__, } filter_properties_dict(properties=self._config, clean_falsy=True, inplace=True) @override def remove_key(self, key: Union[DataContextVariableKey, GXCloudIdentifier]) -> None: """ See parent `Store.remove_key()` for more information """ return self._store_backend.remove_key(key.to_tuple()) @override def serialize(self, value: FluentDatasource) -> dict: """ See parent 'Store.serialize()' for more information """ # DataAsset.order_by is not supported by v1, but has not yet been removed, # so we drop it before serialization and alert the user with a warning. if any(asset.order_by for asset in value.assets): asset_names = [asset.name for asset in value.assets if asset.order_by] warnings.warn( f"Datasource {value.name} has one or more DataAssets that define a non-empty " "order_by field. This property is no longer supported, and will be " "silently dropped during serialization. The following DataAsset(s) are affected: " + ", ".join(asset_names), category=UserWarning, ) exclude: MappingIntStrAny = {"assets": {"__all__": {"order_by"}}} return value._json_dict(exclude=exclude) @override def deserialize(self, value: dict | FluentDatasource) -> FluentDatasource: """ See parent 'Store.deserialize()' for more information """ # When using the InlineStoreBackend, objects are already converted to their respective config types. # noqa: E501 # FIXME CoP if isinstance(value, FluentDatasource): return value else: type_: str | None = value["type"] if not type_: raise ValueError("Datasource type is missing") # noqa: TRY003 # FIXME CoP try: datasource_model = DataSourceManager.type_lookup[type_] return datasource_model(**value) except (PydanticValidationError, LookupError) as config_error: warnings.warn( f"Datasource {value.get('name', '')} configuration is invalid." " Check `my_datasource.config_error` attribute for more details.", GxInvalidDatasourceWarning, ) # Any fields that are not part of the schema are ignored return InvalidDatasource(config_error=config_error, **value) @override @classmethod def gx_cloud_response_json_to_object_dict( cls, response_json: CloudResponsePayloadTD, # type: ignore[override] # FIXME CoP ) -> dict: """ This method takes full json response from GX cloud and outputs a dict appropriate for deserialization into a GX object """ data = response_json["data"] if isinstance(data, list): if len(data) > 1: # Larger arrays of datasources should be handled by `gx_cloud_response_json_to_object_collection` # noqa: E501 # FIXME CoP raise TypeError(f"GX Cloud returned {len(data)} Datasources but expected 1") # noqa: TRY003 # FIXME CoP data = data[0] return DatasourceStore._convert_raw_json_to_object_dict(data) @override @staticmethod def _convert_raw_json_to_object_dict(data: DataPayload) -> dict: # type: ignore[override] # FIXME CoP return data # type: ignore[return-value] # FIXME CoP def retrieve_by_name(self, name: str) -> FluentDatasource: """Retrieves a Datasource persisted in the store by it's given name. Args: name: The name of the Datasource to retrieve. Returns: The Datasource persisted in the store that is associated with the given input name. Raises: ValueError if a Datasource is not found. """ datasource_key: Union[DataContextVariableKey, GXCloudIdentifier] = ( self.store_backend.build_key(name=name) ) if not self.has_key(datasource_key): raise ValueError( # noqa: TRY003 # FIXME CoP f"Unable to load datasource `{name}` -- no configuration found or invalid configuration." # noqa: E501 # FIXME CoP ) datasource_config: FluentDatasource = copy.deepcopy(self.get(datasource_key)) # type: ignore[arg-type] # FIXME CoP datasource_config.name = name return datasource_config def delete(self, datasource_config: FluentDatasource) -> None: """Deletes a Datasource persisted in the store using its config. Args: datasource_config: The config of the Datasource to delete. """ self.remove_key(self._build_key_from_config(datasource_config)) @override def _build_key_from_config( # type: ignore[override] # FIXME CoP self, datasource_config: FluentDatasource ) -> Union[GXCloudIdentifier, DataContextVariableKey]: id_: str | None = ( str(datasource_config.id) if datasource_config.id else datasource_config.id # type: ignore[assignment] # uuid will be converted to str ) return self.store_backend.build_key(name=datasource_config.name, id=id_) def get_fluent_datasource_by_name(self, name: str) -> FluentDatasource: # TODO: Delete this when we remove block style datasource configs key = DataContextVariableKey( resource_name=name, ) datasource = self.get(key) if not isinstance(datasource, FluentDatasource): raise ValueError("Datasource is not a FluentDatasource") # noqa: TRY003, TRY004 # FIXME CoP return datasource @override def set( self, key: Union[DataContextKey, None], value: FluentDatasource, **kwargs, ) -> FluentDatasource: """Create a datasource config in the store using a store_backend-specific key. Args: key: Optional key to use when setting value. value: Datasource set in the store at the key provided or created from the Datsource. **_: kwargs will be ignored but accepted to align with the parent class. Returns: Datasource retrieved from the DatasourceStore. """ if not key: key = self._build_key_from_config(value) return self._persist_datasource(key=key, config=value) def _persist_datasource( self, key: DataContextKey, config: FluentDatasource ) -> FluentDatasource: # Make two separate requests to set and get in order to obtain any additional # values that may have been added to the config by the StoreBackend (i.e. object ids) ref: Optional[Union[bool, GXCloudResourceRef]] = super().set(key=key, value=config) if ref and isinstance(ref, GXCloudResourceRef): key.id = ref.id # type: ignore[attr-defined] # FIXME CoP return_value: FluentDatasource = self.get(key) # type: ignore[assignment] # FIXME CoP if not return_value.name and isinstance(key, DataContextVariableKey): # Setting the name in the config is currently needed to handle adding the name to v2 datasource # noqa: E501 # FIXME CoP # configs and can be refactored (e.g. into `get()`) if not key.resource_name: raise ValueError("Missing resource name") # noqa: TRY003 # FIXME CoP return_value.name = key.resource_name return return_value def _determine_datasource_key(self, name: str) -> DataContextVariableKey: datasource_key = DataContextVariableKey( resource_name=name, ) return datasource_key
DatasourceStore
python
joke2k__faker
faker/proxy.py
{ "start": 488, "end": 10257 }
class ____: """Proxy class capable of supporting multiple locales""" cache_pattern: Pattern = re.compile(r"^_cached_\w*_mapping$") generator_attrs = [ attr for attr in dir(Generator) if not attr.startswith("__") and attr not in ["seed", "seed_instance", "random"] ] def __init__( self, locale: str | Sequence[str] | dict[str, int | float] | None = None, providers: list[str] | None = None, generator: Generator | None = None, includes: list[str] | None = None, use_weighting: bool = True, **config: Any, ) -> None: self._factory_map: OrderedDict[str, Generator | Faker] = OrderedDict() self._weights = None self._unique_proxy = UniqueProxy(self) self._optional_proxy = OptionalProxy(self) if isinstance(locale, str): locales = [locale.replace("-", "_")] # This guarantees a FIFO ordering of elements in `locales` based on the final # locale string while discarding duplicates after processing elif isinstance(locale, (list, tuple, set)): locales = [] for code in locale: if not isinstance(code, str): raise TypeError(f'The locale "{str(code)}" must be a string.') final_locale = code.replace("-", "_") if final_locale not in locales: locales.append(final_locale) elif isinstance(locale, (OrderedDict, dict)): assert all(isinstance(v, (int, float)) for v in locale.values()) odict = OrderedDict() for k, v in locale.items(): key = k.replace("-", "_") odict[key] = v locales = list(odict.keys()) self._weights = list(odict.values()) else: locales = [DEFAULT_LOCALE] if len(locales) == 1: self._factory_map[locales[0]] = Factory.create( locales[0], providers, generator, includes, use_weighting=use_weighting, **config, ) else: for locale in locales: self._factory_map[locale] = Faker( locale, providers, generator, includes, use_weighting=use_weighting, **config, ) self._locales = locales self._factories = list(self._factory_map.values()) def __dir__(self): attributes = set(super().__dir__()) for factory in self.factories: attributes |= {attr for attr in dir(factory) if not attr.startswith("_")} return sorted(attributes) def __getitem__(self, locale: str) -> Faker: if locale.replace("-", "_") in self.locales and len(self.locales) == 1: return self instance = self._factory_map[locale.replace("-", "_")] assert isinstance(instance, Faker) # for mypy return instance def __getattribute__(self, attr: str) -> Any: """ Handles the "attribute resolution" behavior for declared members of this proxy class The class method `seed` cannot be called from an instance. :param attr: attribute name :return: the appropriate attribute """ if attr == "seed": msg = "Calling `.seed()` on instances is deprecated. Use the class method `Faker.seed()` instead." raise TypeError(msg) else: return super().__getattribute__(attr) def __getattr__(self, attr: str) -> Any: """ Handles cache access and proxying behavior :param attr: attribute name :return: the appropriate attribute """ if len(self._factories) == 1: return getattr(self._factories[0], attr) elif attr in self.generator_attrs: msg = "Proxying calls to `%s` is not implemented in multiple locale mode." % attr raise NotImplementedError(msg) elif self.cache_pattern.match(attr): msg = "Cached attribute `%s` does not exist" % attr raise AttributeError(msg) else: factory = self._select_factory(attr) return getattr(factory, attr) def __deepcopy__(self, memodict): cls = self.__class__ result = cls.__new__(cls) result._locales = copy.deepcopy(self._locales) result._factories = copy.deepcopy(self._factories) result._factory_map = copy.deepcopy(self._factory_map) result._weights = copy.deepcopy(self._weights) result._unique_proxy = UniqueProxy(self) result._unique_proxy._seen = {k: {result._unique_proxy._sentinel} for k in self._unique_proxy._seen.keys()} return result def __setstate__(self, state: Any) -> None: self.__dict__.update(state) @property def unique(self) -> UniqueProxy: return self._unique_proxy @property def optional(self) -> OptionalProxy: return self._optional_proxy def _select_factory(self, method_name: str) -> Factory: """ Returns a random factory that supports the provider method :param method_name: Name of provider method :return: A factory that supports the provider method """ factories, weights = self._map_provider_method(method_name) if len(factories) == 0: msg = f"No generator object has attribute {method_name!r}" raise AttributeError(msg) elif len(factories) == 1: return factories[0] if weights: factory = self._select_factory_distribution(factories, weights) else: factory = self._select_factory_choice(factories) return factory def _select_factory_distribution(self, factories, weights): return choices_distribution(factories, weights, random, length=1)[0] def _select_factory_choice(self, factories): return random.choice(factories) def _map_provider_method(self, method_name: str) -> tuple[list[Factory], list[float] | None]: """ Creates a 2-tuple of factories and weights for the given provider method name The first element of the tuple contains a list of compatible factories. The second element of the tuple contains a list of distribution weights. :param method_name: Name of provider method :return: 2-tuple (factories, weights) """ # Return cached mapping if it exists for given method attr = f"_cached_{method_name}_mapping" if hasattr(self, attr): return getattr(self, attr) # Create mapping if it does not exist if self._weights: value = [ (factory, weight) for factory, weight in zip(self.factories, self._weights) if hasattr(factory, method_name) ] factories, weights = zip(*value) mapping = list(factories), list(weights) else: value = [factory for factory in self.factories if hasattr(factory, method_name)] # type: ignore mapping = value, None # type: ignore # Then cache and return results setattr(self, attr, mapping) return mapping @classmethod def seed(cls, seed: SeedType | None = None) -> None: """ Hashables the shared `random.Random` object across all factories :param seed: seed value """ Generator.seed(seed) def seed_instance(self, seed: SeedType | None = None) -> None: """ Creates and seeds a new `random.Random` object for each factory :param seed: seed value """ for factory in self._factories: factory.seed_instance(seed) def seed_locale(self, locale: str, seed: SeedType | None = None) -> None: """ Creates and seeds a new `random.Random` object for the factory of the specified locale :param locale: locale string :param seed: seed value """ self._factory_map[locale.replace("-", "_")].seed_instance(seed) @property def random(self) -> Random: """ Proxies `random` getter calls In single locale mode, this will be proxied to the `random` getter of the only internal `Generator` object. Subclasses will have to implement desired behavior in multiple locale mode. """ if len(self._factories) == 1: return self._factories[0].random else: msg = "Proxying `random` getter calls is not implemented in multiple locale mode." raise NotImplementedError(msg) @random.setter def random(self, value: Random) -> None: """ Proxies `random` setter calls In single locale mode, this will be proxied to the `random` setter of the only internal `Generator` object. Subclasses will have to implement desired behavior in multiple locale mode. """ if len(self._factories) == 1: self._factories[0].random = value else: msg = "Proxying `random` setter calls is not implemented in multiple locale mode." raise NotImplementedError(msg) @property def locales(self) -> list[str]: return list(self._locales) @property def weights(self) -> list[int | float] | None: return self._weights @property def factories(self) -> list[Generator | Faker]: return self._factories def items(self) -> list[tuple[str, Generator | Faker]]: return list(self._factory_map.items())
Faker
python
aio-libs__aiohttp
examples/fake_server.py
{ "start": 247, "end": 1262 }
class ____(AbstractResolver): _LOCAL_HOST = {0: "127.0.0.1", socket.AF_INET: "127.0.0.1", socket.AF_INET6: "::1"} def __init__(self, fakes: dict[str, int]) -> None: """fakes -- dns -> port dict""" self._fakes = fakes self._resolver = DefaultResolver() async def resolve( self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET, ) -> list[ResolveResult]: fake_port = self._fakes.get(host) if fake_port is not None: return [ { "hostname": host, "host": self._LOCAL_HOST[family], "port": fake_port, "family": family, "proto": 0, "flags": socket.AI_NUMERICHOST, } ] else: return await self._resolver.resolve(host, port, family) async def close(self) -> None: await self._resolver.close()
FakeResolver
python
gevent__gevent
src/gevent/backdoor.py
{ "start": 8074, "end": 8674 }
class ____(_BaseFileLike): # Like _StdErr, but for stdin. def readline(self, *a): try: return self.fobj.readline(*a).replace("\r\n", "\n") except UnicodeError: # Typically, under python 3, a ^C on the other end return '' if __name__ == '__main__': if not sys.argv[1:]: print('USAGE: %s PORT [banner]' % sys.argv[0]) else: BackdoorServer(('127.0.0.1', int(sys.argv[1])), banner=(sys.argv[2] if len(sys.argv) > 2 else None), locals={'hello': 'world'}).serve_forever()
_StdIn
python
matplotlib__matplotlib
galleries/examples/units/basic_units.py
{ "start": 1970, "end": 2298 }
class ____(PassThroughProxy): def __init__(self, fn_name, obj): super().__init__(fn_name, obj) self.unit = obj.unit def __call__(self, *args): ret = super().__call__(*args) return (NotImplemented if ret is NotImplemented else TaggedValue(ret, self.unit))
ConvertReturnProxy
python
pallets__quart
src/quart/routing.py
{ "start": 248, "end": 1089 }
class ____(Rule): def __init__( self, string: str, defaults: dict | None = None, subdomain: str | None = None, methods: Iterable[str] | None = None, endpoint: str | None = None, strict_slashes: bool | None = None, merge_slashes: bool | None = None, host: str | None = None, websocket: bool = False, provide_automatic_options: bool = False, ) -> None: super().__init__( string, defaults=defaults, subdomain=subdomain, methods=methods, endpoint=endpoint, strict_slashes=strict_slashes, merge_slashes=merge_slashes, host=host, websocket=websocket, ) self.provide_automatic_options = provide_automatic_options
QuartRule
python
readthedocs__readthedocs.org
readthedocs/projects/forms.py
{ "start": 36082, "end": 37077 }
class ____(forms.ModelForm): """Form for project redirects.""" project = forms.CharField(widget=forms.HiddenInput(), required=False, disabled=True) class Meta: model = Redirect fields = [ "project", "redirect_type", "from_url", "to_url", "http_status", "force", "enabled", "description", ] def __init__(self, *args, **kwargs): self.project = kwargs.pop("project", None) super().__init__(*args, **kwargs) # Remove the nullable option from the form. self.fields["enabled"].widget = forms.CheckboxInput() self.fields["enabled"].empty_value = False # Remove the nullable option from the form. # TODO: remove after migration. self.fields["force"].widget = forms.CheckboxInput() self.fields["force"].empty_value = False def clean_project(self): return self.project
RedirectForm
python
mlflow__mlflow
tests/genai/evaluate/test_evaluation.py
{ "start": 1691, "end": 5897 }
class ____: def predict(self, question: str) -> str: return "I don't know" @scorer def exact_match(outputs, expectations): return outputs == expectations["expected_response"] @scorer def is_concise(outputs, expectations): return len(outputs) <= expectations["max_length"] @scorer def relevance(inputs, outputs): return Feedback( name="relevance", value="yes", rationale="The response is relevant to the question", source=AssessmentSource(source_id="gpt", source_type="LLM_JUDGE"), ) @scorer @mlflow.trace(span_type=SpanType.EVALUATOR) def has_trace(trace): return trace is not None def _validate_assessments(traces): """Validate assessments are added to the traces""" for trace in traces: assert len(trace.info.assessments) == 6, ( f"Expected 6 assessments, got {len(trace.info.assessments)}" f"Assessments: {[a.name for a in trace.info.assessments]}" ) # 2 expectations + 4 feedbacks assessments = {a.name: a for a in trace.info.assessments} a_exact_match = assessments["exact_match"] assert isinstance(a_exact_match, Feedback) assert a_exact_match.trace_id == trace.info.trace_id assert isinstance(a_exact_match.value, bool) assert a_exact_match.source.source_type == AssessmentSourceType.CODE # Scorer name is used as source_id assert a_exact_match.source.source_id == "exact_match" assert a_exact_match.metadata[AssessmentMetadataKey.SOURCE_RUN_ID] is not None a_is_concise = assessments["is_concise"] assert isinstance(a_is_concise, Feedback) assert isinstance(a_is_concise.value, bool) assert a_is_concise.metadata[AssessmentMetadataKey.SOURCE_RUN_ID] is not None a_has_trace = assessments["has_trace"] assert isinstance(a_has_trace, Feedback) assert a_has_trace.value is True assert a_has_trace.metadata[AssessmentMetadataKey.SOURCE_RUN_ID] is not None a_relevance = assessments["relevance"] assert isinstance(a_relevance, Feedback) assert a_relevance.value == "yes" assert a_relevance.source.source_id == "gpt" assert a_relevance.source.source_type == "LLM_JUDGE" assert a_relevance.rationale == "The response is relevant to the question" assert a_relevance.metadata[AssessmentMetadataKey.SOURCE_RUN_ID] is not None a_expected_response = assessments["expected_response"] assert isinstance(a_expected_response, Expectation) assert isinstance(a_expected_response.value, str) assert a_expected_response.source.source_type == AssessmentSourceType.HUMAN assert a_expected_response.source.source_id is not None a_max_length = assessments["max_length"] assert isinstance(a_max_length, Expectation) assert isinstance(a_max_length.value, (int, float)) assert a_max_length.source.source_type == AssessmentSourceType.HUMAN def _validate_eval_result_df(result: EvaluationResult): search_traces_df = mlflow.search_traces(run_id=result.run_id) assert result.result_df is not None assert len(result.result_df) == len(search_traces_df) assert set(result.result_df.columns) >= set(search_traces_df.columns) actual = result.result_df.sort_values(by="trace_id").reset_index(drop=True) expected = search_traces_df.sort_values(by="trace_id").reset_index(drop=True) for i in range(len(actual)): assert actual.iloc[i].trace_id == expected.iloc[i].trace_id assert actual.iloc[i].spans == expected.iloc[i].spans assert actual.iloc[i].assessments == expected.iloc[i].assessments assert actual.iloc[i]["exact_match/value"] is not None assert actual.iloc[i]["is_concise/value"] is not None assert actual.iloc[i]["relevance/value"] is not None assert actual.iloc[i]["has_trace/value"] is not None assert actual.iloc[i]["expected_response/value"] is not None assert actual.iloc[i]["max_length/value"] is not None # backwards compatibility assert len(result.tables["eval_results"]) == len(result.result_df) @dataclass
TestModel
python
getsentry__sentry
tests/sentry/models/test_auditlogentry.py
{ "start": 235, "end": 1024 }
class ____(TestCase): def test_audit_log_entry(self) -> None: AuditLogEntry.objects.create( organization_id=self.organization.id, event=audit_log.get_event_id("TEAM_ADD"), actor=self.user, datetime=timezone.now(), data={"slug": "New Team"}, ) AuditLogEntry.objects.create( organization_id=self.organization.id, event=audit_log.get_event_id("TEAM_REMOVE"), actor=self.user, datetime=timezone.now(), data={"slug": "Old Team"}, ) assert AuditLogEntry.objects.filter(event=audit_log.get_event_id("TEAM_ADD")).exists() assert AuditLogEntry.objects.filter(event=audit_log.get_event_id("TEAM_REMOVE")).exists()
AuditLogEntryTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/asyncio/session.py
{ "start": 60464, "end": 64787 }
class ____( ReversibleProxy[SessionTransaction], StartableContext["AsyncSessionTransaction"], ): """A wrapper for the ORM :class:`_orm.SessionTransaction` object. This object is provided so that a transaction-holding object for the :meth:`_asyncio.AsyncSession.begin` may be returned. The object supports both explicit calls to :meth:`_asyncio.AsyncSessionTransaction.commit` and :meth:`_asyncio.AsyncSessionTransaction.rollback`, as well as use as an async context manager. .. versionadded:: 1.4 """ __slots__ = ("session", "sync_transaction", "nested") session: AsyncSession sync_transaction: Optional[SessionTransaction] def __init__(self, session: AsyncSession, nested: bool = False): self.session = session self.nested = nested self.sync_transaction = None @property def is_active(self) -> bool: return ( self._sync_transaction() is not None and self._sync_transaction().is_active ) def _sync_transaction(self) -> SessionTransaction: if not self.sync_transaction: self._raise_for_not_started() return self.sync_transaction async def rollback(self) -> None: """Roll back this :class:`_asyncio.AsyncTransaction`.""" await greenlet_spawn(self._sync_transaction().rollback) async def commit(self) -> None: """Commit this :class:`_asyncio.AsyncTransaction`.""" await greenlet_spawn(self._sync_transaction().commit) @classmethod def _regenerate_proxy_for_target( # type: ignore[override] cls, target: SessionTransaction, async_session: AsyncSession, **additional_kw: Any, # noqa: U100 ) -> AsyncSessionTransaction: sync_transaction = target nested = target.nested obj = cls.__new__(cls) obj.session = async_session obj.sync_transaction = obj._assign_proxied(sync_transaction) obj.nested = nested return obj async def start( self, is_ctxmanager: bool = False ) -> AsyncSessionTransaction: self.sync_transaction = self._assign_proxied( await greenlet_spawn( self.session.sync_session.begin_nested if self.nested else self.session.sync_session.begin ) ) if is_ctxmanager: self.sync_transaction.__enter__() return self async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None: await greenlet_spawn( self._sync_transaction().__exit__, type_, value, traceback ) def async_object_session(instance: object) -> Optional[AsyncSession]: """Return the :class:`_asyncio.AsyncSession` to which the given instance belongs. This function makes use of the sync-API function :class:`_orm.object_session` to retrieve the :class:`_orm.Session` which refers to the given instance, and from there links it to the original :class:`_asyncio.AsyncSession`. If the :class:`_asyncio.AsyncSession` has been garbage collected, the return value is ``None``. This functionality is also available from the :attr:`_orm.InstanceState.async_session` accessor. :param instance: an ORM mapped instance :return: an :class:`_asyncio.AsyncSession` object, or ``None``. .. versionadded:: 1.4.18 """ session = object_session(instance) if session is not None: return async_session(session) else: return None def async_session(session: Session) -> Optional[AsyncSession]: """Return the :class:`_asyncio.AsyncSession` which is proxying the given :class:`_orm.Session` object, if any. :param session: a :class:`_orm.Session` instance. :return: a :class:`_asyncio.AsyncSession` instance, or ``None``. .. versionadded:: 1.4.18 """ return AsyncSession._retrieve_proxy_for_target(session, regenerate=False) async def close_all_sessions() -> None: """Close all :class:`_asyncio.AsyncSession` sessions. .. versionadded:: 2.0.23 .. seealso:: :func:`.session.close_all_sessions` """ await greenlet_spawn(_sync_close_all_sessions) _instance_state._async_provider = async_session # type: ignore
AsyncSessionTransaction
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/collective_ops_test.py
{ "start": 43493, "end": 48310 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): _setup_context() super().setUp() def testTimeout(self, collective_op, device, communication): timeout = 1.5 tokens = {} for i in range(2): dev = '/{}:{}'.format(device, i) with ops.device(dev): tokens[dev] = create_ordering_token() @def_function.function def run(group_size, reported_group_size=None): group_key = 20 instance_key = 30 tensor = [1., 2., 3., 4.] results = [] if reported_group_size is None: reported_group_size = group_size for i in range(group_size): dev = '/{}:{}'.format(device, i) with ops.device(dev): input_data = constant_op.constant(tensor) result = collective_op( input_data, group_size=reported_group_size, group_key=group_key, instance_key=instance_key, ordering_token=tokens[dev], communication_hint=communication, timeout=timeout) results.append(result) return results run(2, 2) start_time = time.time() with self.assertRaisesRegex(errors.DeadlineExceededError, 'Collective has timed out during execution'): run(1, 2) elapsed = time.time() - start_time self.assertAllGreaterEqual(elapsed, timeout) def testParamResolutionAfterTimeout(self, collective_op, device, communication): dev0 = '/device:%s:0' % device dev1 = '/device:%s:1' % device timeout = 1.5 group_key = 20 instance_key = 30 input_data = constant_op.constant([1., 2., 3., 4.]) tokens = {} for device in [dev0, dev1]: with ops.device(device): tokens[device] = create_ordering_token() # This timeout comes from param solution. with self.assertRaisesRegex( errors.DeadlineExceededError, 'Collective has timed out waiting for other workers'): with ops.device(dev0): collective_op( input_data, group_size=2, group_key=group_key, instance_key=instance_key, ordering_token=tokens[dev0], communication_hint=communication, timeout=timeout) # We launch the second device after the first device times out. This is to # simulate the situation when other workers are slow and the timeout is # short. It should error immediately. with self.assertRaisesRegex( errors.DeadlineExceededError, 'Collective has timed out waiting for other workers'): with ops.device(dev1): collective_op( input_data, group_size=2, group_key=group_key, instance_key=instance_key, ordering_token=tokens[dev1], communication_hint=communication) def testExecutionAfterTimeout(self, collective_op, device, communication): dev0 = '/device:%s:0' % device dev1 = '/device:%s:1' % device timeout = 1.5 group_key = 20 instance_key = 30 input_data = constant_op.constant([1., 2., 3., 4.]) tokens = {} for device in [dev0, dev1]: with ops.device(device): tokens[device] = create_ordering_token() @def_function.function def run(): for device in [dev0, dev1]: with ops.device(device): collective_op( input_data, group_size=2, group_key=group_key, instance_key=instance_key, ordering_token=tokens[device], communication_hint=communication, timeout=timeout) # Run a normal all-reduce to complete param resolution. run() with self.assertRaisesRegex(errors.DeadlineExceededError, 'Collective has timed out during execution'): with ops.device(dev0): collective_op( input_data, group_size=2, group_key=group_key, instance_key=instance_key, ordering_token=tokens[dev0], communication_hint=communication, timeout=timeout) # We launch the second device after the first device times out. This is to # simulate the situation when other workers are slow and the timeout is # short. It should error immediately. with self.assertRaisesRegex(errors.DeadlineExceededError, 'Collective has timed out during execution'): with ops.device(dev1): # No timeout. collective_op( input_data, group_size=2, group_key=group_key, instance_key=instance_key, ordering_token=tokens[dev1], communication_hint=communication)
TimeoutTest
python
python-excel__xlwt
tests/test_mini.py
{ "start": 213, "end": 592 }
class ____(unittest.TestCase): def test_create_mini_xls(self): book = xlwt.Workbook() sheet = book.add_sheet('xlwt was here') book.save(in_tst_output_dir('mini.xls')) self.assertTrue(filecmp.cmp(in_tst_dir('mini.xls'), in_tst_output_dir('mini.xls'), shallow=False))
TestMini
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/app_platform_event.py
{ "start": 714, "end": 777 }
class ____(TypedDict): uuid: str
AppPlatformEventInstallation
python
readthedocs__readthedocs.org
readthedocs/core/mixins.py
{ "start": 915, "end": 2358 }
class ____: """ Explicitly cache or not a view at the CDN level. The cache control header is used to mark the response as public/private, so it can be cached or not. Views that can be cached should always return the same response for all users (anonymous and authenticated users), like when the version attached to the request is public. To explicitly cache a view you can either set the `cache_response` attribute to `True`/`False`, or override the `can_be_cached` method (which defaults to return the `cache_response` attribute). If set to `None` (default), the cache header won't be set, so the default value can be set by our middleware (public for .org and private for .com). We use ``CDN-Cache-Control``, to control caching at the CDN level only. This doesn't affect caching at the browser level (``Cache-Control``). See https://developers.cloudflare.com/cache/about/cdn-cache-control. """ cache_response = None def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) can_be_cached = self.can_be_cached(request) if can_be_cached is not None: if can_be_cached: cache_response(response) else: private_response(response) return response def can_be_cached(self, request): return self.cache_response
CDNCacheControlMixin
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/fixtures/orm.py
{ "start": 5205, "end": 6095 }
class ____: @config.fixture(autouse=True) def _remove_listeners(self): yield orm_events.MapperEvents._clear() orm_events.InstanceEvents._clear() orm_events.SessionEvents._clear() orm_events.InstrumentationEvents._clear() orm_events.QueryEvents._clear() _fixture_sessions = set() def fixture_session(**kw): kw.setdefault("autoflush", True) kw.setdefault("expire_on_commit", True) bind = kw.pop("bind", config.db) sess = orm.Session(bind, **kw) _fixture_sessions.add(sess) return sess def close_all_sessions(): # will close all still-referenced sessions orm.close_all_sessions() _fixture_sessions.clear() def stop_test_class_inside_fixtures(cls): close_all_sessions() orm.clear_mappers() def after_test(): if _fixture_sessions: close_all_sessions()
RemoveORMEventsGlobally
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 9474, "end": 9542 }
class ____(HTTPClientError): status_code = 426
HTTPUpgradeRequired
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-huggingface-api/llama_index/embeddings/huggingface_api/base.py
{ "start": 583, "end": 8153 }
class ____(BaseEmbedding): # type: ignore[misc] """ Wrapper on the Hugging Face's Inference API for embeddings. Overview of the design: - Uses the feature extraction task: https://huggingface.co/tasks/feature-extraction """ pooling: Optional[Pooling] = Field( default=Pooling.CLS, description="Pooling strategy. If None, the model's default pooling is used.", ) query_instruction: Optional[str] = Field( default=None, description="Instruction to prepend during query embedding." ) text_instruction: Optional[str] = Field( default=None, description="Instruction to prepend during text embedding." ) # Corresponds with huggingface_hub.InferenceClient model_name: Optional[str] = Field( default=None, description="Hugging Face model name. If None, the task will be used.", ) token: Union[str, bool, None] = Field( default=None, description=( "Hugging Face token. Will default to the locally saved token. Pass " "token=False if you don’t want to send your token to the server." ), ) timeout: Optional[float] = Field( default=None, description=( "The maximum number of seconds to wait for a response from the server." " Loading a new model in Inference API can take up to several minutes." " Defaults to None, meaning it will loop until the server is available." ), ) headers: Optional[Dict[str, str]] = Field( default=None, description=( "Additional headers to send to the server. By default only the" " authorization and user-agent headers are sent. Values in this dictionary" " will override the default values." ), ) cookies: Optional[Dict[str, str]] = Field( default=None, description="Additional cookies to send to the server." ) task: Optional[str] = Field( default=None, description=( "Optional task to pick Hugging Face's recommended model, used when" " model_name is left as default of None." ), ) _sync_client: "InferenceClient" = PrivateAttr() _async_client: "AsyncInferenceClient" = PrivateAttr() _get_model_info: "Callable[..., ModelInfo]" = PrivateAttr() def _get_inference_client_kwargs(self) -> Dict[str, Any]: """Extract the Hugging Face InferenceClient construction parameters.""" return { "model": self.model_name, "token": self.token, "timeout": self.timeout, "headers": self.headers, "cookies": self.cookies, } def __init__(self, **kwargs: Any) -> None: """ Initialize. Args: kwargs: See the class-level Fields. """ if kwargs.get("model_name") is None: task = kwargs.get("task", "") # NOTE: task being None or empty string leads to ValueError, # which ensures model is present kwargs["model_name"] = InferenceClient.get_recommended_model(task=task) logger.debug( f"Using Hugging Face's recommended model {kwargs['model_name']}" f" given task {task}." ) print(kwargs["model_name"], flush=True) super().__init__(**kwargs) # Populate pydantic Fields self._sync_client = InferenceClient(**self._get_inference_client_kwargs()) self._async_client = AsyncInferenceClient(**self._get_inference_client_kwargs()) self._get_model_info = model_info def validate_supported(self, task: str) -> None: """ Confirm the contained model_name is deployed on the Inference API service. Args: task: Hugging Face task to check within. A list of all tasks can be found here: https://huggingface.co/tasks """ all_models = self._sync_client.list_deployed_models(frameworks="all") try: if self.model_name not in all_models[task]: raise ValueError( "The Inference API service doesn't have the model" f" {self.model_name!r} deployed." ) except KeyError as exc: raise KeyError( f"Input task {task!r} not in possible tasks {list(all_models.keys())}." ) from exc def get_model_info(self, **kwargs: Any) -> "ModelInfo": """Get metadata on the current model from Hugging Face.""" return self._get_model_info(self.model_name, **kwargs) @classmethod def class_name(cls) -> str: return "HuggingFaceInferenceAPIEmbedding" async def _async_embed_single(self, text: str) -> Embedding: embedding = await self._async_client.feature_extraction(text) if len(embedding.shape) == 1: return embedding.tolist() embedding = embedding.squeeze(axis=0) if len(embedding.shape) == 1: # Some models pool internally return embedding.tolist() try: return self.pooling(embedding).tolist() # type: ignore[misc] except TypeError as exc: raise ValueError( f"Pooling is required for {self.model_name} because it returned" " a > 1-D value, please specify pooling as not None." ) from exc async def _async_embed_bulk(self, texts: Sequence[str]) -> List[Embedding]: """ Embed a sequence of text, in parallel and asynchronously. NOTE: this uses an externally created asyncio event loop. """ tasks = [self._async_embed_single(text) for text in texts] return await asyncio.gather(*tasks) def _get_query_embedding(self, query: str) -> Embedding: """ Embed the input query synchronously. NOTE: a new asyncio event loop is created internally for this. """ return asyncio.run(self._aget_query_embedding(query)) def _get_text_embedding(self, text: str) -> Embedding: """ Embed the text query synchronously. NOTE: a new asyncio event loop is created internally for this. """ return asyncio.run(self._aget_text_embedding(text)) def _get_text_embeddings(self, texts: List[str]) -> List[Embedding]: """ Embed the input sequence of text synchronously and in parallel. NOTE: a new asyncio event loop is created internally for this. """ loop = asyncio.new_event_loop() try: tasks = [ loop.create_task(self._aget_text_embedding(text)) for text in texts ] loop.run_until_complete(asyncio.wait(tasks)) finally: loop.close() return [task.result() for task in tasks] async def _aget_query_embedding(self, query: str) -> Embedding: return await self._async_embed_single( text=format_query(query, self.model_name, self.query_instruction) ) async def _aget_text_embedding(self, text: str) -> Embedding: return await self._async_embed_single( text=format_text(text, self.model_name, self.text_instruction) ) async def _aget_text_embeddings(self, texts: List[str]) -> List[Embedding]: return await self._async_embed_bulk( texts=[ format_text(text, self.model_name, self.text_instruction) for text in texts ] )
HuggingFaceInferenceAPIEmbedding
python
spyder-ide__spyder
spyder/utils/environ.py
{ "start": 8189, "end": 9392 }
class ____(CollectionsEditor): """Remote process environment variables dialog.""" def __init__(self, environ=None, parent=None, title=_("Environment variables"), readonly=True): super().__init__(parent) kwargs = dict(title=title, readonly=readonly, icon=ima.icon('environ')) if environ is None: self.setup( {}, **kwargs, loading_img="dependencies", loading_msg=_("Retrieving environment variables...") ) # Get system environment variables future = get_user_environment_variables() future.connect(self._set_data_from_future) else: try: self.setup(environ, **kwargs) except Exception as err: remote_env_dialog_warning(parent, err) @AsyncDispatcher.QtSlot def _set_data_from_future(self, future): try: self.data_copy = envdict2listdict(future.result()) self.widget.set_data(self.data_copy) self.stacked_widget.setCurrentWidget(self.widget) except Exception as err: remote_env_dialog_warning(self.parent(), err)
RemoteEnvDialog
python
openai__gym
tests/test_core.py
{ "start": 145, "end": 386 }
class ____(core.Env): observation_space = spaces.Box(low=0, high=1, shape=(1,)) action_space = spaces.Box(low=0, high=1, shape=(1,)) calls = 0 def __init__(self, arg): self.calls += 1 self.arg = arg
ArgumentEnv
python
kamyu104__LeetCode-Solutions
Python/display-table-of-food-orders-in-a-restaurant.py
{ "start": 66, "end": 672 }
class ____(object): def displayTable(self, orders): """ :type orders: List[List[str]] :rtype: List[List[str]] """ table_count = collections.defaultdict(collections.Counter) for _, table, food in orders: table_count[int(table)][food] += 1 foods = sorted({food for _, _, food in orders}) result = [["Table"]] result[0].extend(foods) for table in sorted(table_count): result.append([str(table)]) result[-1].extend(str(table_count[table][food]) for food in foods) return result
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 928913, "end": 929669 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveReaction""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "reaction", "reaction_groups", "subject") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" reaction = sgqlc.types.Field("Reaction", graphql_name="reaction") """The reaction object.""" reaction_groups = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(ReactionGroup)), graphql_name="reactionGroups") """The reaction groups for the subject.""" subject = sgqlc.types.Field(Reactable, graphql_name="subject") """The reactable subject."""
RemoveReactionPayload
python
kamyu104__LeetCode-Solutions
Python/find-the-closest-palindrome.py
{ "start": 29, "end": 495 }
class ____(object): def nearestPalindromic(self, n): """ :type n: str :rtype: str """ l = len(n) candidates = set((str(10**l + 1), str(10**(l - 1) - 1))) prefix = int(n[:(l + 1)/2]) for i in map(str, (prefix-1, prefix, prefix+1)): candidates.add(i + [i, i[:-1]][l%2][::-1]) candidates.discard(n) return min(candidates, key=lambda x: (abs(int(x) - int(n)), int(x)))
Solution
python
aimacode__aima-python
notebook.py
{ "start": 13087, "end": 17867 }
class ____(Canvas): """Play a 3x3 TicTacToe game on HTML canvas""" def __init__(self, varname, player_1='human', player_2='random', width=300, height=350, cid=None): valid_players = ('human', 'random', 'alpha_beta') if player_1 not in valid_players or player_2 not in valid_players: raise TypeError("Players must be one of {}".format(valid_players)) super().__init__(varname, width, height, cid) self.ttt = TicTacToe() self.state = self.ttt.initial self.turn = 0 self.strokeWidth(5) self.players = (player_1, player_2) self.font("20px Arial") self.draw_board() def mouse_click(self, x, y): player = self.players[self.turn] if self.ttt.terminal_test(self.state): if 0.55 <= x / self.width <= 0.95 and 6 / 7 <= y / self.height <= 6 / 7 + 1 / 8: self.state = self.ttt.initial self.turn = 0 self.draw_board() return if player == 'human': x, y = int(3 * x / self.width) + 1, int(3 * y / (self.height * 6 / 7)) + 1 if (x, y) not in self.ttt.actions(self.state): # Invalid move return move = (x, y) elif player == 'alpha_beta': move = alpha_beta_player(self.ttt, self.state) else: move = random_player(self.ttt, self.state) self.state = self.ttt.result(self.state, move) self.turn ^= 1 self.draw_board() def draw_board(self): self.clear() self.stroke(0, 0, 0) offset = 1 / 20 self.line_n(0 + offset, (1 / 3) * 6 / 7, 1 - offset, (1 / 3) * 6 / 7) self.line_n(0 + offset, (2 / 3) * 6 / 7, 1 - offset, (2 / 3) * 6 / 7) self.line_n(1 / 3, (0 + offset) * 6 / 7, 1 / 3, (1 - offset) * 6 / 7) self.line_n(2 / 3, (0 + offset) * 6 / 7, 2 / 3, (1 - offset) * 6 / 7) board = self.state.board for mark in board: if board[mark] == 'X': self.draw_x(mark) elif board[mark] == 'O': self.draw_o(mark) if self.ttt.terminal_test(self.state): # End game message utility = self.ttt.utility(self.state, self.ttt.to_move(self.ttt.initial)) if utility == 0: self.text_n('Game Draw!', offset, 6 / 7 + offset) else: self.text_n('Player {} wins!'.format("XO"[utility < 0]), offset, 6 / 7 + offset) # Find the 3 and draw a line self.stroke([255, 0][self.turn], [0, 255][self.turn], 0) for i in range(3): if all([(i + 1, j + 1) in self.state.board for j in range(3)]) and \ len({self.state.board[(i + 1, j + 1)] for j in range(3)}) == 1: self.line_n(i / 3 + 1 / 6, offset * 6 / 7, i / 3 + 1 / 6, (1 - offset) * 6 / 7) if all([(j + 1, i + 1) in self.state.board for j in range(3)]) and \ len({self.state.board[(j + 1, i + 1)] for j in range(3)}) == 1: self.line_n(offset, (i / 3 + 1 / 6) * 6 / 7, 1 - offset, (i / 3 + 1 / 6) * 6 / 7) if all([(i + 1, i + 1) in self.state.board for i in range(3)]) and \ len({self.state.board[(i + 1, i + 1)] for i in range(3)}) == 1: self.line_n(offset, offset * 6 / 7, 1 - offset, (1 - offset) * 6 / 7) if all([(i + 1, 3 - i) in self.state.board for i in range(3)]) and \ len({self.state.board[(i + 1, 3 - i)] for i in range(3)}) == 1: self.line_n(offset, (1 - offset) * 6 / 7, 1 - offset, offset * 6 / 7) # restart button self.fill(0, 0, 255) self.rect_n(0.5 + offset, 6 / 7, 0.4, 1 / 8) self.fill(0, 0, 0) self.text_n('Restart', 0.5 + 2 * offset, 13 / 14) else: # Print which player's turn it is self.text_n("Player {}'s move({})".format("XO"[self.turn], self.players[self.turn]), offset, 6 / 7 + offset) self.update() def draw_x(self, position): self.stroke(0, 255, 0) x, y = [i - 1 for i in position] offset = 1 / 15 self.line_n(x / 3 + offset, (y / 3 + offset) * 6 / 7, x / 3 + 1 / 3 - offset, (y / 3 + 1 / 3 - offset) * 6 / 7) self.line_n(x / 3 + 1 / 3 - offset, (y / 3 + offset) * 6 / 7, x / 3 + offset, (y / 3 + 1 / 3 - offset) * 6 / 7) def draw_o(self, position): self.stroke(255, 0, 0) x, y = [i - 1 for i in position] self.arc_n(x / 3 + 1 / 6, (y / 3 + 1 / 6) * 6 / 7, 1 / 9, 0, 360)
Canvas_TicTacToe
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/numeric.py
{ "start": 84, "end": 2098 }
class ____(WidgetParameterItem): """ Subclasses `WidgetParameterItem` to provide the following types: ========================== ============================================================= **Registered Types:** int Displays a :class:`SpinBox <pyqtgraph.SpinBox>` in integer mode. float Displays a :class:`SpinBox <pyqtgraph.SpinBox>`. ========================== ============================================================= """ def makeWidget(self): opts = self.param.opts t = opts['type'] defs = { 'value': 0, 'min': None, 'max': None, 'step': 1.0, 'dec': False, 'siPrefix': False, 'suffix': '', 'decimals': 3, } if t == 'int': defs['int'] = True defs['minStep'] = 1.0 for k in defs: if k in opts: defs[k] = opts[k] if opts.get('limits') is not None: defs['min'], defs['max'] = opts['limits'] w = SpinBox() w.setOpts(**defs) w.sigChanged = w.sigValueChanged w.sigChanging = w.sigValueChanging return w def updateDisplayLabel(self, value=None): if value is None: value = self.widget.lineEdit().text() super().updateDisplayLabel(value) def showEditor(self): super().showEditor() self.widget.selectNumber() # select the numerical portion of the text for quick editing def limitsChanged(self, param, limits): self.widget.setOpts(bounds=limits) def optsChanged(self, param, opts): super().optsChanged(param, opts) sbOpts = {} if 'units' in opts and 'suffix' not in opts: sbOpts['suffix'] = opts['units'] for k, v in opts.items(): if k in self.widget.opts: sbOpts[k] = v self.widget.setOpts(**sbOpts) self.updateDisplayLabel()
NumericParameterItem
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hparams.py
{ "start": 33586, "end": 37168 }
class ____(LightningDataModule): def __init__(self, hparams): super().__init__() self.save_hyperparameters(hparams) def train_dataloader(self, *args, **kwargs) -> DataLoader: return DataLoader(RandomDataset(32, 64), batch_size=32) def _get_mock_logger(tmp_path): mock_logger = mock.MagicMock(name="logger") mock_logger.name = "mock_logger" mock_logger.save_dir = tmp_path mock_logger.version = "0" del mock_logger.__iter__ return mock_logger @pytest.mark.parametrize("model", [SaveHparamsModel({"arg1": 5, "arg2": "abc"}), NoHparamsModel()]) @pytest.mark.parametrize("data", [DataModuleWithHparams({"data_dir": "foo"}), DataModuleWithoutHparams()]) def test_adding_datamodule_hparams(tmp_path, model, data): """Test that hparams from datamodule and model are logged.""" org_model_hparams = copy.deepcopy(model.hparams_initial) org_data_hparams = copy.deepcopy(data.hparams_initial) mock_logger = _get_mock_logger(tmp_path) trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, logger=mock_logger) trainer.fit(model, datamodule=data) # Hparams of model and data were not modified assert org_model_hparams == model.hparams assert org_data_hparams == data.hparams # Merged hparams were logged merged_hparams = copy.deepcopy(org_model_hparams) merged_hparams.update(org_data_hparams) if merged_hparams: mock_logger.log_hyperparams.assert_called_with(merged_hparams) else: mock_logger.log_hyperparams.assert_not_called() def test_no_datamodule_for_hparams(tmp_path): """Test that hparams model are logged if no datamodule is used.""" model = SaveHparamsModel({"arg1": 5, "arg2": "abc"}) org_model_hparams = copy.deepcopy(model.hparams_initial) data = DataModuleWithoutHparams() data.setup("fit") mock_logger = _get_mock_logger(tmp_path) trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, logger=mock_logger) trainer.fit(model, datamodule=data) # Merged hparams were logged mock_logger.log_hyperparams.assert_called_with(org_model_hparams) def test_colliding_hparams(tmp_path): model = SaveHparamsModel({"data_dir": "abc", "arg2": "abc"}) data = DataModuleWithHparams({"data_dir": "foo"}) trainer = Trainer(default_root_dir=tmp_path, max_epochs=1, logger=CSVLogger(tmp_path)) with pytest.raises(RuntimeError, match=r"Error while merging hparams:"): trainer.fit(model, datamodule=data) def test_nn_modules_warning_when_saved_as_hparams(): class TorchModule(torch.nn.Module): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(4, 5) class CustomBoringModelWarn(BoringModel): def __init__(self, encoder, decoder, other_hparam=7): super().__init__() self.save_hyperparameters() with pytest.warns(UserWarning, match="is an instance of `nn.Module` and is already saved"): model = CustomBoringModelWarn(encoder=TorchModule(), decoder=TorchModule()) assert list(model.hparams) == ["encoder", "decoder", "other_hparam"] class CustomBoringModelNoWarn(BoringModel): def __init__(self, encoder, decoder, other_hparam=7): super().__init__() self.save_hyperparameters("other_hparam") with no_warning_call(UserWarning, match="is an instance of `nn.Module` and is already saved"): model = CustomBoringModelNoWarn(encoder=TorchModule(), decoder=TorchModule()) assert list(model.hparams) == ["other_hparam"]
DataModuleWithHparams
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/compute.py
{ "start": 42622, "end": 47581 }
class ____(ComputeEngineBaseOperator): """ Deletes an Instance Template in Google Compute Engine. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ComputeEngineDeleteInstanceTemplateOperator` :param resource_id: Name of the Instance Template. :param project_id: Google Cloud project ID where the Compute Engine Instance exists. If set to None or missing, the default project_id from the Google Cloud connection is used. :param request_id: Unique request_id that you might add to achieve full idempotence (for example when client call times out repeating the request with the same request id will not create a new instance template again) It should be in UUID format as defined in RFC 4122 :param gcp_conn_id: The connection ID used to connect to Google Cloud. Defaults to 'google_cloud_default'. :param api_version: API version used (for example v1 - or beta). Defaults to v1. :param impersonation_chain: Service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param retry: A retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. """ # [START gce_instance_template_delete_fields] template_fields: Sequence[str] = ( "resource_id", "request_id", "project_id", "gcp_conn_id", "api_version", "impersonation_chain", ) # [END gce_instance_template_delete_fields] def __init__( self, *, resource_id: str, request_id: str | None = None, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | None = None, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", api_version: str = "v1", validate_body: bool = True, impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: self.request_id = request_id self.resource_id = resource_id self._field_validator = None # Optional[GcpBodyFieldValidator] self.retry = retry self.timeout = timeout self.metadata = metadata if validate_body: self._field_validator = GcpBodyFieldValidator( GCE_INSTANCE_TEMPLATE_VALIDATION_PATCH_SPECIFICATION, api_version=api_version ) self._field_sanitizer = GcpBodyFieldSanitizer(GCE_INSTANCE_FIELDS_TO_SANITIZE) super().__init__( project_id=project_id, zone="global", resource_id=resource_id, gcp_conn_id=gcp_conn_id, api_version=api_version, impersonation_chain=impersonation_chain, **kwargs, ) def _validate_inputs(self) -> None: super()._validate_inputs() if not self.resource_id: raise AirflowException("The required parameter 'resource_id' is missing.") def execute(self, context: Context) -> None: hook = ComputeEngineHook( gcp_conn_id=self.gcp_conn_id, api_version=self.api_version, impersonation_chain=self.impersonation_chain, ) try: # Checking if specified Instance Template exists and if it does, delete it hook.get_instance_template( resource_id=self.resource_id, project_id=self.project_id, ) self.log.info("Successfully found Instance Template %s", self.resource_id) hook.delete_instance_template( resource_id=self.resource_id, project_id=self.project_id, request_id=self.request_id, ) self.log.info("Successfully deleted Instance template %s", self.resource_id) except exceptions.NotFound as e: # Expecting 404 Error in case if Instance template doesn't exist. if e.code == 404: self.log.error("Instance template %s doesn't exist", self.resource_id) raise e
ComputeEngineDeleteInstanceTemplateOperator
python
conda__conda
conda/plugins/prefix_data_loaders/pypi/pkg_format.py
{ "start": 17103, "end": 41608 }
class ____: """ Object representing the metada of a Python Distribution given by anchor file (or directory) path. This metadata is extracted from a single file. Python distributions might create additional files that complement this metadata information, but that is handled at the python distribution level. Notes ----- - https://packaging.python.org/specifications/core-metadata/ - Metadata 2.1: https://www.python.org/dev/peps/pep-0566/ - Metadata 2.0: https://www.python.org/dev/peps/pep-0426/ (Withdrawn) - Metadata 1.2: https://www.python.org/dev/peps/pep-0345/ - Metadata 1.1: https://www.python.org/dev/peps/pep-0314/ - Metadata 1.0: https://www.python.org/dev/peps/pep-0241/ """ FILE_NAMES = ("METADATA", "PKG-INFO") # Python Packages Metadata 2.1 # ----------------------------------------------------------------------------- SINGLE_USE_KEYS = frozendict( ( ("Metadata-Version", "metadata_version"), ("Name", "name"), ("Version", "version"), # ('Summary', 'summary'), # ('Description', 'description'), # ('Description-Content-Type', 'description_content_type'), # ('Keywords', 'keywords'), # ('Home-page', 'home_page'), # ('Download-URL', 'download_url'), # ('Author', 'author'), # ('Author-email', 'author_email'), # ('Maintainer', 'maintainer'), # ('Maintainer-email', 'maintainer_email'), ("License", "license"), # # Deprecated # ('Obsoleted-By', 'obsoleted_by'), # Note: See 2.0 # ('Private-Version', 'private_version'), # Note: See 2.0 ) ) MULTIPLE_USE_KEYS = frozendict( ( ("Platform", "platform"), ("Supported-Platform", "supported_platform"), # ('Classifier', 'classifier'), ("Requires-Dist", "requires_dist"), ("Requires-External", "requires_external"), ("Requires-Python", "requires_python"), # ('Project-URL', 'project_url'), ("Provides-Extra", "provides_extra"), # ('Provides-Dist', 'provides_dist'), # ('Obsoletes-Dist', 'obsoletes_dist'), # # Deprecated # ('Extension', 'extension'), # Note: See 2.0 # ('Obsoletes', 'obsoletes'), # ('Provides', 'provides'), ("Requires", "requires"), # ('Setup-Requires-Dist', 'setup_requires_dist'), # Note: See 2.0 ) ) def __init__(self, path): metadata_path = self._process_path(path, self.FILE_NAMES) self._path = path self._data = self._read_metadata(metadata_path) @staticmethod def _process_path(path, metadata_filenames): """Find metadata file inside dist-info folder, or check direct file.""" metadata_path = None if path: if isdir(path): for fname in metadata_filenames: fpath = join(path, fname) if isfile(fpath): metadata_path = fpath break elif isfile(path): # '<pkg>.egg-info' file contains metadata directly filenames = [".egg-info"] if metadata_filenames: filenames.extend(metadata_filenames) if not any(path.endswith(filename) for filename in filenames): raise RuntimeError("Mismatched paths in dist-info folder") metadata_path = path else: # `path` does not exist warnings.warn("Metadata path not found", MetadataWarning) else: warnings.warn("Metadata path not found", MetadataWarning) return metadata_path @classmethod def _message_to_dict(cls, message): """ Convert the RFC-822 headers data into a dictionary. `message` is an email.parser.Message instance. The canonical method to transform metadata fields into such a data structure is as follows: - The original key-value format should be read with email.parser.HeaderParser - All transformed keys should be reduced to lower case. Hyphens should be replaced with underscores, but otherwise should retain all other characters - The transformed value for any field marked with "(Multiple-use") should be a single list containing all the original values for the given key - The Keywords field should be converted to a list by splitting the original value on whitespace characters - The message body, if present, should be set to the value of the description key. - The result should be stored as a string-keyed dictionary. """ new_data = {} if message: for key, value in message.items(): if key in cls.MULTIPLE_USE_KEYS: new_key = cls.MULTIPLE_USE_KEYS[key] if new_key not in new_data: new_data[new_key] = [value] else: new_data[new_key].append(value) elif key in cls.SINGLE_USE_KEYS: new_key = cls.SINGLE_USE_KEYS[key] new_data[new_key] = value # TODO: Handle license later on for convenience return new_data @classmethod def _read_metadata(cls, fpath): """Read the original format which is stored as RFC-822 headers.""" data = {} if fpath and isfile(fpath): parser = HeaderParser() # FIXME: Is this a correct assumption for the encoding? # This was needed due to some errors on windows with open_utf8(fpath) as fp: data = parser.parse(fp) return cls._message_to_dict(data) def _get_multiple_data(self, keys): """ Helper method to get multiple data values by keys. Keys is an iterable including the preferred key in order, to include values of key that might have been replaced (deprecated), for example keys can be ['requires_dist', 'requires'], where the key 'requires' is deprecated and replaced by 'requires_dist'. """ data = [] if self._data: for key in keys: raw_data = self._data.get(key, []) for req in raw_data: data.append(req.strip()) if data: break return frozenset(data) def get_dist_requirements(self): """ Changed in version 2.1: The field format specification was relaxed to accept the syntax used by popular publishing tools. Each entry contains a string naming some other distutils project required by this distribution. The format of a requirement string contains from one to four parts: - A project name, in the same format as the Name: field. The only mandatory part. - A comma-separated list of ‘extra’ names. These are defined by the required project, referring to specific features which may need extra dependencies. - A version specifier. Tools parsing the format should accept optional parentheses around this, but tools generating it should not use parentheses. - An environment marker after a semicolon. This means that the requirement is only needed in the specified conditions. This field may be followed by an environment marker after a semicolon. Example ------- frozenset(['pkginfo', 'PasteDeploy', 'zope.interface (>3.5.0)', 'pywin32 >1.0; sys_platform == "win32"']) Return 'Requires' if 'Requires-Dist' is empty. """ return self._get_multiple_data(["requires_dist", "requires"]) def get_python_requirements(self): """ New in version 1.2. This field specifies the Python version(s) that the distribution is guaranteed to be compatible with. Installation tools may look at this when picking which version of a project to install. The value must be in the format specified in Version specifiers. This field may be followed by an environment marker after a semicolon. Example ------- frozenset(['>=3', '>2.6,!=3.0.*,!=3.1.*', '~=2.6', '>=3; sys_platform == "win32"']) """ return self._get_multiple_data(["requires_python"]) def get_external_requirements(self): """ Changed in version 2.1: The field format specification was relaxed to accept the syntax used by popular publishing tools. Each entry contains a string describing some dependency in the system that the distribution is to be used. This field is intended to serve as a hint to downstream project maintainers, and has no semantics which are meaningful to the distutils distribution. The format of a requirement string is a name of an external dependency, optionally followed by a version declaration within parentheses. This field may be followed by an environment marker after a semicolon. Because they refer to non-Python software releases, version numbers for this field are not required to conform to the format specified in PEP 440: they should correspond to the version scheme used by the external dependency. Notice that there’s is no particular rule on the strings to be used! Example ------- frozenset(['C', 'libpng (>=1.5)', 'make; sys_platform != "win32"']) """ return self._get_multiple_data(["requires_external"]) def get_extra_provides(self): """ New in version 2.1. A string containing the name of an optional feature. Must be a valid Python identifier. May be used to make a dependency conditional on hether the optional feature has been requested. Example ------- frozenset(['pdf', 'doc', 'test']) """ return self._get_multiple_data(["provides_extra"]) def get_dist_provides(self): """ New in version 1.2. Changed in version 2.1: The field format specification was relaxed to accept the syntax used by popular publishing tools. Each entry contains a string naming a Distutils project which is contained within this distribution. This field must include the project identified in the Name field, followed by the version : Name (Version). A distribution may provide additional names, e.g. to indicate that multiple projects have been bundled together. For instance, source distributions of the ZODB project have historically included the transaction project, which is now available as a separate distribution. Installing such a source distribution satisfies requirements for both ZODB and transaction. A distribution may also provide a “virtual” project name, which does not correspond to any separately-distributed project: such a name might be used to indicate an abstract capability which could be supplied by one of multiple projects. E.g., multiple projects might supply RDBMS bindings for use by a given ORM: each project might declare that it provides ORM-bindings, allowing other projects to depend only on having at most one of them installed. A version declaration may be supplied and must follow the rules described in Version specifiers. The distribution’s version number will be implied if none is specified. This field may be followed by an environment marker after a semicolon. Return `Provides` in case `Provides-Dist` is empty. """ return self._get_multiple_data(["provides_dist", "provides"]) def get_dist_obsolete(self): """ New in version 1.2. Changed in version 2.1: The field format specification was relaxed to accept the syntax used by popular publishing tools. Each entry contains a string describing a distutils project’s distribution which this distribution renders obsolete, meaning that the two projects should not be installed at the same time. Version declarations can be supplied. Version numbers must be in the format specified in Version specifiers [1]. The most common use of this field will be in case a project name changes, e.g. Gorgon 2.3 gets subsumed into Torqued Python 1.0. When you install Torqued Python, the Gorgon distribution should be removed. This field may be followed by an environment marker after a semicolon. Return `Obsoletes` in case `Obsoletes-Dist` is empty. Example ------- frozenset(['Gorgon', "OtherProject (<3.0) ; python_version == '2.7'"]) Notes ----- - [1] https://packaging.python.org/specifications/version-specifiers/ """ return self._get_multiple_data(["obsoletes_dist", "obsoletes"]) def get_classifiers(self): """ Classifiers are described in PEP 301, and the Python Package Index publishes a dynamic list of currently defined classifiers. This field may be followed by an environment marker after a semicolon. Example ------- frozenset(['Development Status :: 4 - Beta', "Environment :: Console (Text Based) ; os_name == "posix"]) """ return self._get_multiple_data(["classifier"]) @property def name(self): return self._data.get("name") # TODO: Check for existence? @property def version(self): return self._data.get("version") # TODO: Check for existence? # Helper functions # ----------------------------------------------------------------------------- def norm_package_name(name): return name.replace(".", "-").replace("_", "-").lower() if name else "" def pypi_name_to_conda_name(pypi_name): return PYPI_TO_CONDA.get(pypi_name, pypi_name) if pypi_name else "" def norm_package_version(version): """Normalize a version by removing extra spaces and parentheses.""" if version: version = ",".join(v.strip() for v in version.split(",")).strip() if version.startswith("(") and version.endswith(")"): version = version[1:-1] version = "".join(v for v in version if v.strip()) else: version = "" return version def split_spec(spec, sep): """Split a spec by separator and return stripped start and end parts.""" parts = spec.rsplit(sep, 1) spec_start = parts[0].strip() spec_end = "" if len(parts) == 2: spec_end = parts[-1].strip() return spec_start, spec_end def parse_specification(spec): """ Parse a requirement from a python distribution metadata and return a namedtuple with name, extras, constraints, marker and url components. This method does not enforce strict specifications but extracts the information which is assumed to be *correct*. As such no errors are raised. Example ------- PySpec(name='requests', extras=['security'], constraints='>=3.3.0', marker='foo >= 2.7 or bar == 1', url='']) """ name, extras, const = spec, [], "" # Remove excess whitespace spec = " ".join(p for p in spec.split(" ") if p).strip() # Extract marker (Assumes that there can only be one ';' inside the spec) spec, marker = split_spec(spec, ";") # Extract url (Assumes that there can only be one '@' inside the spec) spec, url = split_spec(spec, "@") # Find name, extras and constraints r = PARTIAL_PYPI_SPEC_PATTERN.match(spec) if r: # Normalize name name = r.group("name") name = norm_package_name(name) # TODO: Do we want this or not? # Clean extras extras = r.group("extras") extras = [e.strip() for e in extras.split(",") if e] if extras else [] # Clean constraints const = r.group("constraints") const = "".join(c for c in const.split(" ") if c).strip() if const.startswith("(") and const.endswith(")"): # Remove parens const = const[1:-1] const = const.replace("-", ".") return PySpec(name=name, extras=extras, constraints=const, marker=marker, url=url) def get_site_packages_anchor_files(site_packages_path, site_packages_dir): """Get all the anchor files for the site packages directory.""" site_packages_anchor_files = set() for entry in scandir(site_packages_path): fname = entry.name anchor_file = None if fname.endswith(".dist-info"): anchor_file = "{}/{}/{}".format(site_packages_dir, fname, "RECORD") elif fname.endswith(".egg-info"): if isfile(join(site_packages_path, fname)): anchor_file = f"{site_packages_dir}/{fname}" else: anchor_file = "{}/{}/{}".format(site_packages_dir, fname, "PKG-INFO") elif fname.endswith(".egg"): if isdir(join(site_packages_path, fname)): anchor_file = "{}/{}/{}/{}".format( site_packages_dir, fname, "EGG-INFO", "PKG-INFO" ) # FIXME: If it is a .egg file, we need to unzip the content to be # able. Do this once and leave the directory, and remove the egg # (which is a zip file in disguise?) elif fname.endswith(".egg-link"): anchor_file = f"{site_packages_dir}/{fname}" elif fname.endswith(".pth"): continue else: continue if anchor_file: site_packages_anchor_files.add(anchor_file) return site_packages_anchor_files def get_dist_file_from_egg_link(egg_link_file, prefix_path): """Return the egg info file path following an egg link.""" egg_info_full_path = None egg_link_path = join(prefix_path, win_path_ok(egg_link_file)) try: with open_utf8(egg_link_path) as fh: # See: https://setuptools.readthedocs.io/en/latest/formats.html#egg-links # "...Each egg-link file should contain a single file or directory name # with no newlines..." egg_link_contents = fh.readlines()[0].strip() except UnicodeDecodeError: from locale import getpreferredencoding with open_utf8(egg_link_path, encoding=getpreferredencoding()) as fh: egg_link_contents = fh.readlines()[0].strip() if lexists(egg_link_contents): egg_info_fnames = tuple( name for name in (entry.name for entry in scandir(egg_link_contents)) if name[-9:] == ".egg-info" ) else: egg_info_fnames = () if egg_info_fnames: if len(egg_info_fnames) != 1: raise CondaError( f"Expected exactly one `egg-info` directory in '{egg_link_contents}', via egg-link '{egg_link_file}'." f" Instead found: {egg_info_fnames}. These are often left over from " "legacy operations that did not clean up correctly. Please " "remove all but one of these." ) egg_info_full_path = join(egg_link_contents, egg_info_fnames[0]) if isdir(egg_info_full_path): egg_info_full_path = join(egg_info_full_path, "PKG-INFO") if egg_info_full_path is None: raise OSError(ENOENT, strerror(ENOENT), egg_link_contents) return egg_info_full_path # See: https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/util.py?at=default&fileviewer=file-view-default # ------------------------------------------------------------------------------------------------ def parse_marker(marker_string): """ Parse marker string and return a dictionary containing a marker expression. The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in the expression grammar, or strings. A string contained in quotes is to be interpreted as a literal string, and a string not contained in quotes is a variable (such as os_name). """ def marker_var(remaining): # either identifier, or literal string m = IDENTIFIER.match(remaining) if m: result = m.groups()[0] remaining = remaining[m.end() :] elif not remaining: raise SyntaxError("unexpected end of input") else: q = remaining[0] if q not in "'\"": raise SyntaxError(f"invalid expression: {remaining}") oq = "'\"".replace(q, "") remaining = remaining[1:] parts = [q] while remaining: # either a string chunk, or oq, or q to terminate if remaining[0] == q: break elif remaining[0] == oq: parts.append(oq) remaining = remaining[1:] else: m = STRING_CHUNK.match(remaining) if not m: raise SyntaxError(f"error in string literal: {remaining}") parts.append(m.groups()[0]) remaining = remaining[m.end() :] else: s = "".join(parts) raise SyntaxError(f"unterminated string: {s}") parts.append(q) result = "".join(parts) remaining = remaining[1:].lstrip() # skip past closing quote return result, remaining def marker_expr(remaining): if remaining and remaining[0] == "(": result, remaining = marker(remaining[1:].lstrip()) if remaining[0] != ")": raise SyntaxError(f"unterminated parenthesis: {remaining}") remaining = remaining[1:].lstrip() else: lhs, remaining = marker_var(remaining) while remaining: m = MARKER_OP.match(remaining) if not m: break op = m.groups()[0] remaining = remaining[m.end() :] rhs, remaining = marker_var(remaining) lhs = {"op": op, "lhs": lhs, "rhs": rhs} result = lhs return result, remaining def marker_and(remaining): lhs, remaining = marker_expr(remaining) while remaining: m = AND.match(remaining) if not m: break remaining = remaining[m.end() :] rhs, remaining = marker_expr(remaining) lhs = {"op": "and", "lhs": lhs, "rhs": rhs} return lhs, remaining def marker(remaining): lhs, remaining = marker_and(remaining) while remaining: m = OR.match(remaining) if not m: break remaining = remaining[m.end() :] rhs, remaining = marker_and(remaining) lhs = {"op": "or", "lhs": lhs, "rhs": rhs} return lhs, remaining return marker(marker_string) # See: # https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/util.py?at=default&fileviewer=file-view-default # https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/markers.py?at=default&fileviewer=file-view-default # ------------------------------------------------------------------------------------------------ # # Requirement parsing code as per PEP 508 # IDENTIFIER = re.compile(r"^([\w\.-]+)\s*") VERSION_IDENTIFIER = re.compile(r"^([\w\.*+-]+)\s*") COMPARE_OP = re.compile(r"^(<=?|>=?|={2,3}|[~!]=)\s*") MARKER_OP = re.compile(r"^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*") OR = re.compile(r"^or\b\s*") AND = re.compile(r"^and\b\s*") NON_SPACE = re.compile(r"(\S+)\s*") STRING_CHUNK = re.compile(r"([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)") def _is_literal(o): if not isinstance(o, str) or not o: return False return o[0] in "'\""
PythonDistributionMetadata
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py
{ "start": 2307, "end": 8115 }
class ____(graphene.ObjectType): rule = graphene.NonNull(GrapheneAutoMaterializeRule) ruleEvaluations = non_null_list(GrapheneAutoMaterializeRuleEvaluation) class Meta: name = "AutoMaterializeRuleWithRuleEvaluations" def __init__( self, rule: GrapheneAutoMaterializeRule, ruleEvaluations, ): super().__init__( rule=rule, ruleEvaluations=ruleEvaluations, ) def create_graphene_auto_materialize_rule_evaluation( asset_subset_with_metadata: AssetSubsetWithMetadata, ) -> Optional[GrapheneAutoMaterializeRuleEvaluation]: if not asset_subset_with_metadata.subset.is_partitioned: partition_keys_or_error = None else: partition_keys_or_error = GraphenePartitionKeys( partitionKeys=asset_subset_with_metadata.subset.subset_value.get_partition_keys() ) metadata = asset_subset_with_metadata.metadata if "text" in metadata.keys() and isinstance(metadata["text"], str): rule_evaluation_data = GrapheneTextRuleEvaluationData(text=metadata["text"]) elif any(key.startswith("updated_parent") for key in metadata.keys()): updatedAssetKeys = [ value.asset_key for key, value in sorted(metadata.items()) if key.startswith("updated_parent") and isinstance(value, DagsterAssetMetadataValue) ] willUpdateAssetKeys = [ value.asset_key for key, value in sorted(metadata.items()) if key.startswith("will_update_parent") and isinstance(value, DagsterAssetMetadataValue) ] rule_evaluation_data = GrapheneParentMaterializedRuleEvaluationData( updatedAssetKeys=updatedAssetKeys, willUpdateAssetKeys=willUpdateAssetKeys ) elif any(key.startswith("waiting_on_ancestor") for key in metadata.keys()): waitingOnAssetKeys = [ value.asset_key for key, value in sorted(metadata.items()) if key.startswith("waiting_on_ancestor") and isinstance(value, DagsterAssetMetadataValue) ] rule_evaluation_data = GrapheneWaitingOnKeysRuleEvaluationData( waitingOnAssetKeys=waitingOnAssetKeys ) else: rule_evaluation_data = None return GrapheneAutoMaterializeRuleEvaluation( partitionKeysOrError=partition_keys_or_error, evaluationData=rule_evaluation_data ) def _create_rules_with_rule_evaluations_for_decision_type( evaluation: AutomationConditionEvaluation, decision_type: AutoMaterializeDecisionType ) -> tuple[ Sequence[GrapheneAutoMaterializeRule], Sequence[GrapheneAutoMaterializeRuleWithRuleEvaluations] ]: rules = [] rules_with_rule_evaluations = [] leaf_evaluations = evaluation.child_evaluations for le in leaf_evaluations: snapshot = le.condition_snapshot if snapshot.class_name != RuleCondition.__name__: continue rule = GrapheneAutoMaterializeRule(snapshot.description, decision_type) rules.append(rule) if le.subsets_with_metadata: rules_with_rule_evaluations.append( GrapheneAutoMaterializeRuleWithRuleEvaluations( rule=rule, ruleEvaluations=[ create_graphene_auto_materialize_rule_evaluation(sswm) for sswm in le.subsets_with_metadata ], ) ) elif le.true_subset.size > 0: rules_with_rule_evaluations.append( GrapheneAutoMaterializeRuleWithRuleEvaluations( rule=rule, ruleEvaluations=[ GrapheneAutoMaterializeRuleEvaluation( partitionKeysOrError=GraphenePartitionKeys( partitionKeys=le.true_subset.subset_value.get_partition_keys() ) if le.true_subset.is_partitioned else None, evaluationData=None, ) ], ) ) return rules, rules_with_rule_evaluations def create_graphene_auto_materialize_rules_with_rule_evaluations( evaluation: AutomationConditionEvaluation, ) -> tuple[ Sequence[GrapheneAutoMaterializeRule], Sequence[GrapheneAutoMaterializeRuleWithRuleEvaluations] ]: rules, rules_with_rule_evaluations = [], [] if len(evaluation.child_evaluations) > 0: materialize_evaluation = evaluation.child_evaluations[0] rs, rwres = _create_rules_with_rule_evaluations_for_decision_type( materialize_evaluation, AutoMaterializeDecisionType.MATERIALIZE ) rules.extend(rs) rules_with_rule_evaluations.extend(rwres) if ( len(evaluation.child_evaluations) > 1 and len(evaluation.child_evaluations[1].child_evaluations) == 1 ): skip_evaluation = evaluation.child_evaluations[1].child_evaluations[0] rs, rwres = _create_rules_with_rule_evaluations_for_decision_type( skip_evaluation, AutoMaterializeDecisionType.SKIP ) rules.extend(rs) rules_with_rule_evaluations.extend(rwres) if ( len(evaluation.child_evaluations) > 2 and len(evaluation.child_evaluations[2].child_evaluations) == 1 ): discard_evaluation = evaluation.child_evaluations[2] rs, rwres = _create_rules_with_rule_evaluations_for_decision_type( discard_evaluation, AutoMaterializeDecisionType.DISCARD ) rules.extend(rs) rules_with_rule_evaluations.extend(rwres) return rules, rules_with_rule_evaluations
GrapheneAutoMaterializeRuleWithRuleEvaluations
python
Lightning-AI__lightning
src/lightning/fabric/strategies/strategy.py
{ "start": 16359, "end": 17089 }
class ____(ABC): """Interface for any :class:`Strategy` that wants to offer a functionality to enable or disable gradient synchronization during/after back-propagation. The most common use-case is gradient accumulation. If a :class:`Strategy` implements this interface, the user can implement their gradient accumulation loop very efficiently by disabling redundant gradient synchronization. """ @abstractmethod def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: """Blocks the synchronization of gradients during the backward pass. This is a context manager. It is only effective if it wraps a call to `.backward()`. """
_BackwardSyncControl
python
langchain-ai__langchain
libs/core/langchain_core/messages/system.py
{ "start": 198, "end": 1728 }
class ____(BaseMessage): """Message for priming AI behavior. The system message is usually passed in as the first of a sequence of input messages. Example: ```python from langchain_core.messages import HumanMessage, SystemMessage messages = [ SystemMessage(content="You are a helpful assistant! Your name is Bob."), HumanMessage(content="What is your name?"), ] # Define a chat model and invoke it with the messages print(model.invoke(messages)) ``` """ type: Literal["system"] = "system" """The type of the message (used for serialization).""" @overload def __init__( self, content: str | list[str | dict], **kwargs: Any, ) -> None: ... @overload def __init__( self, content: str | list[str | dict] | None = None, content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: ... def __init__( self, content: str | list[str | dict] | None = None, content_blocks: list[types.ContentBlock] | None = None, **kwargs: Any, ) -> None: """Specify `content` as positional arg or `content_blocks` for typing.""" if content_blocks is not None: super().__init__( content=cast("str | list[str | dict]", content_blocks), **kwargs, ) else: super().__init__(content=content, **kwargs)
SystemMessage
python
django__django
tests/raw_query/tests.py
{ "start": 410, "end": 16751 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create( first_name="Joe", last_name="Smith", dob=date(1950, 9, 20) ) cls.a2 = Author.objects.create( first_name="Jill", last_name="Doe", dob=date(1920, 4, 2) ) cls.a3 = Author.objects.create( first_name="Bob", last_name="Smith", dob=date(1986, 1, 25) ) cls.a4 = Author.objects.create( first_name="Bill", last_name="Jones", dob=date(1932, 5, 10) ) cls.b1 = Book.objects.create( title="The awesome book", author=cls.a1, paperback=False, opening_line=( "It was a bright cold day in April and the clocks were striking " "thirteen." ), ) cls.b2 = Book.objects.create( title="The horrible book", author=cls.a1, paperback=True, opening_line=( "On an evening in the latter part of May a middle-aged man " "was walking homeward from Shaston to the village of Marlott, " "in the adjoining Vale of Blakemore, or Blackmoor." ), ) cls.b3 = Book.objects.create( title="Another awesome book", author=cls.a1, paperback=False, opening_line="A squat gray building of only thirty-four stories.", ) cls.b4 = Book.objects.create( title="Some other book", author=cls.a3, paperback=True, opening_line="It was the day my grandmother exploded.", ) cls.c1 = Coffee.objects.create(brand="dunkin doughnuts") cls.c2 = Coffee.objects.create(brand="starbucks") cls.r1 = Reviewer.objects.create() cls.r2 = Reviewer.objects.create() cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4) def assertSuccessfulRawQuery( self, model, query, expected_results, expected_annotations=(), params=[], translations=None, ): """ Execute the passed query against the passed model and check the output """ results = list( model.objects.raw(query, params=params, translations=translations) ) self.assertProcessed(model, results, expected_results, expected_annotations) self.assertAnnotations(results, expected_annotations) def assertProcessed(self, model, results, orig, expected_annotations=()): """ Compare the results of a raw query against expected results """ self.assertEqual(len(results), len(orig)) for index, item in enumerate(results): orig_item = orig[index] for annotation in expected_annotations: setattr(orig_item, *annotation) for field in model._meta.fields: # All values on the model are equal self.assertEqual( getattr(item, field.attname), getattr(orig_item, field.attname) ) # This includes checking that they are the same type self.assertEqual( type(getattr(item, field.attname)), type(getattr(orig_item, field.attname)), ) def assertNoAnnotations(self, results): """ The results of a raw query contain no annotations """ self.assertAnnotations(results, ()) def assertAnnotations(self, results, expected_annotations): """ The passed raw query results contain the expected annotations """ if expected_annotations: for index, result in enumerate(results): annotation, value = expected_annotations[index] self.assertTrue(hasattr(result, annotation)) self.assertEqual(getattr(result, annotation), value) def test_rawqueryset_repr(self): queryset = RawQuerySet(raw_query="SELECT * FROM raw_query_author") self.assertEqual( repr(queryset), "<RawQuerySet: SELECT * FROM raw_query_author>" ) self.assertEqual( repr(queryset.query), "<RawQuery: SELECT * FROM raw_query_author>" ) def test_simple_raw_query(self): """ Basic test of raw query with a simple database query """ query = "SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_raw_query_lazy(self): """ Raw queries are lazy: they aren't actually executed until they're iterated over. """ q = Author.objects.raw("SELECT * FROM raw_query_author") self.assertIsNone(q.query.cursor) list(q) self.assertIsNotNone(q.query.cursor) def test_FK_raw_query(self): """ Test of a simple raw query against a model containing a foreign key """ query = "SELECT * FROM raw_query_book" books = Book.objects.all() self.assertSuccessfulRawQuery(Book, query, books) def test_fk_fetch_mode_peers(self): query = "SELECT * FROM raw_query_book" books = list(Book.objects.fetch_mode(FETCH_PEERS).raw(query)) with self.assertNumQueries(1): books[0].author books[1].author def test_fk_fetch_mode_raise(self): query = "SELECT * FROM raw_query_book" books = list(Book.objects.fetch_mode(RAISE).raw(query)) msg = "Fetching of Book.author blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: books[0].author self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) def test_db_column_handler(self): """ Test of a simple raw query against a model containing a field with db_column defined. """ query = "SELECT * FROM raw_query_coffee" coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees) def test_pk_with_mixed_case_db_column(self): """ A raw query with a model that has a pk db_column with mixed case. """ query = "SELECT * FROM raw_query_mixedcaseidcolumn" queryset = MixedCaseIDColumn.objects.all() self.assertSuccessfulRawQuery(MixedCaseIDColumn, query, queryset) def test_order_handler(self): """Raw query tolerates columns being returned in any order.""" selects = ( ("dob, last_name, first_name, id"), ("last_name, dob, first_name, id"), ("first_name, last_name, dob, id"), ) for select in selects: query = "SELECT %s FROM raw_query_author" % select authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_translations(self): """ Test of raw query's optional ability to translate unexpected result column names to specific model fields """ query = ( "SELECT first_name AS first, last_name AS last, dob, id " "FROM raw_query_author" ) translations = {"first": "first_name", "last": "last_name"} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def test_params(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %s" author = Author.objects.all()[2] params = [author.first_name] qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) def test_params_none(self): query = "SELECT * FROM raw_query_author WHERE first_name like 'J%'" qset = Author.objects.raw(query, params=None) self.assertEqual(len(qset), 2) def test_escaped_percent(self): query = "SELECT * FROM raw_query_author WHERE first_name like 'J%%'" qset = Author.objects.raw(query) self.assertEqual(len(qset), 2) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_pyformat_params(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s" author = Author.objects.all()[2] params = {"first": author.first_name} qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) def test_query_representation(self): """ Test representation of raw query with parameters """ query = "SELECT * FROM raw_query_author WHERE last_name = %(last)s" qset = Author.objects.raw(query, {"last": "foo"}) self.assertEqual( repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>", ) self.assertEqual( repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>", ) query = "SELECT * FROM raw_query_author WHERE last_name = %s" qset = Author.objects.raw(query, {"foo"}) self.assertEqual( repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>", ) self.assertEqual( repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>", ) def test_many_to_many(self): """ Test of a simple raw query against a model containing a m2m field """ query = "SELECT * FROM raw_query_reviewer" reviewers = Reviewer.objects.all() self.assertSuccessfulRawQuery(Reviewer, query, reviewers) def test_extra_conversions(self): """Extra translations are ignored.""" query = "SELECT * FROM raw_query_author" translations = {"something": "else"} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def test_missing_fields(self): query = "SELECT id, first_name, dob FROM raw_query_author" for author in Author.objects.raw(query): self.assertIsNotNone(author.first_name) # last_name isn't given, but it will be retrieved on demand self.assertIsNotNone(author.last_name) def test_missing_fields_without_PK(self): query = "SELECT first_name, dob FROM raw_query_author" msg = "Raw query must include the primary key" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Author.objects.raw(query)) def test_missing_fields_fetch_mode_peers(self): query = "SELECT id, first_name, dob FROM raw_query_author" authors = list(Author.objects.fetch_mode(FETCH_PEERS).raw(query)) with self.assertNumQueries(1): authors[0].last_name authors[1].last_name def test_missing_fields_fetch_mode_raise(self): query = "SELECT id, first_name, dob FROM raw_query_author" authors = list(Author.objects.fetch_mode(RAISE).raw(query)) msg = "Fetching of Author.last_name blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: authors[0].last_name self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) self.assertTrue(cm.exception.__suppress_context__) def test_annotations(self): query = ( "SELECT a.*, count(b.id) as book_count " "FROM raw_query_author a " "LEFT JOIN raw_query_book b ON a.id = b.author_id " "GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" ) expected_annotations = ( ("book_count", 3), ("book_count", 0), ("book_count", 1), ("book_count", 0), ) authors = Author.objects.order_by("pk") self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations) def test_white_space_query(self): query = " SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_multiple_iterations(self): query = "SELECT * FROM raw_query_author" normal_authors = Author.objects.all() raw_authors = Author.objects.raw(query) # First Iteration first_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) first_iterations += 1 # Second Iteration second_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) second_iterations += 1 self.assertEqual(first_iterations, second_iterations) def test_get_item(self): # Indexing on RawQuerySets query = "SELECT * FROM raw_query_author ORDER BY id ASC" third_author = Author.objects.raw(query)[2] self.assertEqual(third_author.first_name, "Bob") first_two = Author.objects.raw(query)[0:2] self.assertEqual(len(first_two), 2) with self.assertRaises(TypeError): Author.objects.raw(query)["test"] def test_inheritance(self): f = FriendlyAuthor.objects.create( first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28) ) query = "SELECT * FROM raw_query_friendlyauthor" self.assertEqual([o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]) def test_query_count(self): self.assertNumQueries( 1, list, Author.objects.raw("SELECT * FROM raw_query_author") ) def test_subquery_in_raw_sql(self): list( Book.objects.raw( "SELECT id FROM " "(SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq" ) ) def test_db_column_name_is_used_in_raw_query(self): """ Regression test that ensures the `column` attribute on the field is used to generate the list of fields included in the query, as opposed to the `attname`. This is important when the primary key is a ForeignKey field because `attname` and `column` are not necessarily the same. """ b = BookFkAsPk.objects.create(book=self.b1) self.assertEqual( list( BookFkAsPk.objects.raw( "SELECT not_the_default FROM raw_query_bookfkaspk" ) ), [b], ) def test_decimal_parameter(self): c = Coffee.objects.create(brand="starbucks", price=20.5) qs = Coffee.objects.raw( "SELECT * FROM raw_query_coffee WHERE price >= %s", params=[Decimal(20)] ) self.assertEqual(list(qs), [c]) def test_result_caching(self): with self.assertNumQueries(1): books = Book.objects.raw("SELECT * FROM raw_query_book") list(books) list(books) def test_iterator(self): with self.assertNumQueries(2): books = Book.objects.raw("SELECT * FROM raw_query_book") list(books.iterator()) list(books.iterator()) def test_bool(self): self.assertIs(bool(Book.objects.raw("SELECT * FROM raw_query_book")), True) self.assertIs( bool(Book.objects.raw("SELECT * FROM raw_query_book WHERE id = 0")), False ) def test_len(self): self.assertEqual(len(Book.objects.raw("SELECT * FROM raw_query_book")), 4) self.assertEqual( len(Book.objects.raw("SELECT * FROM raw_query_book WHERE id = 0")), 0 )
RawQueryTests
python
cython__cython
tests/run/pep3135_class_cell.py
{ "start": 2212, "end": 2597 }
class ____: """ >>> obj = E() >>> obj.method()().__name__ 'E' >>> obj.method2()()().__name__ 'E' """ def method(self): def inner(): return __class__ return inner def method2(self): def inner(): def inner_inner(): return __class__ return inner_inner return inner @cython.cclass
E
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_fx.py
{ "start": 270, "end": 1321 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.weight1 = torch.nn.Parameter(torch.randn(6, 6)) self.weight2 = torch.nn.Parameter(torch.randn(6, 6)) self.weight_unused = torch.nn.Parameter(torch.randn(2, 2)) self.layer0 = torch.nn.Linear(6, 6) self.layer1 = torch.nn.Linear(6, 6, bias=False) self.layer2 = torch.nn.Sequential( torch.nn.Linear(6, 3, bias=False), torch.nn.ReLU(), torch.nn.Linear(3, 6, bias=False), ) self.relu = torch.nn.ReLU() def forward(self, x: torch.Tensor, run_all_layers: bool) -> torch.Tensor: z = self.relu(self.layer0(x)) z = self.relu(self.layer2(z)) z = z @ self.weight1 if run_all_layers: z = self.relu(self.layer1(z)) z = z @ self.weight2 # Use `layer0` twice to check the handling of multiplicity in the # saved data structures z = self.relu(self.layer0(x)) return z
Model
python
openai__openai-python
src/openai/types/evals/run_create_params.py
{ "start": 10076, "end": 12557 }
class ____(TypedDict, total=False): max_completion_tokens: int """The maximum number of tokens in the generated output.""" reasoning_effort: Optional[ReasoningEffort] """ Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1. - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. """ seed: int """A seed value to initialize the randomness, during sampling.""" temperature: float """A higher temperature increases randomness in the outputs.""" text: DataSourceCreateEvalResponsesRunDataSourceSamplingParamsText """Configuration options for a text response from the model. Can be plain text or structured JSON data. Learn more: - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) """ tools: Iterable[ToolParam] """An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter. The two categories of tools you can provide the model are: - **Built-in tools**: Tools that are provided by OpenAI that extend the model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about [built-in tools](https://platform.openai.com/docs/guides/tools). - **Function calls (custom tools)**: Functions that are defined by you, enabling the model to call your own code. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). """ top_p: float """An alternative to temperature for nucleus sampling; 1.0 includes all tokens."""
DataSourceCreateEvalResponsesRunDataSourceSamplingParams
python
pytorch__pytorch
test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py
{ "start": 50718, "end": 53960 }
class ____(TestCase): def setUp(self) -> None: self._store = DummyStore() self._backend = DummyRendezvousBackend() self._params = RendezvousParameters( backend=self._backend.name, endpoint="dummy_endpoint", run_id="dummy_run_id", min_nodes=3, max_nodes=6, join_timeout="50", last_call_timeout="60", close_timeout="70", ) self._expected_timeout = RendezvousTimeout( timedelta(seconds=50), timedelta(seconds=60), timedelta(seconds=70) ) def test_create_handler_returns_handler(self) -> None: handler = create_handler(self._store, self._backend, self._params) self.assertEqual(handler.get_backend(), self._backend.name) self.assertEqual(handler.get_run_id(), self._params.run_id) self.assertEqual(handler.settings.min_nodes, self._params.min_nodes) self.assertEqual(handler.settings.max_nodes, self._params.max_nodes) self.assertEqual(handler.settings.timeout.join, self._expected_timeout.join) self.assertEqual( handler.settings.timeout.last_call, self._expected_timeout.last_call ) self.assertEqual(handler.settings.timeout.close, self._expected_timeout.close) def test_create_handler_returns_handler_if_timeout_is_not_specified(self) -> None: del self._params.config["join_timeout"] del self._params.config["last_call_timeout"] del self._params.config["close_timeout"] self._expected_timeout = RendezvousTimeout() self.test_create_handler_returns_handler() @patch("torch.distributed.elastic.events.record_rdzv_event") def test_create_handler_records_and_raises_exceptions(self, record_mock) -> None: with patch.object(DynamicRendezvousHandler, "from_backend") as from_mock: from_mock.side_effect = RendezvousError("test error") with self.assertRaises(RendezvousError): create_handler(self._store, self._backend, self._params) record_mock.assert_called_once() def test_create_handler_rdzv_local_addr(self) -> None: params = RendezvousParameters( backend=self._backend.name, endpoint="dummy_endpoint", run_id="dummy_run_id", min_nodes=1, max_nodes=1, join_timeout="50", last_call_timeout="60", close_timeout="70", local_addr="127.0.0.2", ) store = HashStore() handler = create_handler(store, self._backend, params) rdzv_info = handler.next_rendezvous() self.assertEqual(rdzv_info.bootstrap_store_info.master_addr, "127.0.0.2") def _ignore_exception(exception_type: Exception, fn: Callable): try: fn() except exception_type: pass def _wait_for(condition, timeout=10, interval=1, name=None): def _wait_while(): while True: if condition(): break else: time.sleep(interval) wait_thread = threading.Thread(target=_wait_while, name=name) wait_thread.start() wait_thread.join(timeout=timeout)
CreateHandlerTest
python
ethereum__web3.py
web3/exceptions.py
{ "start": 5971, "end": 6103 }
class ____(ContractLogicError): """ Raised when a contract reverts with Panic, as of Solidity 0.8.0 """
ContractPanicError
python
getsentry__sentry
src/sentry/tagstore/snuba/backend.py
{ "start": 4185, "end": 4345 }
class ____[T, U](Protocol): def __call__( self, *, key: str, values_seen: int, count: int, top_values: tuple[U, ...] = () ) -> T: ...
_KeyCallable
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/components.py
{ "start": 35395, "end": 37386 }
class ____(PaginationStrategy): """ This pagination strategy functioning similarly to the default cursor pagination strategy. The custom behavior accounts for Hubspot's /search API limitation that only allows for a max of 10,000 total results for a query. Once we reach 10,000 records, we start a new query using the latest id collected. """ page_size: int primary_key: str = "id" RECORDS_LIMIT = 10000 @property def initial_token(self) -> Optional[Any]: return {"after": 0} def next_page_token( self, response: requests.Response, last_page_size: int, last_record: Optional[Record], last_page_token_value: Optional[Any] = None, ) -> Optional[Any]: # Hubspot documentation states that the search endpoints are limited to 10,000 total results # for any given query. Attempting to page beyond 10,000 will result in a 400 error. # https://developers.hubspot.com/docs/api/crm/search. We stop getting data at 10,000 and # start a new search query with the latest id that has been collected. if last_page_token_value and last_page_token_value.get("after", 0) + last_page_size >= self.RECORDS_LIMIT: return {"after": 0, "id": int(last_record[self.primary_key]) + 1} # Stop paginating when there are fewer records than the page size or the current page has no records if (last_page_size < self.page_size) or last_page_size == 0 or not response.json().get("paging"): return None last_id_of_previous_chunk = last_page_token_value.get("id") if last_id_of_previous_chunk: return {"after": last_page_token_value["after"] + last_page_size, self.primary_key: last_id_of_previous_chunk} else: return {"after": last_page_token_value["after"] + last_page_size} def get_page_size(self) -> Optional[int]: return self.page_size @dataclass
HubspotCRMSearchPaginationStrategy
python
huggingface__transformers
src/transformers/models/bros/modeling_bros.py
{ "start": 39399, "end": 43953 }
class ____(BrosPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.config = config self.num_labels = config.num_labels self.n_relations = config.n_relations self.backbone_hidden_size = config.hidden_size self.bros = BrosModel(config) (config.classifier_dropout if hasattr(config, "classifier_dropout") else config.hidden_dropout_prob) self.entity_linker = BrosRelationExtractor(config) self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, bbox: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, bbox_first_token_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]: r""" bbox ('torch.FloatTensor' of shape '(batch_size, num_boxes, 4)'): Bounding box coordinates for each token in the input sequence. Each bounding box is a list of four values (x1, y1, x2, y2), where (x1, y1) is the top left corner, and (x2, y2) is the bottom right corner of the bounding box. bbox_first_token_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to indicate the first token of each bounding box. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Examples: ```python >>> import torch >>> from transformers import BrosProcessor, BrosSpadeELForTokenClassification >>> processor = BrosProcessor.from_pretrained("jinho8345/bros-base-uncased") >>> model = BrosSpadeELForTokenClassification.from_pretrained("jinho8345/bros-base-uncased") >>> encoding = processor("Hello, my dog is cute", add_special_tokens=False, return_tensors="pt") >>> bbox = torch.tensor([[[0, 0, 1, 1]]]).repeat(1, encoding["input_ids"].shape[-1], 1) >>> encoding["bbox"] = bbox >>> outputs = model(**encoding) ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.bros( input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=True, ) last_hidden_states = outputs[0] last_hidden_states = last_hidden_states.transpose(0, 1).contiguous() logits = self.entity_linker(last_hidden_states, last_hidden_states).squeeze(0) loss = None if labels is not None: loss_fct = CrossEntropyLoss() batch_size, max_seq_length = attention_mask.shape device = attention_mask.device self_token_mask = torch.eye(max_seq_length, max_seq_length + 1).to(device=device, dtype=torch.bool) mask = bbox_first_token_mask.view(-1) bbox_first_token_mask = torch.cat( [ ~bbox_first_token_mask, torch.zeros([batch_size, 1], dtype=torch.bool, device=device), ], axis=1, ) logits = logits.masked_fill(bbox_first_token_mask[:, None, :], torch.finfo(logits.dtype).min) logits = logits.masked_fill(self_token_mask[None, :, :], torch.finfo(logits.dtype).min) loss = loss_fct(logits.view(-1, max_seq_length + 1)[mask], labels.view(-1)[mask]) return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "BrosPreTrainedModel", "BrosModel", "BrosForTokenClassification", "BrosSpadeEEForTokenClassification", "BrosSpadeELForTokenClassification", ]
BrosSpadeELForTokenClassification
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/api/auth/backend/test_basic_auth.py
{ "start": 1672, "end": 3838 }
class ____: def setup_method(self) -> None: mock_call.reset_mock() def test_requires_authentication_with_no_header(self, app): with app.test_request_context() as mock_context: mock_context.request.authorization = None result = function_decorated() assert type(result) is Response assert result.status_code == 401 @patch("airflow.providers.fab.auth_manager.api.auth.backend.basic_auth.get_auth_manager") @patch("airflow.providers.fab.auth_manager.api.auth.backend.basic_auth.login_user") def test_requires_authentication_with_ldap( self, mock_login_user, mock_get_auth_manager, app, mock_sm, mock_auth_manager, mock_authorization ): mock_sm.auth_type = AUTH_LDAP mock_get_auth_manager.return_value = mock_auth_manager user = Mock() mock_sm.auth_user_ldap.return_value = user with app.test_request_context() as mock_context: mock_context.request.authorization = mock_authorization function_decorated() mock_sm.auth_user_ldap.assert_called_once_with( mock_authorization.username, mock_authorization.password ) mock_login_user.assert_called_once_with(user, remember=False) mock_call.assert_called_once() @patch("airflow.providers.fab.auth_manager.api.auth.backend.basic_auth.get_auth_manager") @patch("airflow.providers.fab.auth_manager.api.auth.backend.basic_auth.login_user") def test_requires_authentication_with_db( self, mock_login_user, mock_get_auth_manager, app, mock_sm, mock_auth_manager, mock_authorization ): mock_get_auth_manager.return_value = mock_auth_manager user = Mock() mock_sm.auth_user_db.return_value = user with app.test_request_context() as mock_context: mock_context.request.authorization = mock_authorization function_decorated() mock_sm.auth_user_db.assert_called_once_with(mock_authorization.username, mock_authorization.password) mock_login_user.assert_called_once_with(user, remember=False) mock_call.assert_called_once()
TestBasicAuth
python
gevent__gevent
src/gevent/tests/test__event.py
{ "start": 4328, "end": 9467 }
class ____(greentest.TestCase): def _makeOne(self): return AsyncResult() def _setOne(self, one): one.set('from main') BG_WAIT_DELAY = 60 def _check_pypy_switch(self): # On PyPy 7.3.3, switching to the main greenlet of a thread from a # different thread silently does nothing. We can't detect the cross-thread # switch, and so this test breaks # https://foss.heptapod.net/pypy/pypy/-/issues/3381 if greentest.PYPY: import sys if sys.pypy_version_info[:3] <= (7, 3, 3): # pylint:disable=no-member self.skipTest("PyPy bug: https://foss.heptapod.net/pypy/pypy/-/issues/3381") @greentest.ignores_leakcheck def test_cross_thread_use(self, timed_wait=False, wait_in_bg=False): # Issue 1739. # AsyncResult has *never* been thread safe, and using it from one # thread to another is not safe. However, in some very careful use cases # that can actually work. # # This test makes sure it doesn't hang in one careful use # scenario. self.assertNotMonkeyPatched() # Need real threads, event objects from threading import Thread as NativeThread from threading import Event as NativeEvent if not wait_in_bg: self._check_pypy_switch() test = self class Thread(NativeThread): def __init__(self): NativeThread.__init__(self) self.daemon = True self.running_event = NativeEvent() self.finished_event = NativeEvent() self.async_result = test._makeOne() self.result = '<never set>' def run(self): # Give the loop in this thread something to do g_event = Event() def spin(): while not g_event.is_set(): g_event.wait(DELAY * 2) glet = gevent.spawn(spin) def work(): self.running_event.set() # If we use a timed wait(), the bug doesn't manifest. # This is probably because the loop wakes up to handle the timer, # and notices the callback. # See https://github.com/gevent/gevent/issues/1735 if timed_wait: self.result = self.async_result.wait(test.BG_WAIT_DELAY) else: self.result = self.async_result.wait() if wait_in_bg: # This results in a separate code path worker = gevent.spawn(work) worker.join() del worker else: work() g_event.set() glet.join() del glet self.finished_event.set() gevent.get_hub().destroy(destroy_loop=True) thread = Thread() thread.start() try: thread.running_event.wait() self._setOne(thread.async_result) thread.finished_event.wait(DELAY * 5) finally: thread.join(DELAY * 15) self._check_result(thread.result) def _check_result(self, result): self.assertEqual(result, 'from main') def test_cross_thread_use_bg(self): self.test_cross_thread_use(timed_wait=False, wait_in_bg=True) def test_cross_thread_use_timed(self): self.test_cross_thread_use(timed_wait=True, wait_in_bg=False) def test_cross_thread_use_timed_bg(self): self.test_cross_thread_use(timed_wait=True, wait_in_bg=True) @greentest.ignores_leakcheck def test_cross_thread_use_set_in_bg(self): self.assertNotMonkeyPatched() # Need real threads, event objects from threading import Thread as NativeThread from threading import Event as NativeEvent self._check_pypy_switch() test = self class Thread(NativeThread): def __init__(self): NativeThread.__init__(self) self.daemon = True self.running_event = NativeEvent() self.finished_event = NativeEvent() self.async_result = test._makeOne() self.result = '<never set>' def run(self): self.running_event.set() test._setOne(self.async_result) self.finished_event.set() gevent.get_hub().destroy(destroy_loop=True) thread = Thread() glet = None try: glet = gevent.spawn(thread.start) result = thread.async_result.wait(self.BG_WAIT_DELAY) finally: thread.join(DELAY * 15) if glet is not None: glet.join(DELAY) self._check_result(result) @greentest.ignores_leakcheck def test_cross_thread_use_set_in_bg2(self): # Do it again to make sure it works multiple times. self.test_cross_thread_use_set_in_bg()
TestAsyncResultCrossThread
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault2.py
{ "start": 2674, "end": 2780 }
class ____[**P = P1]: ... # This should generate an error because ParamSpec must be a list of types.
ClassP9
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis10.py
{ "start": 315, "end": 1576 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis10.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": "bar"}) chart.axis_ids = [41012608, 55821440] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) chart.set_x_axis({"reverse": 1}) chart.set_y_axis({"reverse": 1}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
pydantic__pydantic
tests/test_type_adapter.py
{ "start": 786, "end": 850 }
class ____(BaseModel): x: int T = TypeVar('T')
PydanticModel
python
django__django
tests/staticfiles_tests/storage.py
{ "start": 2561, "end": 2661 }
class ____(ManifestStaticFilesStorage): max_post_process_passes = 0
NoPostProcessReplacedPathStorage
python
google__jax
jax/experimental/topologies.py
{ "start": 799, "end": 2078 }
class ____: def __init__(self, devices: list[Device]): self.devices: list[Device] = devices def get_attached_topology(platform=None) -> TopologyDescription: return TopologyDescription(jax.devices(backend=platform)) def get_topology_desc( topology_name: str = "", platform: str | None = None, **kwargs ) -> TopologyDescription: if platform == "tpu" or platform is None: return TopologyDescription( xb.make_pjrt_tpu_topology( topology_name, **kwargs )._make_compile_only_devices() ) try: topology = xb.make_pjrt_topology(platform, topology_name, **kwargs) return TopologyDescription(topology._make_compile_only_devices()) # pytype: disable=attribute-error except _jax.JaxRuntimeError as e: msg, *_ = e.args if msg.startswith("UNIMPLEMENTED"): raise NotImplementedError(msg) from e else: raise # -- future mesh_utils -- def make_mesh( topo: TopologyDescription, mesh_shape: Sequence[int], axis_names: tuple[str, ...], *, contiguous_submeshes: bool = False ) -> jax.sharding.Mesh: devices = mesh_utils.create_device_mesh( mesh_shape, list(topo.devices), contiguous_submeshes=contiguous_submeshes) return jax.sharding.Mesh(devices, axis_names)
TopologyDescription
python
pypa__warehouse
warehouse/organizations/models.py
{ "start": 5159, "end": 6145 }
class ____(db.Model): __tablename__ = "organization_stripe_customers" __table_args__ = ( Index("organization_stripe_customers_organization_id_idx", "organization_id"), Index( "organization_stripe_customers_stripe_customer_id_idx", "stripe_customer_id" ), UniqueConstraint( "organization_id", "stripe_customer_id", name="_organization_stripe_customers_organization_customer_uc", ), ) __repr__ = make_repr("organization_id", "stripe_customer_id") organization_id: Mapped[UUID] = mapped_column( ForeignKey("organizations.id", onupdate="CASCADE", ondelete="CASCADE"), ) stripe_customer_id: Mapped[UUID] = mapped_column( ForeignKey("stripe_customers.id", onupdate="CASCADE", ondelete="CASCADE"), ) organization: Mapped[Organization] = relationship(lazy=False) customer: Mapped[StripeCustomer] = relationship(lazy=False)
OrganizationStripeCustomer
python
sphinx-doc__sphinx
sphinx/util/inventory.py
{ "start": 9383, "end": 12275 }
class ____: __slots__ = 'project_name', 'project_version', 'uri', 'display_name' project_name: str project_version: str uri: str display_name: str def __init__( self, *, project_name: str, project_version: str, uri: str, display_name: str, ) -> None: object.__setattr__(self, 'project_name', project_name) object.__setattr__(self, 'project_version', project_version) object.__setattr__(self, 'uri', uri) object.__setattr__(self, 'display_name', display_name) def __repr__(self) -> str: return ( '_InventoryItem(' f'project_name={self.project_name!r}, ' f'project_version={self.project_version!r}, ' f'uri={self.uri!r}, ' f'display_name={self.display_name!r}' ')' ) def __eq__(self, other: object) -> bool: if not isinstance(other, _InventoryItem): return NotImplemented return ( self.project_name == other.project_name and self.project_version == other.project_version and self.uri == other.uri and self.display_name == other.display_name ) def __hash__(self) -> int: return hash(( self.project_name, self.project_version, self.uri, self.display_name, )) def __setattr__(self, key: str, value: object) -> NoReturn: msg = '_InventoryItem is immutable' raise AttributeError(msg) def __delattr__(self, key: str) -> NoReturn: msg = '_InventoryItem is immutable' raise AttributeError(msg) def __getstate__(self) -> tuple[str, str, str, str]: return self.project_name, self.project_version, self.uri, self.display_name def __setstate__(self, state: tuple[str, str, str, str]) -> None: project_name, project_version, uri, display_name = state object.__setattr__(self, 'project_name', project_name) object.__setattr__(self, 'project_version', project_version) object.__setattr__(self, 'uri', uri) object.__setattr__(self, 'display_name', display_name) def __getitem__(self, key: int | slice) -> str | tuple[str, ...]: warnings.warn( 'The tuple interface for _InventoryItem objects is deprecated.', RemovedInSphinx10Warning, stacklevel=2, ) tpl = self.project_name, self.project_version, self.uri, self.display_name return tpl[key] def __iter__(self) -> Iterator[str]: warnings.warn( 'The iter() interface for _InventoryItem objects is deprecated.', RemovedInSphinx10Warning, stacklevel=2, ) tpl = self.project_name, self.project_version, self.uri, self.display_name return iter(tpl)
_InventoryItem
python
PyCQA__pyflakes
pyflakes/test/test_doctests.py
{ "start": 388, "end": 1410 }
class ____: withDoctest = True def doctestify(self, input): lines = [] for line in textwrap.dedent(input).splitlines(): if line.strip() == '': pass elif (line.startswith(' ') or line.startswith('except:') or line.startswith('except ') or line.startswith('finally:') or line.startswith('else:') or line.startswith('elif ') or (lines and lines[-1].startswith(('>>> @', '... @')))): line = "... %s" % line else: line = ">>> %s" % line lines.append(line) doctestificator = textwrap.dedent('''\ def doctest_something(): """ %s """ ''') return doctestificator % "\n ".join(lines) def flakes(self, input, *args, **kw): return super().flakes(self.doctestify(input), *args, **kw)
_DoctestMixin
python
sqlalchemy__sqlalchemy
test/engine/test_execute.py
{ "start": 91640, "end": 107330 }
class ____(fixtures.TestBase): __sparse_driver_backend__ = True def teardown_test(self): Engine.dispatch._clear() Engine._has_events = False def test_handle_error(self): engine = engines.testing_engine() canary = Mock(return_value=None) event.listen(engine, "handle_error", canary) with engine.connect() as conn: try: conn.exec_driver_sql("SELECT FOO FROM I_DONT_EXIST") assert False except tsa.exc.DBAPIError as e: ctx = canary.mock_calls[0][1][0] eq_(ctx.original_exception, e.orig) is_(ctx.sqlalchemy_exception, e) eq_(ctx.statement, "SELECT FOO FROM I_DONT_EXIST") def test_exception_event_reraise(self): engine = engines.testing_engine() class MyException(Exception): pass @event.listens_for(engine, "handle_error", retval=True) def err(context): stmt = context.statement exception = context.original_exception if "ERROR ONE" in str(stmt): return MyException("my exception") elif "ERROR TWO" in str(stmt): return exception else: return None conn = engine.connect() # case 1: custom exception assert_raises_message( MyException, "my exception", conn.exec_driver_sql, "SELECT 'ERROR ONE' FROM I_DONT_EXIST", ) # case 2: return the DBAPI exception we're given; # no wrapping should occur assert_raises( conn.dialect.dbapi.Error, conn.exec_driver_sql, "SELECT 'ERROR TWO' FROM I_DONT_EXIST", ) # case 3: normal wrapping assert_raises( tsa.exc.DBAPIError, conn.exec_driver_sql, "SELECT 'ERROR THREE' FROM I_DONT_EXIST", ) def test_exception_event_reraise_chaining(self): engine = engines.testing_engine() class MyException1(Exception): pass class MyException2(Exception): pass class MyException3(Exception): pass @event.listens_for(engine, "handle_error", retval=True) def err1(context): stmt = context.statement if ( "ERROR ONE" in str(stmt) or "ERROR TWO" in str(stmt) or "ERROR THREE" in str(stmt) ): return MyException1("my exception") elif "ERROR FOUR" in str(stmt): raise MyException3("my exception short circuit") @event.listens_for(engine, "handle_error", retval=True) def err2(context): stmt = context.statement if ( "ERROR ONE" in str(stmt) or "ERROR FOUR" in str(stmt) ) and isinstance(context.chained_exception, MyException1): raise MyException2("my exception chained") elif "ERROR TWO" in str(stmt): return context.chained_exception else: return None conn = engine.connect() with patch.object( engine.dialect.execution_ctx_cls, "handle_dbapi_exception" ) as patched: assert_raises_message( MyException2, "my exception chained", conn.exec_driver_sql, "SELECT 'ERROR ONE' FROM I_DONT_EXIST", ) eq_(patched.call_count, 1) with patch.object( engine.dialect.execution_ctx_cls, "handle_dbapi_exception" ) as patched: assert_raises( MyException1, conn.exec_driver_sql, "SELECT 'ERROR TWO' FROM I_DONT_EXIST", ) eq_(patched.call_count, 1) with patch.object( engine.dialect.execution_ctx_cls, "handle_dbapi_exception" ) as patched: # test that non None from err1 isn't cancelled out # by err2 assert_raises( MyException1, conn.exec_driver_sql, "SELECT 'ERROR THREE' FROM I_DONT_EXIST", ) eq_(patched.call_count, 1) with patch.object( engine.dialect.execution_ctx_cls, "handle_dbapi_exception" ) as patched: assert_raises( tsa.exc.DBAPIError, conn.exec_driver_sql, "SELECT 'ERROR FIVE' FROM I_DONT_EXIST", ) eq_(patched.call_count, 1) with patch.object( engine.dialect.execution_ctx_cls, "handle_dbapi_exception" ) as patched: assert_raises_message( MyException3, "my exception short circuit", conn.exec_driver_sql, "SELECT 'ERROR FOUR' FROM I_DONT_EXIST", ) eq_(patched.call_count, 1) @testing.only_on("sqlite", "using specific DB message") def test_exception_no_autorollback(self): """with the 2.0 engine, a SQL statement will have run "autobegin", so that we are in a transaction. so if an error occurs, we report the error but stay in the transaction. previously, we'd see the rollback failing due to autorollback when transaction isn't started. """ engine = engines.testing_engine() conn = engine.connect() def boom(connection): raise engine.dialect.dbapi.OperationalError("rollback failed") with patch.object(conn.dialect, "do_rollback", boom): assert_raises_message( tsa.exc.OperationalError, "no such table: i_dont_exist", conn.exec_driver_sql, "insert into i_dont_exist (x) values ('y')", ) # we're still in a transaction assert conn._transaction # only fails when we actually call rollback assert_raises_message( tsa.exc.OperationalError, "rollback failed", conn.rollback, ) def test_actual_autorollback(self): """manufacture an autorollback scenario that works in 2.x.""" engine = engines.testing_engine() conn = engine.connect() def boom(connection): raise engine.dialect.dbapi.OperationalError("rollback failed") @event.listens_for(conn, "begin") def _do_begin(conn): # run a breaking statement before begin actually happens conn.exec_driver_sql("insert into i_dont_exist (x) values ('y')") with patch.object(conn.dialect, "do_rollback", boom): assert_raises_message( tsa.exc.OperationalError, "rollback failed", conn.begin, ) def test_exception_event_ad_hoc_context(self): """test that handle_error is called with a context in cases where _handle_dbapi_error() is normally called without any context. """ engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, "handle_error", listener) nope = SomeException("nope") class MyType(TypeDecorator): impl = Integer cache_ok = True def process_bind_param(self, value, dialect): raise nope with engine.connect() as conn: assert_raises_message( tsa.exc.StatementError, r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ", conn.execute, select(1).where(column("foo") == literal("bar", MyType())), ) ctx = listener.mock_calls[0][1][0] assert ctx.statement.startswith("SELECT 1 ") is_(ctx.is_disconnect, False) is_(ctx.original_exception, nope) def test_exception_event_non_dbapi_error(self): """test that handle_error is called with a context in cases where DBAPI raises an exception that is not a DBAPI exception, e.g. internal errors or encoding problems. """ engine = engines.testing_engine() listener = Mock(return_value=None) event.listen(engine, "handle_error", listener) nope = TypeError("I'm not a DBAPI error") with engine.connect() as c: c.connection.cursor = Mock( return_value=Mock(execute=Mock(side_effect=nope)) ) assert_raises_message( TypeError, "I'm not a DBAPI error", c.exec_driver_sql, "select ", ) ctx = listener.mock_calls[0][1][0] eq_(ctx.statement, "select ") is_(ctx.is_disconnect, False) is_(ctx.original_exception, nope) def test_exception_event_disable_handlers(self): engine = engines.testing_engine() class MyException1(Exception): pass @event.listens_for(engine, "handle_error") def err1(context): stmt = context.statement if "ERROR_ONE" in str(stmt): raise MyException1("my exception short circuit") with engine.connect() as conn: assert_raises( tsa.exc.DBAPIError, conn.execution_options( skip_user_error_events=True ).exec_driver_sql, "SELECT ERROR_ONE FROM I_DONT_EXIST", ) assert_raises( MyException1, conn.execution_options( skip_user_error_events=False ).exec_driver_sql, "SELECT ERROR_ONE FROM I_DONT_EXIST", ) def _test_alter_disconnect(self, orig_error, evt_value): engine = engines.testing_engine() @event.listens_for(engine, "handle_error") def evt(ctx): ctx.is_disconnect = evt_value with patch.object( engine.dialect, "is_disconnect", Mock(return_value=orig_error) ): with engine.connect() as c: try: c.exec_driver_sql("SELECT x FROM nonexistent") assert False except tsa.exc.StatementError as st: eq_(st.connection_invalidated, evt_value) def test_alter_disconnect_to_true(self): self._test_alter_disconnect(False, True) self._test_alter_disconnect(True, True) def test_alter_disconnect_to_false(self): self._test_alter_disconnect(True, False) self._test_alter_disconnect(False, False) @testing.requires.independent_connections def _test_alter_invalidate_pool_to_false(self, set_to_false): orig_error = True engine = engines.testing_engine() @event.listens_for(engine, "handle_error") def evt(ctx): if set_to_false: ctx.invalidate_pool_on_disconnect = False c1, c2, c3 = ( engine.pool.connect(), engine.pool.connect(), engine.pool.connect(), ) crecs = [conn._connection_record for conn in (c1, c2, c3)] c1.close() c2.close() c3.close() with patch.object( engine.dialect, "is_disconnect", Mock(return_value=orig_error) ): with engine.connect() as c: target_crec = c.connection._connection_record try: c.exec_driver_sql("SELECT x FROM nonexistent") assert False except tsa.exc.StatementError as st: eq_(st.connection_invalidated, True) for crec in crecs: if crec is target_crec or not set_to_false: is_not(crec.dbapi_connection, crec.get_connection()) else: is_(crec.dbapi_connection, crec.get_connection()) def test_alter_invalidate_pool_to_false(self): self._test_alter_invalidate_pool_to_false(True) def test_alter_invalidate_pool_stays_true(self): self._test_alter_invalidate_pool_to_false(False) def test_handle_error_event_connect_isolation_level(self): engine = engines.testing_engine() class MySpecialException(Exception): pass @event.listens_for(engine, "handle_error") def handle_error(ctx): raise MySpecialException("failed operation") ProgrammingError = engine.dialect.dbapi.ProgrammingError with engine.connect() as conn: with patch.object( conn.dialect, "get_isolation_level", Mock(side_effect=ProgrammingError("random error")), ): assert_raises(MySpecialException, conn.get_isolation_level) def test_handle_error_not_on_connection(self, connection): with expect_raises_message( tsa.exc.InvalidRequestError, r"The handle_error\(\) event hook as of SQLAlchemy 2.0 is " r"established " r"on the Dialect, and may only be applied to the Engine as a " r"whole or to a specific Dialect as a whole, not on a " r"per-Connection basis.", ): @event.listens_for(connection, "handle_error") def handle_error(ctx): pass @testing.only_on("sqlite+pysqlite") def test_cursor_close_resultset_failed_connectionless(self): engine = engines.testing_engine() the_conn = [] the_cursor = [] @event.listens_for(engine, "after_cursor_execute") def go( connection, cursor, statement, parameters, context, executemany ): the_cursor.append(cursor) the_conn.append(connection) with mock.patch( "sqlalchemy.engine.cursor.CursorResult.__init__", Mock(side_effect=tsa.exc.InvalidRequestError("duplicate col")), ): with engine.connect() as conn: assert_raises( tsa.exc.InvalidRequestError, conn.execute, text("select 1"), ) # cursor is closed assert_raises_message( engine.dialect.dbapi.ProgrammingError, "Cannot operate on a closed cursor", the_cursor[0].execute, "select 1", ) # connection is closed assert the_conn[0].closed @testing.only_on("sqlite+pysqlite") def test_cursor_close_resultset_failed_explicit(self): engine = engines.testing_engine() the_cursor = [] @event.listens_for(engine, "after_cursor_execute") def go( connection, cursor, statement, parameters, context, executemany ): the_cursor.append(cursor) conn = engine.connect() with mock.patch( "sqlalchemy.engine.cursor.CursorResult.__init__", Mock(side_effect=tsa.exc.InvalidRequestError("duplicate col")), ): assert_raises( tsa.exc.InvalidRequestError, conn.execute, text("select 1"), ) # cursor is closed assert_raises_message( engine.dialect.dbapi.ProgrammingError, "Cannot operate on a closed cursor", the_cursor[0].execute, "select 1", ) # connection not closed assert not conn.closed conn.close()
HandleErrorTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 196658, "end": 197194 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("city", "country", "country_code", "region", "region_code") city = sgqlc.types.Field(String, graphql_name="city") country = sgqlc.types.Field(String, graphql_name="country") country_code = sgqlc.types.Field(String, graphql_name="countryCode") region = sgqlc.types.Field(String, graphql_name="region") region_code = sgqlc.types.Field(String, graphql_name="regionCode")
ActorLocation
python
django__django
tests/admin_views/test_skip_link_to_content.py
{ "start": 262, "end": 7193 }
class ____(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def test_use_skip_link_to_content(self): from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) # `Skip link` is not present. skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertFalse(skip_link.is_displayed()) # 1st TAB is pressed, `skip link` is shown. body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) # Press RETURN to skip the navbar links (view site / documentation / # change password / log out) and focus first model in the admin_views # list. skip_link.send_keys(Keys.RETURN) self.assertFalse(skip_link.is_displayed()) # `skip link` disappear. keys = [Keys.TAB, Keys.TAB] # The 1st TAB is the section title. if self.browser == "firefox": # For some reason Firefox doesn't focus the section title # ('ADMIN_VIEWS'). keys.remove(Keys.TAB) body.send_keys(keys) actors_a_tag = self.selenium.find_element(By.LINK_TEXT, "Actors") self.assertEqual(self.selenium.switch_to.active_element, actors_a_tag) # Go to Actors changelist, skip sidebar and focus "Add actor +". with self.wait_page_loaded(): actors_a_tag.send_keys(Keys.RETURN) body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertTrue(skip_link.is_displayed()) ActionChains(self.selenium).send_keys(Keys.RETURN, Keys.TAB).perform() actors_add_url = reverse("admin:admin_views_actor_add") actors_a_tag = self.selenium.find_element( By.CSS_SELECTOR, f"#content [href='{actors_add_url}']" ) self.assertEqual(self.selenium.switch_to.active_element, actors_a_tag) # Go to the Actor form and the first input will be focused # automatically. with self.wait_page_loaded(): actors_a_tag.send_keys(Keys.RETURN) first_input = self.selenium.find_element(By.ID, "id_name") self.assertEqual(self.selenium.switch_to.active_element, first_input) def test_dont_use_skip_link_to_content(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) # `Skip link` is not present. skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertFalse(skip_link.is_displayed()) # 1st TAB is pressed, `skip link` is shown. body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) # The 2nd TAB will focus the page title. body.send_keys(Keys.TAB) django_administration_title = self.selenium.find_element( By.LINK_TEXT, "Django administration" ) self.assertFalse(skip_link.is_displayed()) # `skip link` disappear. self.assertEqual( self.selenium.switch_to.active_element, django_administration_title ) def test_skip_link_with_RTL_language_doesnt_create_horizontal_scrolling(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys with override_settings(LANGUAGE_CODE="ar"): self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) skip_link = self.selenium.find_element( By.CLASS_NAME, "skip-to-content-link" ) body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) is_vertical_scrolleable = self.selenium.execute_script( "return arguments[0].scrollHeight > arguments[0].offsetHeight;", body ) is_horizontal_scrolleable = self.selenium.execute_script( "return arguments[0].scrollWeight > arguments[0].offsetWeight;", body ) self.assertTrue(is_vertical_scrolleable) self.assertFalse(is_horizontal_scrolleable) def test_skip_link_keyboard_navigation_in_changelist(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys Podcast.objects.create(name="apple", release_date="2000-09-19") self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_podcast_changelist") ) selectors = [ "ul.object-tools", # object_tools. "search#changelist-filter", # list_filter. "form#changelist-search", # search_fields. "nav.toplinks", # date_hierarchy. "form#changelist-form div.actions", # action. "table#result_list", # table. "div.changelist-footer", # footer. ] content = self.selenium.find_element(By.ID, "content-start") content.send_keys(Keys.TAB) for selector in selectors: with self.subTest(selector=selector): # Currently focused element. focused_element = self.selenium.switch_to.active_element expected_element = self.selenium.find_element(By.CSS_SELECTOR, selector) element_points = self.selenium.find_elements( By.CSS_SELECTOR, f"{selector} a, {selector} input, {selector} button", ) self.assertIn( focused_element.get_attribute("outerHTML"), expected_element.get_attribute("innerHTML"), ) # Move to the next container element via TAB. for point in element_points[::-1]: if point.is_displayed(): point.send_keys(Keys.TAB) break
SeleniumTests
python
lazyprogrammer__machine_learning_examples
rl3/a2c/atari_wrappers.py
{ "start": 8284, "end": 10092 }
class ____(gym.Wrapper): def __init__(self, env, rank=0): gym.Wrapper.__init__(self, env=env) self.rank = rank self.rewards = [] self.total_reward = [] self.summaries_dict = {'reward': 0, 'episode_length': 0, 'total_reward': 0, 'total_episode_length': 0} env = self.env while True: if hasattr(env, 'was_real_done'): self.episodic_env = env if not hasattr(env, 'env'): break env = env.env def reset(self): self.summaries_dict['reward'] = -1 self.summaries_dict['episode_length'] = -1 self.summaries_dict['total_reward'] = -1 self.summaries_dict['total_episode_length'] = -1 self.rewards = [] env = self.env if self.episodic_env.was_real_done: self.summaries_dict['total_reward'] = -1 self.summaries_dict['total_episode_length'] = -1 self.total_reward = [] return self.env.reset() def step(self, action): observation, reward, done, info = self.env.step(action) self.rewards.append(reward) self.total_reward.append(reward) if done: # print("Done! R = %s, N = %s" % (sum(self.rewards), len(self.rewards))) self.summaries_dict['reward'] = sum(self.rewards) self.summaries_dict['episode_length'] = len(self.rewards) if self.episodic_env.was_real_done: self.summaries_dict['total_reward'] = sum(self.total_reward) self.summaries_dict['total_episode_length'] = len(self.total_reward) info = self.summaries_dict.copy() # otherwise it will be overwritten # if done: # print("info:", info) return observation, reward, done, info
Monitor
python
mlflow__mlflow
mlflow/pmdarima/__init__.py
{ "start": 19418, "end": 22928 }
class ____: def __init__(self, pmdarima_model): import pmdarima self.pmdarima_model = pmdarima_model self._pmdarima_version = pmdarima.__version__ def get_raw_model(self): """ Returns the underlying model. """ return self.pmdarima_model def predict(self, dataframe, params: dict[str, Any] | None = None) -> pd.DataFrame: """ Args: dataframe: Model input data. params: Additional parameters to pass to the model for inference. Returns: Model predictions. """ df_schema = dataframe.columns.values.tolist() if len(dataframe) > 1: raise MlflowException( f"The provided prediction pd.DataFrame contains {len(dataframe)} rows. " "Only 1 row should be supplied.", error_code=INVALID_PARAMETER_VALUE, ) attrs = dataframe.to_dict(orient="index").get(0) n_periods = attrs.get("n_periods", None) if not n_periods: raise MlflowException( f"The provided prediction configuration pd.DataFrame columns ({df_schema}) do not " "contain the required column `n_periods` for specifying future prediction periods " "to generate.", error_code=INVALID_PARAMETER_VALUE, ) if not isinstance(n_periods, int): raise MlflowException( f"The provided `n_periods` value {n_periods} must be an integer." f"provided type: {type(n_periods)}", error_code=INVALID_PARAMETER_VALUE, ) # NB Any model that is trained with exogenous regressor elements will need to provide # `X` entries as a 2D array structure to the predict method. exogenous_regressor = attrs.get("X", None) if exogenous_regressor and Version(self._pmdarima_version) < Version("1.8.0"): warnings.warn( "An exogenous regressor element was provided in column 'X'. This is " "supported only in pmdarima version >= 1.8.0. Installed version: " f"{self._pmdarima_version}" ) return_conf_int = attrs.get("return_conf_int", False) alpha = attrs.get("alpha", 0.05) if not isinstance(n_periods, int): raise MlflowException( "The prediction DataFrame must contain a column `n_periods` with " "an integer value for number of future periods to predict.", error_code=INVALID_PARAMETER_VALUE, ) if Version(self._pmdarima_version) >= Version("1.8.0"): raw_predictions = self.pmdarima_model.predict( n_periods=n_periods, X=exogenous_regressor, return_conf_int=return_conf_int, alpha=alpha, ) else: raw_predictions = self.pmdarima_model.predict( n_periods=n_periods, return_conf_int=return_conf_int, alpha=alpha, ) if return_conf_int: ci_low, ci_high = list(zip(*raw_predictions[1])) predictions = pd.DataFrame.from_dict( {"yhat": raw_predictions[0], "yhat_lower": ci_low, "yhat_upper": ci_high} ) else: predictions = pd.DataFrame.from_dict({"yhat": raw_predictions}) return predictions
_PmdarimaModelWrapper
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1028857, "end": 1029653 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateEnterpriseTwoFactorAuthenticationRequiredSetting """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "message") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise") """The enterprise with the updated two factor authentication required setting. """ message = sgqlc.types.Field(String, graphql_name="message") """A message confirming the result of updating the two factor authentication required setting. """
UpdateEnterpriseTwoFactorAuthenticationRequiredSettingPayload
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_member_team_details.py
{ "start": 30964, "end": 42226 }
class ____(OrganizationMemberTeamTestBase): endpoint = "sentry-api-0-organization-member-team-details" method = "put" @with_feature("organizations:team-roles") def test_cannot_set_nonexistent_role(self) -> None: self.login_as(self.owner) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="poobah" ) assert resp.status_code == 400 @with_feature("organizations:team-roles") def test_cannot_promote_nonmember(self) -> None: self.login_as(self.owner) resp = self.get_response(self.org.slug, self.member.id, self.team.slug, teamRole="admin") assert resp.status_code == 404 @with_feature("organizations:team-roles") def test_owner_can_promote_member(self) -> None: self.login_as(self.owner) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" @with_feature("organizations:team-roles") def test_team_admin_can_promote_member(self) -> None: self.login_as(self.team_admin) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" @with_feature("organizations:team-roles") def test_superuser_can_promote_member(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" with self.settings(SENTRY_SELF_HOSTED=False): resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" @with_feature("organizations:team-roles") @override_options({"superuser.read-write.ga-rollout": True}) @override_settings(SENTRY_SELF_HOSTED=False) def test_superuser_read_cannot_promote_member(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 400 assert resp.data["detail"] == ERR_INSUFFICIENT_ROLE @with_feature("organizations:team-roles") @override_options({"superuser.read-write.ga-rollout": True}) @override_settings(SENTRY_SELF_HOSTED=False) def test_superuser_write_can_promote_member(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(superuser, superuser=True) self.add_user_permission(superuser, "superuser.write") resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" @with_feature("organizations:team-roles") def test_admin_can_promote_member(self) -> None: self.login_as(self.admin_on_team) resp = self.get_response( self.org.slug, self.member_on_team.id, self.team.slug, teamRole="admin" ) assert resp.status_code == 200 updated_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=self.member_on_team ) assert updated_omt.role == "admin" @with_feature("organizations:team-roles") def test_member_cannot_promote_member(self) -> None: self.login_as(self.member_on_team) other_member = self.create_member( organization=self.org, user=self.create_user(), role="member", teams=[self.team] ) resp = self.get_response(self.org.slug, other_member.id, self.team.slug, teamRole="admin") assert resp.status_code == 400 assert resp.data["detail"] == ERR_INSUFFICIENT_ROLE target_omt = OrganizationMemberTeam.objects.get( team=self.team, organizationmember=other_member ) assert target_omt.role is None assert target_omt.role is None @with_feature("organizations:team-roles") def test_org_write_scope_can_manage_team_roles(self) -> None: """Test that org:write scope is sufficient for managing team roles""" user = self.create_user() member = self.create_member( organization=self.org, user=user, role="member", teams=[self.team] ) self.sentry_app = self.create_sentry_app( name="Testin", organization=self.org, webhook_url="https://example.com", scopes=["org:write"], ) self.install = self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, user=self.admin ) self.api_token = self.create_internal_integration_token( install=self.install, user=self.admin ) resp = self.get_response( self.org.slug, member.id, self.team.slug, teamRole="admin", extra_headers={"HTTP_AUTHORIZATION": f"Bearer {self.api_token.token}"}, ) assert resp.status_code == 200 @with_feature("organizations:team-roles") def test_member_write_scope_can_manage_team_roles(self) -> None: """Test that member:write scope is sufficient for managing team roles""" user = self.create_user() member = self.create_member( organization=self.org, user=user, role="member", teams=[self.team] ) self.sentry_app = self.create_sentry_app( name="Testin", organization=self.org, webhook_url="https://example.com", scopes=["member:write"], ) self.install = self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, user=self.admin ) self.api_token = self.create_internal_integration_token( install=self.install, user=self.admin ) resp = self.get_response( self.org.slug, member.id, self.team.slug, teamRole="admin", extra_headers={"HTTP_AUTHORIZATION": f"Bearer {self.api_token.token}"}, ) assert resp.status_code == 200 @with_feature("organizations:team-roles") def test_team_write_scope_can_manage_team_roles(self) -> None: """Test that team:write scope is sufficient for managing team roles""" user = self.create_user() member = self.create_member( organization=self.org, user=user, role="member", teams=[self.team] ) self.sentry_app = self.create_sentry_app( name="Testin", organization=self.org, webhook_url="https://example.com", scopes=["team:write"], ) self.install = self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, user=self.admin ) self.api_token = self.create_internal_integration_token( install=self.install, user=self.admin ) resp = self.get_response( self.org.slug, member.id, self.team.slug, teamRole="admin", extra_headers={"HTTP_AUTHORIZATION": f"Bearer {self.api_token.token}"}, ) assert resp.status_code == 200 @with_feature("organizations:team-roles") def test_org_read_scope_cannot_manage_team_roles(self) -> None: """Test that org:read scope is insufficient for managing team roles""" user = self.create_user() member = self.create_member( organization=self.org, user=user, role="member", teams=[self.team] ) self.sentry_app = self.create_sentry_app( name="Testin", organization=self.org, webhook_url="https://example.com", scopes=["org:read"], ) self.install = self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, user=self.admin ) self.api_token = self.create_internal_integration_token( install=self.install, user=self.admin ) resp = self.get_response( self.org.slug, member.id, self.team.slug, teamRole="admin", extra_headers={"HTTP_AUTHORIZATION": f"Bearer {self.api_token.token}"}, ) assert resp.status_code == 400 assert resp.data["detail"] == ERR_INSUFFICIENT_ROLE @with_feature("organizations:team-roles") def test_member_read_scope_cannot_manage_team_roles(self) -> None: """Test that member:read scope is insufficient for managing team roles""" user = self.create_user() member = self.create_member( organization=self.org, user=user, role="member", teams=[self.team] ) self.sentry_app = self.create_sentry_app( name="Testin", organization=self.org, webhook_url="https://example.com", scopes=["member:read"], ) self.install = self.create_sentry_app_installation( organization=self.org, slug=self.sentry_app.slug, user=self.admin ) self.api_token = self.create_internal_integration_token( install=self.install, user=self.admin ) resp = self.get_response( self.org.slug, member.id, self.team.slug, teamRole="admin", extra_headers={"HTTP_AUTHORIZATION": f"Bearer {self.api_token.token}"}, ) assert resp.status_code == 400 assert resp.data["detail"] == ERR_INSUFFICIENT_ROLE @with_feature("organizations:team-roles") def test_team_contributor_cannot_downgrade_team_admin(self) -> None: self.login_as(self.member) resp = self.get_response( self.org.slug, self.team_admin.id, self.team.slug, teamRole="contributor", ) assert resp.status_code == 400 assert resp.data["detail"] == ERR_INSUFFICIENT_ROLE
UpdateOrganizationMemberTeamTest
python
pypa__setuptools
setuptools/command/bdist_egg.py
{ "start": 2022, "end": 17355 }
class ____(Command): description = 'create an "egg" distribution' user_options = [ ('bdist-dir=', 'b', "temporary directory for creating the distribution"), ( 'plat-name=', 'p', "platform name to embed in generated filenames " "(by default uses `sysconfig.get_platform()`)", ), ('exclude-source-files', None, "remove all .py files from the generated egg"), ( 'keep-temp', 'k', "keep the pseudo-installation tree around after " "creating the distribution archive", ), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ] boolean_options = ['keep-temp', 'skip-build', 'exclude-source-files'] def initialize_options(self): self.bdist_dir = None self.plat_name = None self.keep_temp = False self.dist_dir = None self.skip_build = False self.egg_output = None self.exclude_source_files = None def finalize_options(self) -> None: ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info") self.egg_info = ei_cmd.egg_info if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'egg') if self.plat_name is None: self.plat_name = get_platform() self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.egg_output is None: # Compute filename of the output egg basename = ei_cmd._get_egg_basename( py_version=get_python_version(), platform=self.distribution.has_ext_modules() and self.plat_name, ) self.egg_output = os.path.join(self.dist_dir, basename + '.egg') def do_install_data(self) -> None: # Hack for packages that install data to install's --install-lib self.get_finalized_command('install').install_lib = self.bdist_dir site_packages = os.path.normcase(os.path.realpath(_get_purelib())) old, self.distribution.data_files = self.distribution.data_files, [] for item in old: if isinstance(item, tuple) and len(item) == 2: if os.path.isabs(item[0]): realpath = os.path.realpath(item[0]) normalized = os.path.normcase(realpath) if normalized == site_packages or normalized.startswith( site_packages + os.sep ): item = realpath[len(site_packages) + 1 :], item[1] # XXX else: raise ??? self.distribution.data_files.append(item) try: log.info("installing package data to %s", self.bdist_dir) self.call_command('install_data', force=False, root=None) finally: self.distribution.data_files = old def get_outputs(self): return [self.egg_output] def call_command(self, cmdname, **kw): """Invoke reinitialized command `cmdname` with keyword args""" for dirname in INSTALL_DIRECTORY_ATTRS: kw.setdefault(dirname, self.bdist_dir) kw.setdefault('skip_build', self.skip_build) kw.setdefault('dry_run', self.dry_run) cmd = self.reinitialize_command(cmdname, **kw) self.run_command(cmdname) return cmd def run(self) -> None: # noqa: C901 # is too complex (14) # FIXME # Generate metadata first self.run_command("egg_info") # We run install_lib before install_data, because some data hacks # pull their data path from the install_lib command. log.info("installing library code to %s", self.bdist_dir) instcmd = self.get_finalized_command('install') old_root = instcmd.root instcmd.root = None if self.distribution.has_c_libraries() and not self.skip_build: self.run_command('build_clib') cmd = self.call_command('install_lib', warn_dir=False) instcmd.root = old_root all_outputs, ext_outputs = self.get_ext_outputs() self.stubs = [] to_compile = [] for p, ext_name in enumerate(ext_outputs): filename, _ext = os.path.splitext(ext_name) pyfile = os.path.join(self.bdist_dir, strip_module(filename) + '.py') self.stubs.append(pyfile) log.info("creating stub loader for %s", ext_name) if not self.dry_run: write_stub(os.path.basename(ext_name), pyfile) to_compile.append(pyfile) ext_outputs[p] = ext_name.replace(os.sep, '/') if to_compile: cmd.byte_compile(to_compile) if self.distribution.data_files: self.do_install_data() # Make the EGG-INFO directory archive_root = self.bdist_dir egg_info = os.path.join(archive_root, 'EGG-INFO') self.mkpath(egg_info) if self.distribution.scripts: script_dir = os.path.join(egg_info, 'scripts') log.info("installing scripts to %s", script_dir) self.call_command('install_scripts', install_dir=script_dir, no_ep=True) self.copy_metadata_to(egg_info) native_libs = os.path.join(egg_info, "native_libs.txt") if all_outputs: log.info("writing %s", native_libs) if not self.dry_run: ensure_directory(native_libs) with open(native_libs, 'wt', encoding="utf-8") as libs_file: libs_file.write('\n'.join(all_outputs)) libs_file.write('\n') elif os.path.isfile(native_libs): log.info("removing %s", native_libs) if not self.dry_run: os.unlink(native_libs) write_safety_flag(os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()) if os.path.exists(os.path.join(self.egg_info, 'depends.txt')): log.warn( "WARNING: 'depends.txt' will not be used by setuptools 0.6!\n" "Use the install_requires/extras_require setup() args instead." ) if self.exclude_source_files: self.zap_pyfiles() # Make the archive make_zipfile( self.egg_output, archive_root, verbose=self.verbose, dry_run=self.dry_run, # type: ignore[arg-type] # Is an actual boolean in vendored _distutils mode=self.gen_header(), ) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) # Add to 'Distribution.dist_files' so that the "upload" command works getattr(self.distribution, 'dist_files', []).append(( 'bdist_egg', get_python_version(), self.egg_output, )) def zap_pyfiles(self) -> None: log.info("Removing .py files from temporary directory") for base, dirs, files in walk_egg(self.bdist_dir): for name in files: path = os.path.join(base, name) if name.endswith('.py'): log.debug("Deleting %s", path) os.unlink(path) if base.endswith('__pycache__'): path_old = path pattern = r'(?P<name>.+)\.(?P<magic>[^.]+)\.pyc' m = re.match(pattern, name) # We shouldn't find any non-pyc files in __pycache__ assert m is not None path_new = os.path.join(base, os.pardir, m.group('name') + '.pyc') log.info(f"Renaming file from [{path_old}] to [{path_new}]") try: os.remove(path_new) except OSError: pass os.rename(path_old, path_new) def zip_safe(self): safe = getattr(self.distribution, 'zip_safe', None) if safe is not None: return safe log.warn("zip_safe flag not set; analyzing archive contents...") return analyze_egg(self.bdist_dir, self.stubs) def gen_header(self) -> Literal["w"]: return 'w' def copy_metadata_to(self, target_dir) -> None: "Copy metadata (egg info) to the target_dir" # normalize the path (so that a forward-slash in egg_info will # match using startswith below) norm_egg_info = os.path.normpath(self.egg_info) prefix = os.path.join(norm_egg_info, '') for path in self.ei_cmd.filelist.files: if path.startswith(prefix): target = os.path.join(target_dir, path[len(prefix) :]) ensure_directory(target) self.copy_file(path, target) def get_ext_outputs(self): """Get a list of relative paths to C extensions in the output distro""" all_outputs = [] ext_outputs = [] paths = {self.bdist_dir: ''} for base, dirs, files in sorted_walk(self.bdist_dir): all_outputs.extend( paths[base] + filename for filename in files if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS ) for filename in dirs: paths[os.path.join(base, filename)] = paths[base] + filename + '/' if self.distribution.has_ext_modules(): build_cmd = self.get_finalized_command('build_ext') for ext in build_cmd.extensions: if isinstance(ext, Library): continue fullname = build_cmd.get_ext_fullname(ext.name) filename = build_cmd.get_ext_filename(fullname) if not os.path.basename(filename).startswith('dl-'): if os.path.exists(os.path.join(self.bdist_dir, filename)): ext_outputs.append(filename) return all_outputs, ext_outputs NATIVE_EXTENSIONS: dict[str, None] = dict.fromkeys('.dll .so .dylib .pyd'.split()) def walk_egg(egg_dir: StrPath) -> Iterator[tuple[str, list[str], list[str]]]: """Walk an unpacked egg's contents, skipping the metadata directory""" walker = sorted_walk(egg_dir) base, dirs, files = next(walker) if 'EGG-INFO' in dirs: dirs.remove('EGG-INFO') yield base, dirs, files yield from walker def analyze_egg(egg_dir, stubs): # check for existing flag in EGG-INFO for flag, fn in safety_flags.items(): if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)): return flag if not can_scan(): return False safe = True for base, dirs, files in walk_egg(egg_dir): for name in files: if name.endswith(('.py', '.pyw')): continue elif name.endswith(('.pyc', '.pyo')): # always scan, even if we already know we're not safe safe = scan_module(egg_dir, base, name, stubs) and safe return safe def write_safety_flag(egg_dir, safe) -> None: # Write or remove zip safety flag file(s) for flag, fn in safety_flags.items(): fn = os.path.join(egg_dir, fn) if os.path.exists(fn): if safe is None or bool(safe) != flag: os.unlink(fn) elif safe is not None and bool(safe) == flag: with open(fn, 'wt', encoding="utf-8") as f: f.write('\n') safety_flags = { True: 'zip-safe', False: 'not-zip-safe', } def scan_module(egg_dir, base, name, stubs): """Check whether module possibly uses unsafe-for-zipfile stuff""" filename = os.path.join(base, name) if filename[:-1] in stubs: return True # Extension module pkg = base[len(egg_dir) + 1 :].replace(os.sep, '.') module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0] skip = 16 # skip magic & reserved? & date & file size f = open(filename, 'rb') f.read(skip) code = marshal.load(f) f.close() safe = True symbols = dict.fromkeys(iter_symbols(code)) for bad in ['__file__', '__path__']: if bad in symbols: log.warn("%s: module references %s", module, bad) safe = False if 'inspect' in symbols: for bad in [ 'getsource', 'getabsfile', 'getfile', 'getsourcefile', 'getsourcelines', 'findsource', 'getcomments', 'getframeinfo', 'getinnerframes', 'getouterframes', 'stack', 'trace', ]: if bad in symbols: log.warn("%s: module MAY be using inspect.%s", module, bad) safe = False return safe def iter_symbols(code: CodeType) -> Iterator[str]: """Yield names and strings used by `code` and its nested code objects""" yield from code.co_names for const in code.co_consts: if isinstance(const, str): yield const elif isinstance(const, CodeType): yield from iter_symbols(const) def can_scan() -> bool: if not sys.platform.startswith('java') and sys.platform != 'cli': # CPython, PyPy, etc. return True log.warn("Unable to analyze compiled code on this platform.") log.warn( "Please ask the author to include a 'zip_safe'" " setting (either True or False) in the package's setup.py" ) return False # Attribute names of options for commands that might need to be convinced to # install to the egg build directory INSTALL_DIRECTORY_ATTRS = ['install_lib', 'install_dir', 'install_data', 'install_base'] def make_zipfile( zip_filename: StrPathT, base_dir, verbose: bool = False, dry_run: bool = False, compress=True, mode: _ZipFileMode = 'w', ) -> StrPathT: """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file. """ import zipfile mkpath(os.path.dirname(zip_filename), dry_run=dry_run) # type: ignore[arg-type] # python/mypy#18075 log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) def visit(z, dirname, names): for name in names: path = os.path.normpath(os.path.join(dirname, name)) if os.path.isfile(path): p = path[len(base_dir) + 1 :] if not dry_run: z.write(path, p) log.debug("adding '%s'", p) compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED if not dry_run: z = zipfile.ZipFile(zip_filename, mode, compression=compression) for dirname, dirs, files in sorted_walk(base_dir): visit(z, dirname, files) z.close() else: for dirname, dirs, files in sorted_walk(base_dir): visit(None, dirname, files) return zip_filename
bdist_egg
python
PyCQA__pylint
tests/functional/n/no/no_member_dataclasses.py
{ "start": 1715, "end": 2029 }
class ____: # not a dataclass, field inferred to a Field attr1: str attr2: str dict_prop: Dict[str, str] = field(default_factory=dict) def some_func(self) -> None: for key, value in self.dict_prop.items(): # [no-member] print(key) print(value) @dataclass
TestClass2
python
matplotlib__matplotlib
lib/mpl_toolkits/axes_grid1/axes_size.py
{ "start": 4365, "end": 5045 }
class ____(_Base): """ Size whose absolute part is either the largest width or the largest height of the given *artist_list*. """ def __init__(self, artist_list, w_or_h): self._artist_list = artist_list _api.check_in_list(["width", "height"], w_or_h=w_or_h) self._w_or_h = w_or_h def add_artist(self, a): self._artist_list.append(a) def get_size(self, renderer): rel_size = 0. extent_list = [ getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi for a in self._artist_list] abs_size = max(extent_list, default=0) return rel_size, abs_size
MaxExtent
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/descriptor3.py
{ "start": 261, "end": 523 }
class ____(Generic[T]): def __get__( self, instance: object | None, owner: type | None = None ) -> list[T]: ... def __set__(self, instance: object, value: list[T]) -> None: ... def func1(factory: Callable[[], list[T]]) -> Desc1[T]: ...
Desc1
python
doocs__leetcode
solution/0900-0999/0992.Subarrays with K Different Integers/Solution.py
{ "start": 0, "end": 546 }
class ____: def subarraysWithKDistinct(self, nums: List[int], k: int) -> int: def f(k): pos = [0] * len(nums) cnt = Counter() j = 0 for i, x in enumerate(nums): cnt[x] += 1 while len(cnt) > k: cnt[nums[j]] -= 1 if cnt[nums[j]] == 0: cnt.pop(nums[j]) j += 1 pos[i] = j return pos return sum(a - b for a, b in zip(f(k - 1), f(k)))
Solution
python
jazzband__prettytable
tests/test_mediawiki.py
{ "start": 2237, "end": 4183 }
class ____: def test_mediawiki_and_back(self, city_data: PrettyTable) -> None: mediawiki_string = city_data.get_mediawiki_string() new_table = from_mediawiki(mediawiki_string) assert new_table.get_string() == city_data.get_string() def test_from_mediawiki_ignores_non_table_text( self, city_data: PrettyTable ) -> None: wiki_table = city_data.get_mediawiki_string() wiki_text = f"Before table text.\n{wiki_table}\nAfter table text." table = from_mediawiki(wiki_text) output = table.get_string() for header in city_data.field_names: assert header in output for row in city_data._rows: for cell in row: assert str(cell) in output assert "Before table text." not in output assert "After table text." not in output def test_from_mediawiki_ignores_caption(self) -> None: wiki_text = """ {| class="wikitable" |+ Optional caption |- ! Field 1 !! Field 2 |- | value 1 || value2 |- | value 4 || value5 |} """ table = from_mediawiki(wiki_text) output = table.get_string() assert "Optional caption" not in output assert "value 1" in output def test_from_mediawiki_no_header(self) -> None: wiki_text = """ {| class="wikitable" |- | value 1 || value2 |- | value 4 || value5 |- | value 7 || value8 |} """ with pytest.raises( ValueError, match="No valid header found in the MediaWiki table." ): from_mediawiki(wiki_text) def test_from_mediawiki_row_length_mismatch(self) -> None: wiki_text = """ {| class="wikitable" |- ! Field 1 !! Field 2 |- | value 1 || value2 || value3 |- | value 4 || value5 || value6 |} """ with pytest.raises( ValueError, match="Row length mismatch between header and body." ): from_mediawiki(wiki_text)
TestMediaWikiConstructor
python
apache__avro
lang/py/avro/errors.py
{ "start": 1114, "end": 1197 }
class ____(Exception): """The base class for exceptions in avro."""
AvroException
python
tensorflow__tensorflow
tensorflow/python/keras/layers/embeddings.py
{ "start": 1211, "end": 8948 }
class ____(Layer): """Turns positive integers (indexes) into dense vectors of fixed size. e.g. `[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]` This layer can only be used as the first layer in a model. Example: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Embedding(1000, 64, input_length=10)) >>> # The model will take as input an integer matrix of size (batch, >>> # input_length), and the largest integer (i.e. word index) in the input >>> # should be no larger than 999 (vocabulary size). >>> # Now model.output_shape is (None, 10, 64), where `None` is the batch >>> # dimension. >>> input_array = np.random.randint(1000, size=(32, 10)) >>> model.compile('rmsprop', 'mse') >>> output_array = model.predict(input_array) >>> print(output_array.shape) (32, 10, 64) Args: input_dim: Integer. Size of the vocabulary, i.e. maximum integer index + 1. output_dim: Integer. Dimension of the dense embedding. embeddings_initializer: Initializer for the `embeddings` matrix (see `keras.initializers`). embeddings_regularizer: Regularizer function applied to the `embeddings` matrix (see `keras.regularizers`). embeddings_constraint: Constraint function applied to the `embeddings` matrix (see `keras.constraints`). mask_zero: Boolean, whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is `True`, then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal size of vocabulary + 1). input_length: Length of input sequences, when it is constant. This argument is required if you are going to connect `Flatten` then `Dense` layers upstream (without it, the shape of the dense outputs cannot be computed). Input shape: 2D tensor with shape: `(batch_size, input_length)`. Output shape: 3D tensor with shape: `(batch_size, input_length, output_dim)`. **Note on variable placement:** By default, if a GPU is available, the embedding matrix will be placed on the GPU. This achieves the best performance, but it might cause issues: - You may be using an optimizer that does not support sparse GPU kernels. In this case you will see an error upon training your model. - Your embedding matrix may be too large to fit on your GPU. In this case you will see an Out Of Memory (OOM) error. In such cases, you should place the embedding matrix on the CPU memory. You can do so with a device scope, as such: ```python with tf.device('cpu:0'): embedding_layer = Embedding(...) embedding_layer.build() ``` The pre-built `embedding_layer` instance can then be added to a `Sequential` model (e.g. `model.add(embedding_layer)`), called in a Functional model (e.g. `x = embedding_layer(x)`), or used in a subclassed model. """ def __init__(self, input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None, **kwargs): if 'input_shape' not in kwargs: if input_length: kwargs['input_shape'] = (input_length,) else: kwargs['input_shape'] = (None,) if input_dim <= 0 or output_dim <= 0: raise ValueError('Both `input_dim` and `output_dim` should be positive, ' 'found input_dim {} and output_dim {}'.format( input_dim, output_dim)) if (not base_layer_utils.v2_dtype_behavior_enabled() and 'dtype' not in kwargs): # In TF1, the dtype defaults to the input dtype which is typically int32, # so explicitly set it to floatx kwargs['dtype'] = backend.floatx() # We set autocast to False, as we do not want to cast floating- point inputs # to self.dtype. In call(), we cast to int32, and casting to self.dtype # before casting to int32 might cause the int32 values to be different due # to a loss of precision. kwargs['autocast'] = False super(Embedding, self).__init__(**kwargs) self.input_dim = input_dim self.output_dim = output_dim self.embeddings_initializer = initializers.get(embeddings_initializer) self.embeddings_regularizer = regularizers.get(embeddings_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.embeddings_constraint = constraints.get(embeddings_constraint) self.mask_zero = mask_zero self.supports_masking = mask_zero self.input_length = input_length @tf_utils.shape_type_conversion def build(self, input_shape=None): self.embeddings = self.add_weight( shape=(self.input_dim, self.output_dim), initializer=self.embeddings_initializer, name='embeddings', regularizer=self.embeddings_regularizer, constraint=self.embeddings_constraint, experimental_autocast=False) self.built = True def compute_mask(self, inputs, mask=None): if not self.mask_zero: return None return math_ops.not_equal(inputs, 0) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.input_length is None: return input_shape + (self.output_dim,) else: # input_length can be tuple if input is 3D or higher if isinstance(self.input_length, (list, tuple)): in_lens = list(self.input_length) else: in_lens = [self.input_length] if len(in_lens) != len(input_shape) - 1: raise ValueError('"input_length" is %s, ' 'but received input has shape %s' % (str( self.input_length), str(input_shape))) else: for i, (s1, s2) in enumerate(zip(in_lens, input_shape[1:])): if s1 is not None and s2 is not None and s1 != s2: raise ValueError('"input_length" is %s, ' 'but received input has shape %s' % (str( self.input_length), str(input_shape))) elif s1 is None: in_lens[i] = s2 return (input_shape[0],) + tuple(in_lens) + (self.output_dim,) def call(self, inputs): dtype = backend.dtype(inputs) if dtype != 'int32' and dtype != 'int64': inputs = math_ops.cast(inputs, 'int32') out = embedding_ops.embedding_lookup_v2(self.embeddings, inputs) if self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype: # Instead of casting the variable as in most layers, cast the output, as # this is mathematically equivalent but is faster. out = math_ops.cast(out, self._dtype_policy.compute_dtype) return out def get_config(self): config = { 'input_dim': self.input_dim, 'output_dim': self.output_dim, 'embeddings_initializer': initializers.serialize(self.embeddings_initializer), 'embeddings_regularizer': regularizers.serialize(self.embeddings_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'embeddings_constraint': constraints.serialize(self.embeddings_constraint), 'mask_zero': self.mask_zero, 'input_length': self.input_length } base_config = super(Embedding, self).get_config() return dict(list(base_config.items()) + list(config.items()))
Embedding
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 206071, "end": 206946 }
class ____(Operation): def __init__(self, k=0, *, name=None): super().__init__(name=name) self.k = k def call(self, x): return backend.numpy.triu(x, k=self.k) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.triu", "keras.ops.numpy.triu"]) def triu(x, k=0): """Return upper triangle of a tensor. For tensors with `ndim` exceeding 2, `triu` will apply to the final two axes. Args: x: Input tensor. k: Diagonal below which to zero elements. Defaults to `0`. the main diagonal. `k < 0` is below it, and `k > 0` is above it. Returns: Upper triangle of `x`, of same shape and data type as `x`. """ if any_symbolic_tensors((x,)): return Triu(k=k).symbolic_call(x) return backend.numpy.triu(x, k=k)
Triu
python
redis__redis-py
tests/test_maint_notifications.py
{ "start": 548, "end": 2713 }
class ____: """Test the base MaintenanceNotification class functionality through concrete subclasses.""" def test_abstract_class_cannot_be_instantiated(self): """Test that MaintenanceNotification cannot be instantiated directly.""" with patch("time.monotonic", return_value=1000): with pytest.raises(TypeError): MaintenanceNotification(id=1, ttl=10) # type: ignore def test_init_through_subclass(self): """Test MaintenanceNotification initialization through concrete subclass.""" with patch("time.monotonic", return_value=1000): notification = NodeMovingNotification( id=1, new_node_host="localhost", new_node_port=6379, ttl=10 ) assert notification.id == 1 assert notification.ttl == 10 assert notification.creation_time == 1000 assert notification.expire_at == 1010 @pytest.mark.parametrize( ("current_time", "expected_expired_state"), [ (1005, False), (1015, True), ], ) def test_is_expired(self, current_time, expected_expired_state): """Test is_expired returns False for non-expired notification.""" with patch("time.monotonic", return_value=1000): notification = NodeMovingNotification( id=1, new_node_host="localhost", new_node_port=6379, ttl=10 ) with patch("time.monotonic", return_value=current_time): assert notification.is_expired() == expected_expired_state def test_is_expired_exact_boundary(self): """Test is_expired at exact expiration boundary.""" with patch("time.monotonic", return_value=1000): notification = NodeMovingNotification( id=1, new_node_host="localhost", new_node_port=6379, ttl=10 ) with patch("time.monotonic", return_value=1010): # Exactly at expiration assert not notification.is_expired() with patch("time.monotonic", return_value=1011): # 1 second past expiration assert notification.is_expired()
TestMaintenanceNotification
python
doocs__leetcode
solution/2100-2199/2140.Solving Questions With Brainpower/Solution.py
{ "start": 0, "end": 295 }
class ____: def mostPoints(self, questions: List[List[int]]) -> int: @cache def dfs(i: int) -> int: if i >= len(questions): return 0 p, b = questions[i] return max(p + dfs(i + b + 1), dfs(i + 1)) return dfs(0)
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 43273, "end": 43380 }
class ____(Protocol[_T_con]): def __call__(s, self: Any, value: _T_con, /) -> None: ...
_HybridSetterType
python
PyCQA__pylint
tests/functional/u/unsubscriptable_object.py
{ "start": 520, "end": 590 }
class ____(Generic[T]): """It's an animal.""" identity: T
Animal
python
hynek__structlog
src/structlog/dev.py
{ "start": 6364, "end": 7885 }
class ____: """ Format a key-value pair. Args: key_style: The style to apply to the key. If None, the key is omitted. value_style: The style to apply to the value. reset_style: The style to apply whenever a style is no longer needed. value_repr: A callable that returns the string representation of the value. width: The width to pad the value to. If 0, no padding is done. prefix: A string to prepend to the formatted key-value pair. May contain styles. postfix: A string to append to the formatted key-value pair. May contain styles. .. versionadded:: 23.3.0 """ key_style: str | None value_style: str reset_style: str value_repr: Callable[[object], str] width: int = 0 prefix: str = "" postfix: str = "" def __call__(self, key: str, value: object) -> str: sio = StringIO() if self.prefix: sio.write(self.prefix) sio.write(self.reset_style) if self.key_style is not None: sio.write(self.key_style) sio.write(key) sio.write(self.reset_style) sio.write("=") sio.write(self.value_style) sio.write(_pad(self.value_repr(value), self.width)) sio.write(self.reset_style) if self.postfix: sio.write(self.postfix) sio.write(self.reset_style) return sio.getvalue()
KeyValueColumnFormatter
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 686190, "end": 686807 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("WorkflowRunEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field(sgqlc.types.list_of("WorkflowRun"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null(PageInfo), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
WorkflowRunConnection
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_business_year.py
{ "start": 4902, "end": 6437 }
class ____: def test_bad_month_fail(self): msg = "Month must go from 1 to 12" with pytest.raises(ValueError, match=msg): BYearEnd(month=13) with pytest.raises(ValueError, match=msg): BYearEnd(month=0) offset_cases = [] offset_cases.append( ( BYearEnd(month=6), { datetime(2008, 1, 1): datetime(2008, 6, 30), datetime(2007, 6, 30): datetime(2008, 6, 30), }, ) ) offset_cases.append( ( BYearEnd(n=-1, month=6), { datetime(2008, 1, 1): datetime(2007, 6, 29), datetime(2007, 6, 30): datetime(2007, 6, 29), }, ) ) @pytest.mark.parametrize("case", offset_cases) def test_offset(self, case): offset, cases = case for base, expected in cases.items(): assert_offset_equal(offset, base, expected) def test_roll(self): offset = BYearEnd(month=6) date = datetime(2009, 11, 30) assert offset.rollforward(date) == datetime(2010, 6, 30) assert offset.rollback(date) == datetime(2009, 6, 30) on_offset_cases = [ (BYearEnd(month=2), datetime(2007, 2, 28), True), (BYearEnd(month=6), datetime(2007, 6, 30), False), ] @pytest.mark.parametrize("case", on_offset_cases) def test_is_on_offset(self, case): offset, dt, expected = case assert_is_on_offset(offset, dt, expected)
TestBYearEndLagged
python
mlflow__mlflow
mlflow/store/artifact/models_artifact_repo.py
{ "start": 993, "end": 11464 }
class ____(ArtifactRepository): """ Handles artifacts associated with a model version in the model registry via URIs of the form: - `models:/<model_name>/<model_version>` - `models:/<model_name>/<stage>` (refers to the latest model version in the given stage) - `models:/<model_name>/latest` (refers to the latest of all model versions) It is a light wrapper that resolves the artifact path to an absolute URI then instantiates and uses the artifact repository for that URI. """ def __init__( self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | None = None ) -> None: from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository super().__init__(artifact_uri, tracking_uri, registry_uri) registry_uri = registry_uri or mlflow.get_registry_uri() self.is_logged_model_uri = self._is_logged_model_uri(artifact_uri) if is_databricks_unity_catalog_uri(uri=registry_uri) and not self.is_logged_model_uri: self.repo = UnityCatalogModelsArtifactRepository( artifact_uri=artifact_uri, registry_uri=registry_uri, tracking_uri=tracking_uri, ) self.model_name = self.repo.model_name self.model_version = self.repo.model_version elif is_oss_unity_catalog_uri(uri=registry_uri) and not self.is_logged_model_uri: self.repo = UnityCatalogOSSModelsArtifactRepository( artifact_uri=artifact_uri, registry_uri=registry_uri, tracking_uri=tracking_uri, ) self.model_name = self.repo.model_name self.model_version = self.repo.model_version elif ( is_using_databricks_registry(artifact_uri, registry_uri) and not self.is_logged_model_uri ): # Use the DatabricksModelsArtifactRepository if a databricks profile is being used. self.repo = DatabricksModelsArtifactRepository( artifact_uri, tracking_uri=tracking_uri, registry_uri=registry_uri ) self.model_name = self.repo.model_name self.model_version = self.repo.model_version else: ( self.model_name, self.model_version, underlying_uri, ) = ModelsArtifactRepository._get_model_uri_infos(artifact_uri) self.repo = get_artifact_repository( underlying_uri, tracking_uri=tracking_uri, registry_uri=registry_uri ) # TODO: it may be nice to fall back to the source URI explicitly here if for some reason # we don't get a download URI here, or fail during the download itself. @staticmethod def is_models_uri(uri): return urllib.parse.urlparse(uri).scheme == "models" @staticmethod def split_models_uri(uri): """ Split 'models:/<name>/<version>/path/to/model' into ('models:/<name>/<version>', 'path/to/model'). Split 'models://<scope>:<prefix>@databricks/<name>/<version>/path/to/model' into ('models://<scope>:<prefix>@databricks/<name>/<version>', 'path/to/model'). Split 'models:/<name>@alias/path/to/model' into ('models:/<name>@alias', 'path/to/model'). """ uri = uri.rstrip("/") parsed_url = urllib.parse.urlparse(uri) path = parsed_url.path netloc = parsed_url.netloc if path.count("/") >= 2 and not path.endswith("/"): splits = path.split("/", 3) cut_index = 2 if "@" in splits[1] else 3 model_name_and_version = splits[:cut_index] artifact_path = "/".join(splits[cut_index:]) base_part = f"models://{netloc}" if netloc else "models:" return base_part + "/".join(model_name_and_version), artifact_path return uri, "" @staticmethod def _is_logged_model_uri(uri: str | Path) -> bool: """ Returns True if the URI is a logged model URI (e.g. 'models:/<model_id>'), False otherwise. """ uri = str(uri) return is_models_uri(uri) and _parse_model_uri(uri).model_id is not None @staticmethod def _get_model_uri_infos(uri): # Note: to support a registry URI that is different from the tracking URI here, # we'll need to add setting of registry URIs via environment variables. from mlflow import MlflowClient databricks_profile_uri = ( get_databricks_profile_uri_from_artifact_uri(uri) or mlflow.get_registry_uri() ) client = MlflowClient(registry_uri=databricks_profile_uri) name_and_version_or_id = get_model_name_and_version(client, uri) if len(name_and_version_or_id) == 1: name = None version = None model_id = name_and_version_or_id[0] download_uri = client.get_logged_model(model_id).artifact_location else: name, version = name_and_version_or_id download_uri = client.get_model_version_download_uri(name, version) return ( name, version, add_databricks_profile_info_to_artifact_uri(download_uri, databricks_profile_uri), ) @staticmethod def get_underlying_uri(uri): _, _, underlying_uri = ModelsArtifactRepository._get_model_uri_infos(uri) return underlying_uri def log_artifact(self, local_file, artifact_path=None): """ Log a local file as an artifact, optionally taking an ``artifact_path`` to place it in within the run's artifacts. Run artifacts can be organized into directories, so you can place the artifact in a directory this way. Args: local_file: Path to artifact to log. artifact_path: Directory within the run's artifact directory in which to log the artifact. """ if self.is_logged_model_uri: return self.repo.log_artifact(local_file, artifact_path) raise ValueError( "log_artifact is not supported for models:/<name>/<version> URIs. " "Use register_model instead." ) def log_artifacts(self, local_dir, artifact_path=None): """ Log the files in the specified local directory as artifacts, optionally taking an ``artifact_path`` to place them in within the run's artifacts. Args: local_dir: Directory of local artifacts to log. artifact_path: Directory within the run's artifact directory in which to log the artifacts. """ if self.is_logged_model_uri: return self.repo.log_artifacts(local_dir, artifact_path) raise ValueError( "log_artifacts is not supported for models:/<name>/<version> URIs. " "Use register_model instead." ) def list_artifacts(self, path): """ Return all the artifacts for this run_id directly under path. If path is a file, returns an empty list. Will error if path is neither a file nor directory. Args: path: Relative source path that contain desired artifacts. Returns: List of artifacts as FileInfo listed directly under path. """ return self.repo.list_artifacts(path) def _add_registered_model_meta_file(self, model_path): from mlflow.utils.yaml_utils import write_yaml write_yaml( model_path, REGISTERED_MODEL_META_FILE_NAME, { "model_name": self.model_name, "model_version": self.model_version, }, overwrite=True, ensure_yaml_extension=False, ) def download_artifacts(self, artifact_path, dst_path=None, lineage_header_info=None): """ Download an artifact file or directory to a local directory if applicable, and return a local path for it. For registered models, when the artifact is downloaded, the model name and version are saved in the "registered_model_meta" file on the caller's side. The caller is responsible for managing the lifecycle of the downloaded artifacts. Args: artifact_path: Relative source path to the desired artifacts. dst_path: Absolute path of the local filesystem destination directory to which to download the specified artifacts. This directory must already exist. If unspecified, the artifacts will either be downloaded to a new uniquely-named directory on the local filesystem or will be returned directly in the case of the LocalArtifactRepository. lineage_header_info: Linear header information. Returns: Absolute path of the local filesystem location containing the desired artifacts. """ from mlflow.models.model import MLMODEL_FILE_NAME # Pass lineage header info if model is registered in UC if isinstance(self.repo, UnityCatalogModelsArtifactRepository): model_path = self.repo.download_artifacts( artifact_path, dst_path, lineage_header_info=lineage_header_info ) else: model_path = self.repo.download_artifacts(artifact_path, dst_path) # NB: only add the registered model metadata iff the artifact path is at the root model # directory. For individual files or subdirectories within the model directory, do not # create the metadata file. if os.path.isdir(model_path) and MLMODEL_FILE_NAME in os.listdir(model_path): self._add_registered_model_meta_file(model_path) return model_path def _download_file(self, remote_file_path, local_path): """ Download the file at the specified relative remote path and saves it at the specified local path. Args: remote_file_path: Source path to the remote file, relative to the root directory of the artifact repository. local_path: The path to which to save the downloaded file. """ self.repo._download_file(remote_file_path, local_path) def delete_artifacts(self, artifact_path=None): raise MlflowException("Not implemented yet")
ModelsArtifactRepository
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/postgres/apps.py
{ "start": 36, "end": 151 }
class ____(AppConfig): name = "sentry.sentry_metrics.indexer.postgres" label = "indexer_postgres_config"
Config
python
apache__airflow
providers/standard/tests/unit/standard/operators/test_python.py
{ "start": 68513, "end": 71840 }
class ____(BaseTestPythonVirtualenvOperator): opcls = ExternalPythonOperator @staticmethod def default_kwargs(*, python_version=DEFAULT_PYTHON_VERSION, **kwargs): kwargs["python"] = sys.executable return kwargs @mock.patch("pickle.loads") def test_except_value_error(self, loads_mock): def f(): return 1 task = ExternalPythonOperator( python_callable=f, task_id="task", python=sys.executable, dag=self.dag_non_serialized, ) loads_mock.side_effect = DeserializingResultError with pytest.raises(DeserializingResultError): task._read_result(path=mock.Mock()) def test_airflow_version(self): def f(): return 42 op = ExternalPythonOperator( python_callable=f, task_id="task", python=sys.executable, expect_airflow=True ) assert op._get_airflow_version_from_target_env() def test_airflow_version_doesnt_match(self, caplog): def f(): return 42 op = ExternalPythonOperator( python_callable=f, task_id="task", python=sys.executable, expect_airflow=True ) with mock.patch.object( ExternalPythonOperator, "_external_airflow_version_script", new_callable=mock.PropertyMock ) as mock_script: mock_script.return_value = "print('1.10.4')" caplog.set_level("WARNING") caplog.clear() assert op._get_airflow_version_from_target_env() is None assert "(1.10.4) is different than the runtime Airflow version" in caplog.text def test_airflow_version_script_error_handle(self, caplog): def f(): return 42 op = ExternalPythonOperator( python_callable=f, task_id="task", python=sys.executable, expect_airflow=True ) with mock.patch.object( ExternalPythonOperator, "_external_airflow_version_script", new_callable=mock.PropertyMock ) as mock_script: mock_script.return_value = "raise SystemExit('Something went wrong')" caplog.set_level("WARNING") caplog.clear() assert op._get_airflow_version_from_target_env() is None assert "Something went wrong" in caplog.text assert "returned non-zero exit status" in caplog.text @mock.patch.object(ExternalPythonOperator, "_get_airflow_version_from_target_env") def test_iter_serializable_context_keys_respects_expect_airflow_false(self, mock_get_airflow_version): """Test that when expect_airflow=False, _get_airflow_version_from_target_env is not called.""" def f(): return 42 op = ExternalPythonOperator( python_callable=f, task_id="task", python=sys.executable, expect_airflow=False ) keys = set(op._iter_serializable_context_keys()) mock_get_airflow_version.assert_not_called() # BASE keys should always be present base_keys = set(op.BASE_SERIALIZABLE_CONTEXT_KEYS) airflow_keys = set(op.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS) assert base_keys <= keys assert not (airflow_keys & keys), "Airflow keys should not be present when expect_airflow=False"
TestExternalPythonOperator
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 94653, "end": 95988 }
class ____(test_util.TensorFlowTestCase): def test_tile_tensor_list(self): t = constant_op.constant(np.random.uniform(size=[2, 3, 4])) handle = list_ops.tensor_list_from_tensor(t, element_shape=None) with ops.device("CPU:0"): tiled_handles = array_ops.tile(array_ops.reshape(handle, [1]), [2]) tiled_tensor_0 = list_ops.tensor_list_stack(tiled_handles[0], t.dtype, 2, [3, 4]) tiled_tensor_1 = list_ops.tensor_list_stack(tiled_handles[1], t.dtype, 2, [3, 4]) self.assertAllEqual(t, tiled_tensor_0) self.assertAllEqual(t, tiled_tensor_1) # Now mutate some of the lists and make sure the changes are not reflected # in the tiled handles. with ops.control_dependencies([ list_ops.tensor_list_scatter([t[0] + 1], [0], input_handle=handle), list_ops.tensor_list_set_item(tiled_handles[0], 0, t[0] + 2)]): tiled_tensor_0 = list_ops.tensor_list_stack(tiled_handles[0], t.dtype, 2, [3, 4]) tiled_tensor_1 = list_ops.tensor_list_stack(tiled_handles[1], t.dtype, 2, [3, 4]) self.assertAllEqual(t, tiled_tensor_0) self.assertAllEqual(t, tiled_tensor_1)
TileVariantTest
python
PrefectHQ__prefect
src/prefect/server/events/filters.py
{ "start": 6947, "end": 8900 }
class ____(EventDataFilter): prefix: Optional[list[str]] = Field( default=None, description="Only include events matching one of these prefixes" ) exclude_prefix: Optional[list[str]] = Field( default=None, description="Exclude events matching one of these prefixes" ) name: Optional[list[str]] = Field( default=None, description="Only include events matching one of these names exactly", ) exclude_name: Optional[list[str]] = Field( default=None, description="Exclude events matching one of these names exactly" ) def includes(self, event: Event) -> bool: if self.prefix: if not any(event.event.startswith(prefix) for prefix in self.prefix): return False if self.exclude_prefix: if any(event.event.startswith(prefix) for prefix in self.exclude_prefix): return False if self.name: if not any(event.event == name for name in self.name): return False if self.exclude_name: if any(event.event == name for name in self.exclude_name): return False return True @db_injector def build_where_clauses( self, db: PrefectDBInterface ) -> Sequence["ColumnExpressionArgument[bool]"]: filters: list["ColumnExpressionArgument[bool]"] = [] if self.prefix: filters.append( sa.or_(*(db.Event.event.startswith(prefix) for prefix in self.prefix)) ) if self.exclude_prefix: filters.extend( sa.not_(db.Event.event.startswith(prefix)) for prefix in self.exclude_prefix ) if self.name: filters.append(db.Event.event.in_(self.name)) if self.exclude_name: filters.append(db.Event.event.not_in(self.exclude_name)) return filters @dataclass
EventNameFilter
python
getsentry__sentry
tests/sentry/seer/explorer/test_custom_tool_utils.py
{ "start": 3167, "end": 3840 }
class ____(ExplorerTool): @classmethod def get_description(cls): return "Process a list of items" @classmethod def get_params(cls): return [ ExplorerToolParam( name="items", description="Items to process", type=ArrayType(item_type=ExplorerParamType.STRING), ), ExplorerToolParam( name="priorities", description="Priorities", type=ArrayType(item_type=ExplorerParamType.INTEGER), ), ] @classmethod def execute(cls, organization, **kwargs): return "Processed"
ProcessItemsTool
python
airbytehq__airbyte
airbyte-integrations/connectors/source-linnworks/source_linnworks/source.py
{ "start": 451, "end": 3170 }
class ____(Oauth2Authenticator): def __init__( self, application_id: str, application_secret: str, token: str, token_expiry_date: pendulum.datetime = None, token_refresh_endpoint: str = "https://api.linnworks.net/api/Auth/AuthorizeByApplication", access_token_name: str = "Token", expires_in_name: str = "TTL", server_name: str = "Server", ): super().__init__( token_refresh_endpoint, application_id, application_secret, token, scopes=None, token_expiry_date=token_expiry_date, access_token_name=access_token_name, expires_in_name=expires_in_name, ) self.access_token_name = access_token_name self.application_id = application_id self.application_secret = application_secret self.expires_in_name = expires_in_name self.token = token self.server_name = server_name self.token_refresh_endpoint = token_refresh_endpoint def get_auth_header(self) -> Mapping[str, Any]: return {"Authorization": self.get_access_token()} def get_access_token(self): if self.token_has_expired(): t0 = pendulum.now() token, expires_in, server = self.refresh_access_token() self._access_token = token self._token_expiry_date = t0.add(seconds=expires_in) self._server = server return self._access_token def get_server(self): if self.token_has_expired(): self.get_access_token() return self._server def get_refresh_request_body(self) -> Mapping[str, Any]: payload: MutableMapping[str, Any] = { "applicationId": self.application_id, "applicationSecret": self.application_secret, "token": self.token, } return payload def refresh_access_token(self) -> Tuple[str, int]: try: response = requests.request(method="POST", url=self.token_refresh_endpoint, data=self.get_refresh_request_body()) response.raise_for_status() response_json = response.json() return response_json[self.access_token_name], response_json[self.expires_in_name], response_json[self.server_name] except Exception as e: try: e = Exception(response.json()["Message"]) except Exception: # Unable to get an error message from the response body. # Continue with the original error. pass raise Exception(f"Error while refreshing access token: {e}") from e
LinnworksAuthenticator
python
pytorch__pytorch
test/distributed/checkpoint/test_fsdp_optim_state.py
{ "start": 834, "end": 5062 }
class ____(DTensorTestBase): def _create_model(self): # make weight tensor dim_0 as large as the world size for scaling test layer1_weight_dim = self.world_size layer2_weight_dim = self.world_size * 2 layer3_weight_dim = self.world_size * 3 class TestDummyModel(torch.nn.Module): def __init__(self, device_type) -> None: super().__init__() self.device_type = device_type self.net1 = nn.Sequential(nn.Linear(8, layer1_weight_dim), nn.ReLU()) self.net2 = nn.Sequential( nn.Linear(layer1_weight_dim, layer2_weight_dim), nn.ReLU() ) self.net3 = nn.Sequential( nn.Linear(layer2_weight_dim, layer3_weight_dim), nn.ReLU() ) def forward(self, x): return self.net3(self.net2(self.net1(x))) def get_input(self): return torch.rand(8, 8, device=self.device_type) model = TestDummyModel(self.device_type).to(self.device_type) return model @property def backend(self): curr_backend = dist.get_default_backend_for_device(self.device_type) return f"cpu:gloo,{self.device_type}:{curr_backend}" @skip_if_lt_x_gpu(2) @with_comms @with_temp_dir @parametrize("pass_planner", [True, False]) def test_load_sharded_optimizer_state_dict(self, pass_planner) -> None: CHECKPOINT_DIR = self.temp_dir planner = dcp.DefaultLoadPlanner() if pass_planner else None model = self._create_model() model = FSDP(model) optim = torch.optim.Adam(model.parameters(), lr=0.1) # step ahead to initialize the optimizer model(model.get_input()).sum().backward() optim.step() FSDP.set_state_dict_type( model, StateDictType.SHARDED_STATE_DICT, ) optim_osd = FSDP.optim_state_dict(model, optim) state_dict = { "model": model.state_dict(), "optim": optim_osd, } dcp.save( state_dict=state_dict, storage_writer=dcp.FileSystemWriter(CHECKPOINT_DIR), ) # now load the model and ensure the values are the same model_2 = self._create_model() model_2 = FSDP(model_2) optim_2 = torch.optim.Adam(model_2.parameters(), lr=0.1) FSDP.set_state_dict_type( model_2, StateDictType.SHARDED_STATE_DICT, ) # Adam lazily creates its state self.assertEqual(0, len(optim_2.state)) state_dict = { "model": model_2.state_dict(), # cannot load the optimizer together with the model } dcp.load( state_dict=state_dict, storage_reader=dcp.FileSystemReader(CHECKPOINT_DIR), ) model_2.load_state_dict(state_dict["model"]) optim_state = load_sharded_optimizer_state_dict( model_state_dict=state_dict["model"], optimizer_key="optim", storage_reader=dcp.FileSystemReader(CHECKPOINT_DIR), planner=planner, ) flattened_osd = FSDP.optim_state_dict_to_load( model_2, optim_2, optim_state["optim"] ) optim_2.load_state_dict(flattened_osd) osd_after_load = FSDP.optim_state_dict(model_2, optim_2) # Compare optim_state_dict prior to save and after load before_optim_state = optim_osd["state"] after_optim_state = osd_after_load["state"] self.assertEqual(len(before_optim_state), len(after_optim_state)) for fqn, states in before_optim_state.items(): for state_name, state in states.items(): state2 = after_optim_state.get(fqn).get(state_name) if isinstance(state, ShardedTensor): self.assertTrue(isinstance(state2, ShardedTensor)) self.assertTrue(torch.allclose(state, state2)) else: self.assertEqual(state, state2) instantiate_parametrized_tests(FsdpOptimStateCheckpoint) if __name__ == "__main__": run_tests()
FsdpOptimStateCheckpoint
python
pytorch__pytorch
test/test_expanded_weights.py
{ "start": 1285, "end": 8829 }
class ____(TestCase): def test_forward_helper(self, device): input = torch.randn(3, 4, device=device) weight = torch.randn(5, 4, device=device) bias = torch.randn(5, device=device) for weight_batched, bias_batched in product([True, False], [True, False]): maybe_batched_weight = weight maybe_batched_bias = bias if weight_batched: maybe_batched_weight = ExpandedWeight( weight.clone().requires_grad_(), 3, loss_reduction="sum" ) if bias_batched: maybe_batched_bias = ExpandedWeight( bias.clone().requires_grad_(), 3, loss_reduction="sum" ) args = (input, maybe_batched_weight, maybe_batched_bias) expanded_args, expanded_kwargs = standard_kwargs(("bias",), args) res = forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) expected = nn.functional.linear(input, weight, bias) self.assertEqual(res, expected) self.assertEqual(len(expanded_args), 2) assert expanded_args[0] is args[0] # avoids property checks in assertEquals assert expanded_args[1] is args[1] # avoids property checks in assertEquals self.assertEqual(len(expanded_kwargs), 1) assert ( expanded_kwargs["bias"] is args[2] ) # avoids property checks in assertEquals def test_forward_helper_failure_args(self, device): weight = torch.randn(5, 4, device=device) bias = torch.randn(5, device=device) with self.assertRaisesRegex( RuntimeError, r"do not support inputs that are also ExpandedWeights." ): input = ExpandedWeight( torch.randn(3, 4, requires_grad=True), 3, loss_reduction="sum" ) expanded_args, expanded_kwargs = standard_kwargs( ("bias",), (input, weight, bias) ) forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) with self.assertRaisesRegex( RuntimeError, r"requires a Tensor as the first input" ): expanded_args, expanded_kwargs = standard_kwargs( ("bias",), (3, weight, bias) ) forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) with self.assertRaisesRegex( RuntimeError, r"requires a batch dimension but got an input of size 0" ): expanded_args, expanded_kwargs = standard_kwargs( ("bias",), (torch.tensor(3), weight, bias) ) forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) with self.assertRaisesRegex( RuntimeError, r"0 is not a valid batch size for Expanded Weights" ): expanded_args, expanded_kwargs = standard_kwargs( ("bias",), (torch.randn(0, 1, 2), weight, bias) ) forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) input = torch.randn(3, 4) for weight_batched, bias_batched in product([True, False], [True, False]): if not weight_batched and not bias_batched: continue maybe_batched_weight = weight maybe_batched_bias = bias if weight_batched: maybe_batched_weight = ExpandedWeight( weight.clone().requires_grad_(), 4, loss_reduction="sum" ) if bias_batched: maybe_batched_bias = ExpandedWeight( bias.clone().requires_grad_(), 4, loss_reduction="sum" ) with self.assertRaisesRegex( RuntimeError, r"Expected ExpandedWeights to have batch size matching input", ): expanded_args, expanded_kwargs = standard_kwargs( ("bias",), (input, maybe_batched_weight, maybe_batched_bias) ) forward_helper(nn.functional.linear, expanded_args, expanded_kwargs) def test_set_grad_sample_if_exists(self, device): def test_fn(a): return grad_sample orig_weight = torch.randn(4, device=device, requires_grad=True) expanded_weight = ExpandedWeight(orig_weight, 3, loss_reduction="sum") grad_sample = torch.randn(3) set_grad_sample_if_exists(expanded_weight, test_fn) self.assertTrue(hasattr(orig_weight, "grad_sample")) self.assertEqual(orig_weight.grad_sample, grad_sample) basic_tensor = torch.randn(4, device=device) set_grad_sample_if_exists(basic_tensor, test_fn) self.assertFalse(hasattr(basic_tensor, "grad_sample")) non_tensor = 3 set_grad_sample_if_exists(non_tensor, test_fn) self.assertFalse(hasattr(non_tensor, "grad_sample")) def test_set_grad_sample_if_exists_failure(self, device): def test_fn(a): return True grad_tensor = torch.randn(4, requires_grad=True, device=device) with self.assertRaisesRegex( RuntimeError, r"does not support a mixture of ExpandedWeight parameters and normal Parameters", ): set_grad_sample_if_exists(grad_tensor, test_fn) def test_unpack_expanded_weight_or_tensor(self, device): input = torch.randn(3, requires_grad=True, device=device) self.assertEqual( input, unpack_expanded_weight_or_tensor( ExpandedWeight(input, 3, loss_reduction="sum") ), ) input.requires_grad_(False) self.assertEqual(input, unpack_expanded_weight_or_tensor(input)) self.assertTrue(unpack_expanded_weight_or_tensor(4) is None) def test_unpack_expanded_weight_or_tensor_with_custom_function(self, device): input = torch.randn(3, requires_grad=True, device=device) self.assertTrue( unpack_expanded_weight_or_tensor( ExpandedWeight(input, 3, loss_reduction="sum"), lambda x: x is input ) ) input.requires_grad_(False) self.assertTrue(unpack_expanded_weight_or_tensor(input, lambda x: x is input)) self.assertTrue( unpack_expanded_weight_or_tensor(4, lambda x: x is input) is None ) def test_unpack_expanded_weight_or_tensor_failure(self, device): input = torch.randn(3, requires_grad=True, device=device) with self.assertRaisesRegex( RuntimeError, r"does not support a mixture of ExpandedWeight parameters and normal Parameters", ): unpack_expanded_weight_or_tensor(input) with self.assertRaisesRegex( RuntimeError, r"does not support a mixture of ExpandedWeight parameters and normal Parameters", ): unpack_expanded_weight_or_tensor(input, lambda x: x is input) def test_sum_over_all_but_batch_and_last_n(self, device): input = torch.randn(1, 2, 3, 4, 5, device=device) res = sum_over_all_but_batch_and_last_n(input, 2) expected = input.sum((1, 2)) self.assertEqual(res, expected) res = sum_over_all_but_batch_and_last_n(input, 0) expected = input.sum((1, 2, 3, 4)) self.assertEqual(res, expected) res = sum_over_all_but_batch_and_last_n(input, 4) self.assertEqual(res, input)
TestExpandedWeightHelperFunction
python
PyCQA__pylint
tests/regrtest_data/max_inferable_limit_for_classes/nodes/roles.py
{ "start": 115, "end": 160 }
class ____(SQLRole): ...
ColumnArgumentRole
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_config_repositories.py
{ "start": 82, "end": 657 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) org = self.create_organization(owner=self.user, name="baz") url = reverse("sentry-api-0-organization-config-repositories", args=[org.slug]) response = self.client.get(url, format="json") assert response.status_code == 200, response.content provider = list(filter(lambda x: x["id"] == "dummy", response.data["providers"]))[0] assert provider["name"] == "Example" assert provider["config"]
OrganizationConfigRepositoriesTest
python
walkccc__LeetCode
solutions/1215. Stepping Numbers/1215-2.py
{ "start": 0, "end": 465 }
class ____: def countSteppingNumbers(self, low: int, high: int) -> list[int]: ans = [0] if low == 0 else [] def dfs(curr: int) -> None: if curr > high: return if curr >= low: ans.append(curr) lastDigit = curr % 10 if lastDigit > 0: dfs(curr * 10 + lastDigit - 1) if lastDigit < 9: dfs(curr * 10 + lastDigit + 1) for i in range(1, 9 + 1): dfs(i) ans.sort() return ans
Solution